From a98223bf93261b32f32b91f9af9ebb207a95f800 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:50:30 +0000 Subject: [PATCH 01/16] ci(release): Move to Craft auto versioning Switch the Release workflow from action-prepare-release to getsentry/craft@v3 with the full bump set (auto, pre, patch, minor, major; default auto), an optional exact version override, and force, matching getsentry/junior. Craft reads the reachable vX.Y.Z-src tags as prereleases, so auto and bump types would promote 0.52.0-src to 0.52.0. Map the source tags back to vX.Y.Z in the job checkout before Craft runs. Set minVersion 3.9.0 so Craft allows auto, bump types, and pre. Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com> --- .craft.yml | 1 + .github/workflows/release.yml | 58 ++++++++++++----------------------- bin/craft-release-tags.sh | 31 +++++++++++++++++++ specs/release-process.md | 28 +++++++++-------- 4 files changed, 67 insertions(+), 51 deletions(-) create mode 100755 bin/craft-release-tags.sh diff --git a/.craft.yml b/.craft.yml index 0b71d7c99..6dcd2e16e 100644 --- a/.craft.yml +++ b/.craft.yml @@ -1,3 +1,4 @@ +minVersion: 3.9.0 changelog: policy: auto preReleaseCommand: bash bin/bump-version.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bdae30325..ddb934e67 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,20 +4,31 @@ on: workflow_dispatch: inputs: bump: - description: Version bump type + description: Version bump type (ignored when version is set). auto picks it from the commits; pre cuts a prerelease of that version. required: true type: choice - default: minor + default: auto options: - - minor + - auto + - pre - patch + - minor - major + version: + description: Exact version override (for example, 0.53.0) + required: false + type: string force: description: Force release (bypass blockers) required: false type: boolean default: false +permissions: + contents: read + # Craft writes AI changelog summaries with the workflow token. + copilot-requests: write + jobs: release: runs-on: ubuntu-latest @@ -41,45 +52,14 @@ jobs: node-version: '24' cache: 'pnpm' - - name: Calculate version - id: version - env: - BUMP: ${{ inputs.bump }} - run: | - CURRENT=$(node -p "require('./packages/warden/package.json').version") - NEW=$(npx semver -i "$BUMP" $CURRENT) - echo "current=$CURRENT" >> $GITHUB_OUTPUT - echo "new=$NEW" >> $GITHUB_OUTPUT - - # Craft uses `git describe --tags` to find the previous version. The - # published action tags point to detached dist/ artifact commits, so the - # previous release must have created a reachable source tag before Craft - # prepares the next changelog. - - name: Verify previous source tag - run: | - VERSION="${{ steps.version.outputs.current }}" - SOURCE_TAG="v${VERSION}-src" - - if ! git rev-parse "$SOURCE_TAG^{commit}" >/dev/null 2>&1; then - echo "::error::Missing source tag $SOURCE_TAG. The previous release did not finalize its source tag." - exit 1 - fi - - DESCRIBED_TAG="$(git describe --tags --abbrev=0)" - DESCRIBED_SHA="$(git rev-parse "$DESCRIBED_TAG^{commit}")" - SOURCE_SHA="$(git rev-parse "$SOURCE_TAG^{commit}")" - - if [ "$DESCRIBED_SHA" != "$SOURCE_SHA" ]; then - echo "::error::Expected git describe to resolve to $SOURCE_TAG ($SOURCE_SHA), got $DESCRIBED_TAG ($DESCRIBED_SHA)" - exit 1 - fi - - echo "Craft previous-release baseline: $DESCRIBED_TAG ($DESCRIBED_SHA)" + - name: Prepare Craft release tags + run: sh bin/craft-release-tags.sh - name: Prepare release - uses: getsentry/action-prepare-release@c8e1c2009ab08259029170132c384f03c1064c0e # v1 + uses: getsentry/craft@68615816cdad571fdc24b7d35f45238c835affc2 # v3.11.0 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: - version: ${{ steps.version.outputs.new }} + version: ${{ inputs.version || inputs.bump }} force: ${{ inputs.force }} + llm_api_key: ${{ github.token }} diff --git a/bin/craft-release-tags.sh b/bin/craft-release-tags.sh new file mode 100755 index 000000000..515551e73 --- /dev/null +++ b/bin/craft-release-tags.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Craft finds the previous release with `git describe --tags`. Published +# vX.Y.Z tags point to detached dist/action commits, so main only reaches the +# vX.Y.Z-src source tags. Craft reads those as prereleases (0.52.0-src), and +# `auto` or a bump type would then promote 0.52.0-src to 0.52.0. This script +# points each vX.Y.Z tag at its source commit in this checkout only, so Craft +# sees the real release history. Nothing is pushed. +set -eu + +current=$(node -p "require('./packages/warden/package.json').version") +source_tag="v${current}-src" + +if ! git rev-parse --verify --quiet "${source_tag}^{commit}" >/dev/null; then + echo "::error::Missing source tag $source_tag. The previous release did not finalize its source tag." + exit 1 +fi + +source_tags=$(git tag --list 'v*-src') +for tag in $source_tags; do + sha=$(git rev-parse "${tag}^{commit}") + git tag --force "${tag%-src}" "$sha" >/dev/null + git tag --delete "$tag" >/dev/null +done + +described=$(git describe --tags --abbrev=0 --match 'v*') +if [ "$described" != "v$current" ]; then + echo "::error::Expected git describe to resolve to v$current, got $described" + exit 1 +fi + +echo "Craft previous-release baseline: $described" diff --git a/specs/release-process.md b/specs/release-process.md index 090229249..2cf9215e5 100644 --- a/specs/release-process.md +++ b/specs/release-process.md @@ -41,22 +41,25 @@ All of `dist/` is gitignored. No exceptions, no whitelist. Build artifacts never ### 1. Trigger -A maintainer runs the **Release** workflow (`release.yml`) via `workflow_dispatch`, choosing a semver bump type (patch, minor, major). +A maintainer runs the **Release** workflow (`release.yml`) via `workflow_dispatch`, choosing a bump type (`auto`, `pre`, `patch`, `minor`, `major`; default `auto`) or an exact `version` override. `auto` picks the bump from the commits since the last stable release. `pre` cuts a prerelease of the version `auto` would release. -### 2. Previous source tag preflight +### 2. Map source tags for Craft -Before preparing the release, the workflow verifies that the current version has a source tag (`vX.Y.Z-src`) and that `git describe --tags --abbrev=0` resolves to that same commit. This is required because the published version tags point to detached action artifact commits that are not ancestors of main. +Craft resolves the version and changelog from the latest tag that `git describe --tags` reaches. The published version tags point to detached action artifact commits that are not ancestors of main, and Craft reads `vX.Y.Z-src` as a prerelease. Without a fix, `auto` or a bump type would turn `0.52.0-src` into `0.52.0`, and the changelog would start from an old reachable tag. -The release workflow does not create this tag. It fails fast if the previous release did not finalize its source tag, preventing Craft from generating a full-history changelog from an old reachable tag. +`bin/craft-release-tags.sh` verifies that the current version has a source tag (`vX.Y.Z-src`). It then points each `vX.Y.Z` tag at its source commit in the job checkout, deletes the local `-src` tags, and checks that `git describe` resolves to `vX.Y.Z`. Nothing is pushed. + +The release workflow does not create the source tag. It fails fast if the previous release did not finalize its source tag. ### 3. Prepare release PR -The workflow runs `getsentry/action-prepare-release@v1` which: +The workflow runs `getsentry/craft@v3` which: -1. Runs `preReleaseCommand` from `.craft.yml` (`bash bin/bump-version.sh`) -2. `bump-version.sh` bumps `packages/warden/package.json`, installs deps, and runs `pnpm build` as a compilation check -3. Since `dist/` is gitignored, only package metadata and lockfile changes are committed -4. A PR is opened on a `releases/X.Y.Z` branch +1. Resolves the version from the `version` input or the bump type +2. Runs `preReleaseCommand` from `.craft.yml` (`bash bin/bump-version.sh`) +3. `bump-version.sh` bumps `packages/warden/package.json`, installs deps, and runs `pnpm build` as a compilation check +4. Since `dist/` is gitignored, only package metadata and lockfile changes are committed +5. A PR is opened on a `releases/X.Y.Z` branch ### 4. CI builds the npm tarball @@ -103,7 +106,7 @@ After this step, `vX.Y.Z` and `vX` point to a detached commit that is NOT on mai workflow_dispatch | v -release.yml: verify current -src tag, prepare PR (bump version) +release.yml: map -src tags, prepare PR (resolve and bump version) | v CI: build, test, pack tarball, upload artifact @@ -143,9 +146,10 @@ Controls what goes into the npm tarball. Key exclusions: | File | Role | |------|------| -| `.craft.yml` | Craft config: `preReleaseCommand`, targets (github, npm) | +| `.craft.yml` | Craft config: `minVersion`, `preReleaseCommand`, targets (github, npm) | +| `bin/craft-release-tags.sh` | Verifies the previous `-src` tag and maps source tags for Craft | | `bin/bump-version.sh` | Version bump + build validation for release PR | -| `.github/workflows/release.yml` | Triggers release PR creation, verifies the previous `-src` tag | +| `.github/workflows/release.yml` | Triggers release PR creation | | `.github/workflows/ci.yml` | Builds tarball for npm, validates ncc build | | `.github/workflows/update-major-tag.yml` | Creates `-src` tags, builds ncc bundle, commits to release tags | | `action.yml` | GitHub Action definition, references `dist/action/index.js` | From 85ffac609e42c48096b11e00b8434d966b0dc81f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:06:23 +0000 Subject: [PATCH 02/16] ci(release): Use floating getsentry/craft@v3 tag --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ddb934e67..0d519b086 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -56,7 +56,7 @@ jobs: run: sh bin/craft-release-tags.sh - name: Prepare release - uses: getsentry/craft@68615816cdad571fdc24b7d35f45238c835affc2 # v3.11.0 + uses: getsentry/craft@v3 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: From ff783f7c4ea88e4f4061e1d5c0646b413b8b5380 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:07:52 +0000 Subject: [PATCH 03/16] ci(release): Keep major Action tag off prereleases A pre release publishes a GitHub Release, and update-major-tag.yml moved v0 to it, so @v0 users would run the prerelease. Move the bundle commit and tag updates into bin/publish-action-bundle.sh and skip the major tag when the version has a prerelease suffix. --- .github/workflows/update-major-tag.yml | 23 +---------------- bin/publish-action-bundle.sh | 35 ++++++++++++++++++++++++++ specs/release-process.md | 5 +++- 3 files changed, 40 insertions(+), 23 deletions(-) create mode 100755 bin/publish-action-bundle.sh diff --git a/.github/workflows/update-major-tag.yml b/.github/workflows/update-major-tag.yml index b64193c0b..26c63a36b 100644 --- a/.github/workflows/update-major-tag.yml +++ b/.github/workflows/update-major-tag.yml @@ -60,25 +60,4 @@ jobs: run: pnpm build:action - name: Commit bundle and update tags - run: | - VERSION="${GITHUB_REF_NAME#v}" - MAJOR="v${VERSION%%.*}" - - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - - # Stage only the bundle files needed by the action - git add -f dist/action/index.js dist/action/licenses.txt dist/action/package.json - # Add chunk and asset files if ncc produced any - git add -f dist/action/*.index.js dist/action/*.wasm 2>/dev/null || true - - # Skip commit if bundle is already present (idempotent re-runs) - git diff --cached --quiet || git commit -m "Build dist/action for $GITHUB_REF_NAME" - - # Update version tag to include the bundle - git tag -fa "$GITHUB_REF_NAME" -m "Release $GITHUB_REF_NAME" - git push -f origin "$GITHUB_REF_NAME" - - # Update major version tag - git tag -fa "$MAJOR" -m "Update $MAJOR to $GITHUB_REF_NAME" - git push -f origin "$MAJOR" + run: sh bin/publish-action-bundle.sh diff --git a/bin/publish-action-bundle.sh b/bin/publish-action-bundle.sh new file mode 100755 index 000000000..795d483f8 --- /dev/null +++ b/bin/publish-action-bundle.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Commits the ncc bundle onto the release tag and moves the version tag to it. +# The major tag (vX) moves only for stable releases, so `@v0` users never get +# a prerelease. Expects GITHUB_REF_NAME to be the release tag (vX.Y.Z). +set -eu + +tag="$GITHUB_REF_NAME" +version="${tag#v}" +major="v${version%%.*}" + +git config user.name "github-actions[bot]" +git config user.email "github-actions[bot]@users.noreply.github.com" + +# Stage only the bundle files needed by the action +git add -f dist/action/index.js dist/action/licenses.txt dist/action/package.json +# Add chunk and asset files if ncc produced any +git add -f dist/action/*.index.js dist/action/*.wasm 2>/dev/null || true + +# Skip commit if bundle is already present (idempotent re-runs) +if ! git diff --cached --quiet; then + git commit -m "Build dist/action for $tag" +fi + +git tag -fa "$tag" -m "Release $tag" +git push -f origin "$tag" + +case "$version" in + *-*) + echo "Prerelease $tag: leaving $major unchanged" + ;; + *) + git tag -fa "$major" -m "Update $major to $tag" + git push -f origin "$major" + ;; +esac diff --git a/specs/release-process.md b/specs/release-process.md index 2cf9215e5..daf098130 100644 --- a/specs/release-process.md +++ b/specs/release-process.md @@ -96,7 +96,9 @@ Triggered by `release: published`. This is where the GitHub Action bundle gets b 3. Installs dependencies and runs `pnpm build:action` 4. Commits only the ncc bundle files (`index.js`, chunk files, `licenses.txt`, `package.json`) via `git add -f` 5. Force-updates `vX.Y.Z` to point to this new commit -6. Force-updates the major tag (`vX`) to the same commit +6. Force-updates the major tag (`vX`) to the same commit, for stable releases only. Prereleases (`vX.Y.Z-alpha.N`) leave `vX` unchanged. + +Steps 4 to 6 run in `bin/publish-action-bundle.sh`. After this step, `vX.Y.Z` and `vX` point to a detached commit that is NOT on main. This commit has everything from the source release plus `dist/action/`. The `vX.Y.Z-src` tag remains on the source release commit so Craft can find the previous release from main during the next prepare run. @@ -152,6 +154,7 @@ Controls what goes into the npm tarball. Key exclusions: | `.github/workflows/release.yml` | Triggers release PR creation | | `.github/workflows/ci.yml` | Builds tarball for npm, validates ncc build | | `.github/workflows/update-major-tag.yml` | Creates `-src` tags, builds ncc bundle, commits to release tags | +| `bin/publish-action-bundle.sh` | Commits the ncc bundle and moves the version tag, and `vX` for stable releases | | `action.yml` | GitHub Action definition, references `dist/action/index.js` | | `.gitignore` | Ignores all of `dist/` | | `packages/warden/.npmignore` | Excludes non-library files from npm tarball | From fc782755823728566d76e2e63b02f2e2137efff1 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:14:52 +0000 Subject: [PATCH 04/16] ci(release): Commit the action bundle and drop detached release tags Craft could not read warden's releases because each vX.Y.Z tag pointed at a detached commit holding dist/action, so main only reached vX.Y.Z-src. Commit the ncc bundle to main instead and check its freshness in CI, so Craft's github target tags a release commit that main reaches. - Track dist/action bundle files, mark them linguist-generated - CI fails when a rebuilt bundle differs from the committed one - Remove the tag remap, -src tags and the detached bundle commit - update-major-tag.yml only moves vX, and skips prereleases Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com> --- .gitattributes | 1 + .github/workflows/ci.yml | 2 + .github/workflows/release.yml | 3 - .github/workflows/update-major-tag.yml | 48 +--------- .gitignore | 9 ++ AGENTS.md | 2 +- CONTRIBUTING.md | 11 +++ bin/check-action-dist.sh | 12 +++ bin/craft-release-tags.sh | 31 ------- bin/publish-action-bundle.sh | 35 -------- bin/update-major-tag.sh | 20 +++++ specs/release-process.md | 116 +++++++++++-------------- 12 files changed, 107 insertions(+), 183 deletions(-) create mode 100644 .gitattributes create mode 100755 bin/check-action-dist.sh delete mode 100755 bin/craft-release-tags.sh delete mode 100755 bin/publish-action-bundle.sh create mode 100755 bin/update-major-tag.sh diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..0fafeaf61 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +dist/action/** linguist-generated=true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f33036a89..ac27c61cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,8 @@ jobs: fail-ci-if-error: true - run: pnpm build - run: pnpm build:action + - name: Check action bundle is committed + run: sh bin/check-action-dist.sh - name: Smoke test action built-in skill resolution run: | GITHUB_ACTION_PATH="$PWD" node --input-type=module -e " diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d519b086..36232b78b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -52,9 +52,6 @@ jobs: node-version: '24' cache: 'pnpm' - - name: Prepare Craft release tags - run: sh bin/craft-release-tags.sh - - name: Prepare release uses: getsentry/craft@v3 env: diff --git a/.github/workflows/update-major-tag.yml b/.github/workflows/update-major-tag.yml index 26c63a36b..32a603a75 100644 --- a/.github/workflows/update-major-tag.yml +++ b/.github/workflows/update-major-tag.yml @@ -14,50 +14,6 @@ jobs: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: ref: ${{ github.event.release.tag_name }} - fetch-depth: 0 - fetch-tags: true - - name: Ensure source release tag - run: | - VERSION="${GITHUB_REF_NAME#v}" - SOURCE_TAG="v${VERSION}-src" - ARTIFACT_SUBJECT="Build dist/action for $GITHUB_REF_NAME" - SOURCE_SHA="$(git rev-parse HEAD)" - - while [ "$(git show -s --format=%s "$SOURCE_SHA")" = "$ARTIFACT_SUBJECT" ]; do - SOURCE_SHA="$(git rev-parse "$SOURCE_SHA^")" - echo "Detected existing artifact commit. Walking back to $SOURCE_SHA for $SOURCE_TAG" - done - - if git rev-parse "$SOURCE_TAG^{commit}" >/dev/null 2>&1; then - EXISTING_SHA="$(git rev-parse "$SOURCE_TAG^{commit}")" - if [ "$EXISTING_SHA" = "$SOURCE_SHA" ]; then - echo "Source tag $SOURCE_TAG already points to $SOURCE_SHA" - exit 0 - fi - - echo "::error::Source tag $SOURCE_TAG points to $EXISTING_SHA, expected $SOURCE_SHA" - exit 1 - fi - - echo "Creating source tag $SOURCE_TAG on $SOURCE_SHA" - git tag "$SOURCE_TAG" "$SOURCE_SHA" - git push origin "refs/tags/$SOURCE_TAG" - - - uses: pnpm/action-setup@02f6c237bd2518259fed6c71566509edfb3f2b74 # v4 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: '24' - cache: 'pnpm' - - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Build service API - run: pnpm --filter @sentry/warden-service-api build - - - name: Build action bundle - run: pnpm build:action - - - name: Commit bundle and update tags - run: sh bin/publish-action-bundle.sh + - name: Update major tag + run: sh bin/update-major-tag.sh diff --git a/.gitignore b/.gitignore index d1182ef68..12e567a32 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,15 @@ node_modules/ # Build output dist/ +# The GitHub Action runs from the committed ncc bundle. CI checks that it is fresh. +!/dist/ +/dist/* +!/dist/action/ +/dist/action/** +!/dist/action/*.js +!/dist/action/*.wasm +!/dist/action/licenses.txt +!/dist/action/package.json *.tgz # IDE diff --git a/AGENTS.md b/AGENTS.md index 2235d5023..f917bd02f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,7 @@ Use `/testing-guidelines` when writing tests. Key principles: ## Build & Dist -All of `dist/` is gitignored. The ncc action bundle (`dist/action/`) is built and committed to release tags only by the `update-major-tag` workflow. Never commit build artifacts to main. +The ncc action bundle (`dist/action/`) is committed so every commit and release tag can run as an Action. After changing code the Action bundles, run `pnpm build:action` and commit `dist/action/`. CI fails when it is stale. The rest of `dist/` is gitignored. See `specs/release-process.md`. ## Verifying Changes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 31377ea03..2fb9779f5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,6 +23,17 @@ pnpm test # Run unit tests in watch mode pnpm test:run # Run unit tests once ``` +## GitHub Action Bundle + +The Action runs from the ncc bundle in `dist/action/`, which is committed. After you change code under `packages/warden/src/` (or its dependencies), rebuild and commit it: + +```bash +pnpm build:action +git add dist/action +``` + +CI rebuilds the bundle and fails when the committed files differ. + ## Testing Locally The CLI runs skills against local git changes. Set up your API key and run it: diff --git a/bin/check-action-dist.sh b/bin/check-action-dist.sh new file mode 100755 index 000000000..115670080 --- /dev/null +++ b/bin/check-action-dist.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Fails when the committed GitHub Action bundle differs from a fresh +# `pnpm build:action`. Run after the build. +set -eu + +dist=dist/action +changes=$(git status --porcelain --untracked-files=all -- "$dist") +if [ -n "$changes" ]; then + echo "::error::$dist is out of date. Run 'pnpm build:action' and commit $dist." + printf '%s\n' "$changes" + exit 1 +fi diff --git a/bin/craft-release-tags.sh b/bin/craft-release-tags.sh deleted file mode 100755 index 515551e73..000000000 --- a/bin/craft-release-tags.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# Craft finds the previous release with `git describe --tags`. Published -# vX.Y.Z tags point to detached dist/action commits, so main only reaches the -# vX.Y.Z-src source tags. Craft reads those as prereleases (0.52.0-src), and -# `auto` or a bump type would then promote 0.52.0-src to 0.52.0. This script -# points each vX.Y.Z tag at its source commit in this checkout only, so Craft -# sees the real release history. Nothing is pushed. -set -eu - -current=$(node -p "require('./packages/warden/package.json').version") -source_tag="v${current}-src" - -if ! git rev-parse --verify --quiet "${source_tag}^{commit}" >/dev/null; then - echo "::error::Missing source tag $source_tag. The previous release did not finalize its source tag." - exit 1 -fi - -source_tags=$(git tag --list 'v*-src') -for tag in $source_tags; do - sha=$(git rev-parse "${tag}^{commit}") - git tag --force "${tag%-src}" "$sha" >/dev/null - git tag --delete "$tag" >/dev/null -done - -described=$(git describe --tags --abbrev=0 --match 'v*') -if [ "$described" != "v$current" ]; then - echo "::error::Expected git describe to resolve to v$current, got $described" - exit 1 -fi - -echo "Craft previous-release baseline: $described" diff --git a/bin/publish-action-bundle.sh b/bin/publish-action-bundle.sh deleted file mode 100755 index 795d483f8..000000000 --- a/bin/publish-action-bundle.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Commits the ncc bundle onto the release tag and moves the version tag to it. -# The major tag (vX) moves only for stable releases, so `@v0` users never get -# a prerelease. Expects GITHUB_REF_NAME to be the release tag (vX.Y.Z). -set -eu - -tag="$GITHUB_REF_NAME" -version="${tag#v}" -major="v${version%%.*}" - -git config user.name "github-actions[bot]" -git config user.email "github-actions[bot]@users.noreply.github.com" - -# Stage only the bundle files needed by the action -git add -f dist/action/index.js dist/action/licenses.txt dist/action/package.json -# Add chunk and asset files if ncc produced any -git add -f dist/action/*.index.js dist/action/*.wasm 2>/dev/null || true - -# Skip commit if bundle is already present (idempotent re-runs) -if ! git diff --cached --quiet; then - git commit -m "Build dist/action for $tag" -fi - -git tag -fa "$tag" -m "Release $tag" -git push -f origin "$tag" - -case "$version" in - *-*) - echo "Prerelease $tag: leaving $major unchanged" - ;; - *) - git tag -fa "$major" -m "Update $major to $tag" - git push -f origin "$major" - ;; -esac diff --git a/bin/update-major-tag.sh b/bin/update-major-tag.sh new file mode 100755 index 000000000..bc7890949 --- /dev/null +++ b/bin/update-major-tag.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Points the major tag (vX) at the release tag. Prereleases leave it alone so +# `@v0` users never get one. Expects GITHUB_REF_NAME to be the release tag. +set -eu + +tag="$GITHUB_REF_NAME" +version="${tag#v}" +major="v${version%%.*}" + +case "$version" in + *-*) + echo "Prerelease $tag: leaving $major unchanged" + exit 0 + ;; +esac + +git config user.name "github-actions[bot]" +git config user.email "github-actions[bot]@users.noreply.github.com" +git tag -fa "$major" -m "Update $major to $tag" HEAD +git push -f origin "refs/tags/$major" diff --git a/specs/release-process.md b/specs/release-process.md index daf098130..5c77c1455 100644 --- a/specs/release-process.md +++ b/specs/release-process.md @@ -6,14 +6,12 @@ How Warden gets from source to published artifacts. ## Artifacts -Warden ships two independent artifacts from the same repo: +Warden ships two artifacts from the same repo: | Artifact | Consumers | Built by | Published via | |----------|-----------|----------|--------------| | **npm package** (`@sentry/warden`) | CLI users, library consumers | `tsc` + `pnpm --filter @sentry/warden pack` in CI | Craft downloads CI tarball, publishes to npm | -| **GitHub Action** (`getsentry/warden@v0`) | GitHub Action users | `ncc` in `update-major-tag` workflow | Force-pushed to release tags | - -Neither artifact is committed to main. All of `dist/` is gitignored. +| **GitHub Action** (`getsentry/warden@v0`) | GitHub Action users | `ncc` (`pnpm build:action`), committed to main | Craft tags the release commit | ## Build Commands @@ -22,20 +20,22 @@ Neither artifact is committed to main. All of `dist/` is gitignored. | `pnpm build` | `packages/warden/dist/` (tsc) | Library + CLI for npm | | `pnpm build:action` | `dist/action/` (ncc) | Self-contained GitHub Action bundle | -The ncc bundle is built with `--no-source-map-register`. No sourcemaps, declaration files, or type maps should ever appear in git history. +The ncc bundle is built with `--no-source-map-register`. Only the bundle files (`dist/action/*.js`, `*.wasm`, `licenses.txt`, `package.json`) are committed. Declaration files and maps stay gitignored. ## What Lives Where ``` -main branch Source + action.yml. No dist/. -v0.7.0 tag Source + action.yml + dist/action/ (ncc bundle only). -v0 tag Same commit as latest v0.x.y tag. +main branch Source + action.yml + dist/action/ (ncc bundle). +vX.Y.Z tag The release commit on main. Same layout as main. +v0 tag Same commit as the latest stable v0.x.y tag. npm tarball packages/warden/dist/ (tsc output) plus runtime skill assets. No dist/action/. ``` -## Gitignore Policy +## Action Bundle Policy + +`dist/action/` is committed so every commit, including every release tag, can run as an Action. `.gitattributes` marks it `linguist-generated`, so GitHub collapses it in diffs. -All of `dist/` is gitignored. No exceptions, no whitelist. Build artifacts never land on main. +Contributors who change code that the Action bundles run `pnpm build:action` and commit `dist/action/`. CI rebuilds the bundle and `bin/check-action-dist.sh` fails when the committed files differ. The rest of `dist/` stays gitignored. ## Release Flow @@ -43,64 +43,42 @@ All of `dist/` is gitignored. No exceptions, no whitelist. Build artifacts never A maintainer runs the **Release** workflow (`release.yml`) via `workflow_dispatch`, choosing a bump type (`auto`, `pre`, `patch`, `minor`, `major`; default `auto`) or an exact `version` override. `auto` picks the bump from the commits since the last stable release. `pre` cuts a prerelease of the version `auto` would release. -### 2. Map source tags for Craft - -Craft resolves the version and changelog from the latest tag that `git describe --tags` reaches. The published version tags point to detached action artifact commits that are not ancestors of main, and Craft reads `vX.Y.Z-src` as a prerelease. Without a fix, `auto` or a bump type would turn `0.52.0-src` into `0.52.0`, and the changelog would start from an old reachable tag. - -`bin/craft-release-tags.sh` verifies that the current version has a source tag (`vX.Y.Z-src`). It then points each `vX.Y.Z` tag at its source commit in the job checkout, deletes the local `-src` tags, and checks that `git describe` resolves to `vX.Y.Z`. Nothing is pushed. +Craft finds the previous release with `git describe --tags`, so release tags must be reachable from main. They are, because Craft tags the release commit and merges the release branch back into main. -The release workflow does not create the source tag. It fails fast if the previous release did not finalize its source tag. - -### 3. Prepare release PR +### 2. Prepare the release branch The workflow runs `getsentry/craft@v3` which: 1. Resolves the version from the `version` input or the bump type 2. Runs `preReleaseCommand` from `.craft.yml` (`bash bin/bump-version.sh`) -3. `bump-version.sh` bumps `packages/warden/package.json`, installs deps, and runs `pnpm build` as a compilation check -4. Since `dist/` is gitignored, only package metadata and lockfile changes are committed -5. A PR is opened on a `releases/X.Y.Z` branch +3. `bump-version.sh` bumps the package versions, installs deps, and runs `pnpm build` as a compilation check +4. Commits the version bump and changelog on a `release/X.Y.Z` branch +5. Opens a publish request in `getsentry/publish` -### 4. CI builds the npm tarball +### 3. CI builds the npm tarball -CI (`ci.yml`) runs on the release branch push and again on merge to main: +CI (`ci.yml`) runs on the release branch push: 1. Builds tsc output (`pnpm build`) -2. Builds ncc bundle (`pnpm build:action`) as a validation step +2. Builds the ncc bundle (`pnpm build:action`) and checks that it matches the committed `dist/action/` 3. Creates a tarball (`pnpm --filter @sentry/warden pack`) which respects `packages/warden/.npmignore` 4. Uploads the tarball as a GitHub Actions artifact The package `.npmignore` excludes `action.yml`, non-runtime source files, tests, and dev config. The tarball contains the tsc-compiled library and CLI plus runtime skill assets. -### 5. Merge - -A maintainer reviews and merges the release PR into main. Main gets the version bump in `packages/warden/package.json` and lockfile updates, but no build artifacts. - -### 6. Craft publishes - -After merge, Craft: +### 4. Craft publishes -1. Creates git tag `vX.Y.Z` on the source release commit -2. Creates a GitHub Release (triggers step 7) -3. Downloads the npm tarball from CI artifacts -4. Publishes the tarball to npm (no build happens here) +After a maintainer approves the publish request, Craft: -Craft's npm target publishes pre-built tarballs. It does not check out code or run builds at publish time. +1. Creates the GitHub Release and tag `vX.Y.Z` on the release commit (triggers step 5) +2. Downloads the npm tarball from CI artifacts and publishes it to npm +3. Merges the release branch into main, so `vX.Y.Z` is reachable from main -### 7. Tag update (update-major-tag.yml) +Craft's npm target publishes pre-built tarballs. It does not run builds at publish time. -Triggered by `release: published`. This is where the GitHub Action bundle gets built: +### 5. Major tag update (update-major-tag.yml) -1. Checks out the `vX.Y.Z` tag -2. Creates the immutable source tag (`vX.Y.Z-src`) on the checked-out source commit -3. Installs dependencies and runs `pnpm build:action` -4. Commits only the ncc bundle files (`index.js`, chunk files, `licenses.txt`, `package.json`) via `git add -f` -5. Force-updates `vX.Y.Z` to point to this new commit -6. Force-updates the major tag (`vX`) to the same commit, for stable releases only. Prereleases (`vX.Y.Z-alpha.N`) leave `vX` unchanged. - -Steps 4 to 6 run in `bin/publish-action-bundle.sh`. - -After this step, `vX.Y.Z` and `vX` point to a detached commit that is NOT on main. This commit has everything from the source release plus `dist/action/`. The `vX.Y.Z-src` tag remains on the source release commit so Craft can find the previous release from main during the next prepare run. +Triggered by `release: published`. `bin/update-major-tag.sh` force-updates the major tag (`vX`) to the release commit. Prereleases (`vX.Y.Z-alpha.N`) leave `vX` unchanged, so `@v0` users never get a prerelease. ## Sequencing @@ -108,31 +86,34 @@ After this step, `vX.Y.Z` and `vX` point to a detached commit that is NOT on mai workflow_dispatch | v -release.yml: map -src tags, prepare PR (resolve and bump version) - | - v -CI: build, test, pack tarball, upload artifact +release.yml: Craft resolves the version, pushes release/X.Y.Z | v -Maintainer merges releases/X.Y.Z -> main +CI: build, test, check dist/action, pack tarball, upload artifact | v -CI: build + pack on main (tarball for Craft) +Maintainer approves the publish request | v -Craft: tag vX.Y.Z, GitHub Release, download tarball, publish npm +Craft: tag vX.Y.Z, GitHub Release, publish npm, merge into main | v -update-major-tag.yml: create vX.Y.Z-src, build ncc, commit to tag, force-update vX.Y.Z + vX +update-major-tag.yml: move vX (stable releases only) ``` -## Timing and failure modes +## Transition from detached tags + +Releases up to 0.52.0 used a different layout. `dist/` was gitignored, a workflow committed the bundle on top of each release tag, and it force-moved `vX.Y.Z` and `v0` to that detached commit. A `vX.Y.Z-src` tag marked the source commit. Those tags stay as they are. + +main reaches only the old `vX.Y.Z-src` tags and `v0.46.0`. Craft reads `0.52.0-src` as a prerelease, so `auto` and bump types would resolve to `0.52.0` again. **Run the first release with an exact `version` (for example `0.53.0`).** Its changelog starts at `v0.46.0`, the latest stable tag main reaches, so remove the 0.47.0 to 0.52.0 entries from the release branch before you approve the publish request. After that release, `auto` works. + +## Failure modes -**Tag update window**: There is a 1-3 minute window between Craft creating the GitHub Release and the tag workflow finishing. During this window, the version and major tags point to a commit without `dist/action/`. Any GitHub Action runs that resolve the tag during this window will fail. Existing users with cached action versions are unaffected. +**Stale bundle**: CI fails on the PR until `dist/action/` is rebuilt and committed. -**Tag workflow failure**: If `update-major-tag.yml` fails before creating the source tag, the next release prepare run will fail fast because the previous source tag is missing. If it fails after creating the source tag but before updating the artifact tags (build error, permission issue), changelog generation for the next release remains safe, but the GitHub Action tag may point to a commit without the ncc bundle. Recovery: fix the issue and re-run the workflow from the Actions tab. +**Major tag workflow failure**: `vX` keeps pointing at the previous stable release. Re-run the workflow from the Actions tab. -**npm publish is independent**: The npm tarball is built by CI and published by Craft before the tag workflow runs. A tag workflow failure does not affect npm. +**npm publish is independent**: The npm tarball is built by CI. A major tag failure does not affect npm. ## .npmignore @@ -149,14 +130,15 @@ Controls what goes into the npm tarball. Key exclusions: | File | Role | |------|------| | `.craft.yml` | Craft config: `minVersion`, `preReleaseCommand`, targets (github, npm) | -| `bin/craft-release-tags.sh` | Verifies the previous `-src` tag and maps source tags for Craft | -| `bin/bump-version.sh` | Version bump + build validation for release PR | -| `.github/workflows/release.yml` | Triggers release PR creation | -| `.github/workflows/ci.yml` | Builds tarball for npm, validates ncc build | -| `.github/workflows/update-major-tag.yml` | Creates `-src` tags, builds ncc bundle, commits to release tags | -| `bin/publish-action-bundle.sh` | Commits the ncc bundle and moves the version tag, and `vX` for stable releases | +| `bin/bump-version.sh` | Version bump + build validation for the release branch | +| `bin/check-action-dist.sh` | Fails when the committed `dist/action/` is stale | +| `bin/update-major-tag.sh` | Moves `vX` to the release, skipping prereleases | +| `.github/workflows/release.yml` | Runs Craft to prepare the release | +| `.github/workflows/ci.yml` | Builds tarball for npm, checks the action bundle | +| `.github/workflows/update-major-tag.yml` | Runs `bin/update-major-tag.sh` on published releases | | `action.yml` | GitHub Action definition, references `dist/action/index.js` | -| `.gitignore` | Ignores all of `dist/` | +| `.gitignore` | Ignores `dist/` except the committed action bundle files | +| `.gitattributes` | Marks `dist/action/` as generated | | `packages/warden/.npmignore` | Excludes non-library files from npm tarball | | `package.json` | Workspace scripts that delegate to `packages/warden` | | `packages/warden/package.json` | Package metadata and build scripts (`build`, `build:action`) | From 9b908fbcde3dda39abf61a2e6741ac5db77ebaed Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:18:43 +0000 Subject: [PATCH 05/16] build(action): Commit the ncc action bundle (part 1) Built with pnpm build:action from the current sources (unchanged from main 95d26a7). The files are byte-identical to the v0.52.0 bundle, and Node 22 and Node 24 builds match. Split in parts to fit the push size limit. Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com> --- dist/action/114.index.js | 486 + dist/action/117.index.js | 46 + dist/action/144.index.js | 458 + dist/action/181.index.js | 24 + dist/action/192.index.js | 78 + dist/action/211.index.js | 19236 +++++++++++++++ dist/action/213.index.js | 449 + dist/action/240.index.js | 58 + dist/action/286.index.js | 363 + dist/action/319.index.js | 318 + dist/action/329.index.js | 17334 +++++++++++++ dist/action/373.index.js | 363 + dist/action/428.index.js | 7498 ++++++ dist/action/451.index.js | 210 + dist/action/453.index.js | 24 + dist/action/508.index.js | 3100 +++ dist/action/53.index.js | 5213 ++++ dist/action/548.index.js | 1763 ++ dist/action/550.index.js | 215 + dist/action/592.index.js | 81 + dist/action/599.index.js | 554 + dist/action/627.index.js | 257 + dist/action/629.index.js | 820 + dist/action/643.index.js | 1356 ++ dist/action/663.index.js | 3912 +++ dist/action/666.index.js | 1387 ++ dist/action/702.index.js | 4533 ++++ dist/action/730.index.js | 13 + dist/action/731.index.js | 290 + dist/action/758.index.js | 48505 +++++++++++++++++++++++++++++++++++++ dist/action/786.index.js | 1478 ++ dist/action/804.index.js | 699 + dist/action/813.index.js | 47868 ++++++++++++++++++++++++++++++++++++ dist/action/833.index.js | 37808 +++++++++++++++++++++++++++++ dist/action/834.index.js | 24 + dist/action/883.index.js | 58 + dist/action/899.index.js | 57 + dist/action/923.index.js | 777 + dist/action/936.index.js | 35 + dist/action/942.index.js | 1760 ++ dist/action/967.index.js | 11608 +++++++++ dist/action/973.index.js | 25 + dist/action/978.index.js | 12 + dist/action/980.index.js | 396 + dist/action/index.js | 848 + dist/action/licenses.txt | 10567 ++++++++ dist/action/package.json | 1 + 47 files changed, 232965 insertions(+) create mode 100644 dist/action/114.index.js create mode 100644 dist/action/117.index.js create mode 100644 dist/action/144.index.js create mode 100644 dist/action/181.index.js create mode 100644 dist/action/192.index.js create mode 100644 dist/action/211.index.js create mode 100644 dist/action/213.index.js create mode 100644 dist/action/240.index.js create mode 100644 dist/action/286.index.js create mode 100644 dist/action/319.index.js create mode 100644 dist/action/329.index.js create mode 100644 dist/action/373.index.js create mode 100644 dist/action/428.index.js create mode 100644 dist/action/451.index.js create mode 100644 dist/action/453.index.js create mode 100644 dist/action/508.index.js create mode 100644 dist/action/53.index.js create mode 100644 dist/action/548.index.js create mode 100644 dist/action/550.index.js create mode 100644 dist/action/592.index.js create mode 100644 dist/action/599.index.js create mode 100644 dist/action/627.index.js create mode 100644 dist/action/629.index.js create mode 100644 dist/action/643.index.js create mode 100644 dist/action/663.index.js create mode 100644 dist/action/666.index.js create mode 100644 dist/action/702.index.js create mode 100644 dist/action/730.index.js create mode 100644 dist/action/731.index.js create mode 100644 dist/action/758.index.js create mode 100644 dist/action/786.index.js create mode 100644 dist/action/804.index.js create mode 100644 dist/action/813.index.js create mode 100644 dist/action/833.index.js create mode 100644 dist/action/834.index.js create mode 100644 dist/action/883.index.js create mode 100644 dist/action/899.index.js create mode 100644 dist/action/923.index.js create mode 100644 dist/action/936.index.js create mode 100644 dist/action/942.index.js create mode 100644 dist/action/967.index.js create mode 100644 dist/action/973.index.js create mode 100644 dist/action/978.index.js create mode 100644 dist/action/980.index.js create mode 100644 dist/action/index.js create mode 100644 dist/action/licenses.txt create mode 100644 dist/action/package.json diff --git a/dist/action/114.index.js b/dist/action/114.index.js new file mode 100644 index 000000000..759f3deac --- /dev/null +++ b/dist/action/114.index.js @@ -0,0 +1,486 @@ +export const id = 114; +export const ids = [114]; +export const modules = { + +/***/ 80114: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ resolveRemoteAgent: () => (/* binding */ resolveRemoteAgent), +/* harmony export */ resolveRemoteSkill: () => (/* binding */ resolveRemoteSkill) +/* harmony export */ }); +/* unused harmony exports parseRemoteRef, formatRemoteRef, getSkillsCacheDir, getRemotePath, getStatePath, loadState, saveState, getCacheTtlSeconds, shouldRefresh, fetchRemote, discoverRemoteSkills, removeRemote, listCachedRemotes, discoverRemoteAgents */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48161); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_os__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(51737); +/* harmony import */ var _sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9263); +/* harmony import */ var _loader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(34691); + + + + + + +/** Default TTL for unpinned remote skills: 24 hours */ +const DEFAULT_TTL_SECONDS = 86400; +/** Schema for a single remote entry in state.json */ +const RemoteEntrySchema = zod__WEBPACK_IMPORTED_MODULE_5__/* .object */ .Ikc({ + sha: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP(), + fetchedAt: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().datetime(), + cloneUrl: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().optional(), +}); +/** Schema for the entire state.json file */ +const RemoteStateSchema = zod__WEBPACK_IMPORTED_MODULE_5__/* .object */ .Ikc({ + remotes: zod__WEBPACK_IMPORTED_MODULE_5__/* .record */ .g1P(zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP(), RemoteEntrySchema), +}); +/** Schema for a plugin in marketplace.json */ +const MarketplacePluginSchema = zod__WEBPACK_IMPORTED_MODULE_5__/* .object */ .Ikc({ + name: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP(), + source: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP(), + description: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().optional(), + category: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().optional(), +}); +/** Schema for .claude-plugin/marketplace.json */ +const MarketplaceConfigSchema = zod__WEBPACK_IMPORTED_MODULE_5__/* .object */ .Ikc({ + $schema: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().optional(), + name: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP(), + description: zod__WEBPACK_IMPORTED_MODULE_5__/* .string */ .YjP().optional(), + plugins: zod__WEBPACK_IMPORTED_MODULE_5__/* .array */ .YOg(MarketplacePluginSchema), +}); +/** + * Parse a remote reference string into its components. Delegates the grammar + * to `@sentry/dotagents-lib`'s `parseSource` and the safety gate to + * `validateGitNameSafety`. Lib errors are translated to `SkillLoaderError` + * with warden-formatted messages so the public contract stays stable. + * + * Accepted shapes: `owner/repo[@sha]` (GitHub), `https://github.com/...`, + * `git@github.com:...`, GitLab equivalents (incl. nested groups), and HTTP + * forms which are upgraded to HTTPS. + */ +function parseRemoteRef(ref) { + if (ref.startsWith('path:')) { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (use --path for local sources; --remote is for network-fetched sources)`); + } + let parsed; + try { + parsed = (0,_sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__/* .parseSource */ .PJ)(ref); + } + catch (err) { + if (err instanceof _sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__/* .ParseSourceError */ .lY) { + const detail = err.kind === 'empty-sha' ? 'empty SHA after @' : 'repo name cannot contain /'; + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (${detail})`); + } + throw err; + } + if (parsed.type === 'local') { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (local sources are not supported here)`); + } + if (parsed.type === 'well-known') { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (well-known HTTPS sources are not supported by warden)`); + } + const owner = parsed.owner ?? ''; + const repo = parsed.repo ?? ''; + const sha = parsed.ref; + // Bare-shorthand inputs without a slash (`noslash`) reach here with empty + // repo since lib populates owner only. + if (!owner || !repo) { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (expected owner/repo format)`); + } + try { + (0,_sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__/* .validateGitNameSafety */ .Av)({ owner, repo, ref: sha }); + } + catch (err) { + if (err instanceof _sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__/* .GitNameSafetyError */ .S2) { + const fieldLabel = err.field === 'ref' ? 'SHA' : err.field; + const detail = err.reason === 'leading-dash' + ? `${fieldLabel} cannot start with -` + : `${fieldLabel} contains invalid characters`; + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Invalid remote ref: ${ref} (${detail})`); + } + throw err; + } + return { owner, repo, sha, cloneUrl: parsed.cloneUrl }; +} +/** + * Format a parsed remote ref back to string format. + */ +function formatRemoteRef(parsed) { + const base = `${parsed.owner}/${parsed.repo}`; + return parsed.sha ? `${base}@${parsed.sha}` : base; +} +/** + * Get the base directory for caching remote skills. + * Respects WARDEN_STATE_DIR environment variable. + * Default: ~/.local/warden/skills/ + */ +function getSkillsCacheDir() { + const stateDir = process.env['WARDEN_STATE_DIR']; + if (stateDir) { + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(stateDir, 'skills'); + } + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)((0,node_os__WEBPACK_IMPORTED_MODULE_1__.homedir)(), '.local', 'warden', 'skills'); +} +/** + * Get the cache path for a specific remote ref. + * - Unpinned: ~/.local/warden/skills/owner/repo/ + * - Pinned: ~/.local/warden/skills/owner/repo@sha/ + */ +function getRemotePath(ref) { + const parsed = parseRemoteRef(ref); + const cacheDir = getSkillsCacheDir(); + if (parsed.sha) { + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(cacheDir, parsed.owner, `${parsed.repo}@${parsed.sha}`); + } + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(cacheDir, parsed.owner, parsed.repo); +} +/** + * Get the path to the state.json file. + */ +function getStatePath() { + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(getSkillsCacheDir(), 'state.json'); +} +/** + * Load the remote state from state.json. + * Returns an empty state if the file doesn't exist. + */ +function loadState() { + const statePath = getStatePath(); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(statePath)) { + return { remotes: {} }; + } + try { + const content = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(statePath, 'utf-8'); + const data = JSON.parse(content); + return RemoteStateSchema.parse(data); + } + catch (error) { + // If state is corrupted, start fresh + const message = error instanceof Error ? error.message : String(error); + console.warn(`Warning: Failed to load state.json, starting fresh: ${message}`); + return { remotes: {} }; + } +} +/** + * Save the remote state to state.json. + * Uses atomic write (write to temp, then rename). + */ +function saveState(state) { + const statePath = getStatePath(); + const stateDir = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.dirname)(statePath); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(stateDir)) { + (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync)(stateDir, { recursive: true }); + } + const tempPath = `${statePath}.tmp`; + (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync)(tempPath, JSON.stringify(state, null, 2), 'utf-8'); + (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.renameSync)(tempPath, statePath); +} +/** + * Get the TTL for remote skill cache in seconds. + * Respects WARDEN_SKILL_CACHE_TTL environment variable. + */ +function getCacheTtlSeconds() { + const envTtl = process.env['WARDEN_SKILL_CACHE_TTL']; + if (envTtl) { + const parsed = parseInt(envTtl, 10); + if (!isNaN(parsed) && parsed > 0) { + return parsed; + } + } + return DEFAULT_TTL_SECONDS; +} +/** + * Check if an unpinned remote ref needs to be refreshed. + * Pinned refs (with @sha) never need refresh. + */ +function shouldRefresh(ref, state) { + const parsed = parseRemoteRef(ref); + // Pinned refs are immutable - never refresh + if (parsed.sha) { + return false; + } + const entry = state.remotes[formatRemoteRef(parsed)]; + if (!entry) { + return true; // Not cached, needs fetch + } + const fetchedAt = new Date(entry.fetchedAt).getTime(); + const now = Date.now(); + const ttl = getCacheTtlSeconds() * 1000; + return now - fetchedAt > ttl; +} + +/** Encode the pin into the lib `cacheKey` so pinned and unpinned land in separate dirs. */ +function cacheKeyFor(parsed) { + if (parsed.sha) { + return `${parsed.owner}/${parsed.repo}@${parsed.sha}`; + } + return `${parsed.owner}/${parsed.repo}`; +} +/** + * Clone or update a remote repository to the cache. + * Returns the SHA of the fetched commit. + */ +async function fetchRemote(ref, options = {}) { + const { force = false, offline = false, onProgress } = options; + const parsed = parseRemoteRef(ref); + const remotePath = getRemotePath(ref); + const state = loadState(); + // Normalize state key so different URL forms (SSH, HTTPS, shorthand) share one entry + const stateKey = formatRemoteRef(parsed); + const isPinned = !!parsed.sha; + const isCached = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(remotePath); + const needsRefresh = shouldRefresh(ref, state); + // Check if we have a valid cache (directory exists AND state entry exists) + const stateEntry = state.remotes[stateKey]; + const hasValidCache = isCached && !!stateEntry; + // Handle offline mode + if (offline) { + if (hasValidCache) { + return stateEntry.sha; + } + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Remote skill not cached and offline mode enabled: ${ref}`); + } + // Pinned + valid cache = use cache (SHA is immutable) + if (isPinned && hasValidCache && !force && parsed.sha) { + return parsed.sha; + } + // Unpinned + valid cache + fresh = use cache + if (!isPinned && hasValidCache && !needsRefresh && !force) { + return stateEntry.sha; + } + // Use the original clone URL if provided, fall back to stored URL from state, then HTTPS + const cloneUrl = parsed.cloneUrl ?? stateEntry?.cloneUrl ?? `https://github.com/${parsed.owner}/${parsed.repo}.git`; + onProgress?.(isCached ? `Updating ${ref}...` : `Cloning ${ref}...`); + const cached = await (0,_sentry_dotagents_lib__WEBPACK_IMPORTED_MODULE_3__/* .ensureCached */ .vJ)({ + stateDir: getSkillsCacheDir(), + url: cloneUrl, + cacheKey: cacheKeyFor(parsed), + ref: parsed.sha, + }); + // Update state with normalized key — preserve cloneUrl for future re-clones + const persistedCloneUrl = parsed.cloneUrl ?? stateEntry?.cloneUrl; + state.remotes[stateKey] = { + sha: cached.commit, + fetchedAt: new Date().toISOString(), + ...(persistedCloneUrl ? { cloneUrl: persistedCloneUrl } : {}), + }; + saveState(state); + return cached.commit; +} +/** + * Parse marketplace.json from a remote repository if it exists. + * Returns null if the file doesn't exist or is invalid. + */ +function parseMarketplaceConfig(remotePath) { + const marketplacePath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(remotePath, '.claude-plugin', 'marketplace.json'); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(marketplacePath)) { + return null; + } + try { + const content = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(marketplacePath, 'utf-8'); + const data = JSON.parse(content); + return MarketplaceConfigSchema.parse(data); + } + catch { + // Invalid or malformed marketplace.json - fall back to traditional discovery + return null; + } +} +/** Directories to search for skills in remote repositories */ +const REMOTE_SKILL_DIRECTORIES = [ + '', // root level + 'skills', // skills/ subdirectory + '.agents/skills', // General agent skills (primary) + '.claude/skills', // Claude Code skills + '.warden/skills', // Repo-local generated skills +]; +/** Directories to search for agents in remote repositories */ +const REMOTE_AGENT_DIRECTORIES = [ + '', // root level + 'agents', // agents/ subdirectory + '.agents/agents', // Primary + '.claude/agents', // Claude Code agents + '.warden/agents', // Legacy +]; +/** + * Discover entries (skills or agents) using traditional directory layout. + * Searches the given subdirectories for directories containing the marker file. + * First occurrence of a name wins (earlier directories have higher precedence). + */ +async function discoverTraditional(remotePath, directories, markerFile) { + const results = []; + const seenNames = new Set(); + for (const subdir of directories) { + const searchPath = subdir ? (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(remotePath, subdir) : remotePath; + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(searchPath)) + continue; + const entries = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync)(searchPath); + for (const entry of entries) { + if (entry.startsWith('.')) + continue; + const entryPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(searchPath, entry); + const stat = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync)(entryPath); + if (stat.isDirectory()) { + const markerPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(entryPath, markerFile); + if ((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(markerPath)) { + try { + const loaded = await (0,_loader_js__WEBPACK_IMPORTED_MODULE_4__/* .loadSkillFromMarkdown */ .hl)(markerPath); + if (!seenNames.has(loaded.name)) { + seenNames.add(loaded.name); + results.push({ + name: loaded.name, + description: loaded.description, + path: entryPath, + }); + } + } + catch { + // Skip invalid entries + } + } + } + } + } + return results; +} +/** + * Discover skills using marketplace format. + * Searches plugins/{plugin}/skills/ for each plugin defined in marketplace.json. + */ +async function discoverMarketplaceSkills(remotePath, config) { + const skills = []; + const seenNames = new Set(); + for (const plugin of config.plugins) { + // Resolve plugin source path (e.g., "./plugins/sentry-skills" -> "plugins/sentry-skills") + const pluginSource = plugin.source.replace(/^\.\//, ''); + const skillsPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(remotePath, pluginSource, 'skills'); + // Security: Ensure plugin source doesn't escape the repo directory via path traversal + const resolvedSkillsPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.resolve)(skillsPath); + const resolvedRemotePath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.resolve)(remotePath); + if (!resolvedSkillsPath.startsWith(resolvedRemotePath + '/')) { + continue; // Silently skip — attacker-controlled marketplace.json, don't leak info + } + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(skillsPath)) + continue; + const entries = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync)(skillsPath); + for (const entry of entries) { + if (entry.startsWith('.')) + continue; + const entryPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(skillsPath, entry); + const stat = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync)(entryPath); + if (stat.isDirectory()) { + const skillMdPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(entryPath, 'SKILL.md'); + if ((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(skillMdPath)) { + try { + const skill = await (0,_loader_js__WEBPACK_IMPORTED_MODULE_4__/* .loadSkillFromMarkdown */ .hl)(skillMdPath); + if (!seenNames.has(skill.name)) { + seenNames.add(skill.name); + skills.push({ + name: skill.name, + description: skill.description, + path: entryPath, + pluginName: plugin.name, + }); + } + } + catch { + // Skip invalid skill directories + } + } + } + } + } + return skills; +} +/** + * Discover all skills in a cached remote repository. + * Detects format and delegates to appropriate discovery function: + * - If .claude-plugin/marketplace.json exists, uses marketplace discovery + * - Otherwise, uses traditional discovery (root, skills/, .warden/skills, etc.) + */ +async function discoverRemoteSkills(ref) { + const remotePath = getRemotePath(ref); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(remotePath)) { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Remote not cached: ${ref}. Run fetch first.`); + } + // Check for marketplace format + const marketplaceConfig = parseMarketplaceConfig(remotePath); + if (marketplaceConfig) { + return discoverMarketplaceSkills(remotePath, marketplaceConfig); + } + // Fall back to traditional discovery + return discoverTraditional(remotePath, REMOTE_SKILL_DIRECTORIES, 'SKILL.md'); +} +/** + * Resolve a remote entry (skill or agent) by name. + * Fetches the remote, discovers available entries, and loads the matching one. + */ +async function resolveRemoteEntry(ref, name, markerFile, discoverFn, label, options = {}) { + await fetchRemote(ref, options); + const available = await discoverFn(ref); + const match = available.find((entry) => entry.name === name); + if (match) { + return (0,_loader_js__WEBPACK_IMPORTED_MODULE_4__/* .loadSkillFromMarkdown */ .hl)((0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(match.path, markerFile)); + } + const labelLower = label.toLowerCase(); + if (available.length === 0) { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`No ${labelLower}s found in remote: ${ref}`); + } + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`${label} '${name}' not found in remote: ${ref}. Available ${labelLower}s: ${available.map((e) => e.name).join(', ')}`); +} +/** + * Resolve a skill from a remote repository. + * Ensures the remote is fetched/cached, then loads the skill. + * Matches by skill name (from SKILL.md), not directory name. + */ +async function resolveRemoteSkill(ref, skillName, options = {}) { + return resolveRemoteEntry(ref, skillName, 'SKILL.md', discoverRemoteSkills, 'Skill', options); +} +/** + * Remove a remote from the cache. + */ +function removeRemote(ref) { + const remotePath = getRemotePath(ref); + if (existsSync(remotePath)) { + rmSync(remotePath, { recursive: true, force: true }); + } + const stateKey = formatRemoteRef(parseRemoteRef(ref)); + const state = loadState(); + const { [stateKey]: _removed, ...remainingRemotes } = state.remotes; + state.remotes = remainingRemotes; + saveState(state); +} +/** + * List all cached remotes with their metadata. + */ +function listCachedRemotes() { + const state = loadState(); + return Object.entries(state.remotes).map(([ref, entry]) => ({ ref, entry })); +} +/** + * Discover all agents in a cached remote repository. + * Uses traditional discovery only (no marketplace format for agents). + */ +async function discoverRemoteAgents(ref) { + const remotePath = getRemotePath(ref); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(remotePath)) { + throw new _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .SkillLoaderError */ .vN(`Remote not cached: ${ref}. Run fetch first.`); + } + return discoverTraditional(remotePath, REMOTE_AGENT_DIRECTORIES, _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .AGENT_MARKER_FILE */ .qA); +} +/** + * Resolve an agent from a remote repository. + * Ensures the remote is fetched/cached, then loads the agent. + * Matches by agent name (from AGENT.md), not directory name. + */ +async function resolveRemoteAgent(ref, agentName, options = {}) { + return resolveRemoteEntry(ref, agentName, _loader_js__WEBPACK_IMPORTED_MODULE_4__/* .AGENT_MARKER_FILE */ .qA, discoverRemoteAgents, 'Agent', options); +} + + +/***/ }) + +}; diff --git a/dist/action/117.index.js b/dist/action/117.index.js new file mode 100644 index 000000000..caa80e043 --- /dev/null +++ b/dist/action/117.index.js @@ -0,0 +1,46 @@ +export const id = 117; +export const ids = [117]; +export const modules = { + +/***/ 82117: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +var node_child_process__WEBPACK_IMPORTED_MODULE_0___namespace_cache; +var node_crypto__WEBPACK_IMPORTED_MODULE_1___namespace_cache; +var node_fs__WEBPACK_IMPORTED_MODULE_2___namespace_cache; +var node_path__WEBPACK_IMPORTED_MODULE_4___namespace_cache; +var node_stream__WEBPACK_IMPORTED_MODULE_5___namespace_cache; +var node_util__WEBPACK_IMPORTED_MODULE_6___namespace_cache; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Et: () => (/* reexport fake namespace object from non-harmony */ node_crypto__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (node_crypto__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__.t(node_crypto__WEBPACK_IMPORTED_MODULE_1__, 2))), +/* harmony export */ Td: () => (/* reexport fake namespace object from non-harmony */ node_stream__WEBPACK_IMPORTED_MODULE_5___namespace_cache || (node_stream__WEBPACK_IMPORTED_MODULE_5___namespace_cache = __webpack_require__.t(node_stream__WEBPACK_IMPORTED_MODULE_5__, 2))), +/* harmony export */ ZS: () => (/* reexport fake namespace object from non-harmony */ node_util__WEBPACK_IMPORTED_MODULE_6___namespace_cache || (node_util__WEBPACK_IMPORTED_MODULE_6___namespace_cache = __webpack_require__.t(node_util__WEBPACK_IMPORTED_MODULE_6__, 2))), +/* harmony export */ fs: () => (/* reexport fake namespace object from non-harmony */ node_fs__WEBPACK_IMPORTED_MODULE_2___namespace_cache || (node_fs__WEBPACK_IMPORTED_MODULE_2___namespace_cache = __webpack_require__.t(node_fs__WEBPACK_IMPORTED_MODULE_2__, 2))), +/* harmony export */ hV: () => (/* reexport fake namespace object from non-harmony */ node_child_process__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (node_child_process__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(node_child_process__WEBPACK_IMPORTED_MODULE_0__, 2))), +/* harmony export */ path: () => (/* reexport fake namespace object from non-harmony */ node_path__WEBPACK_IMPORTED_MODULE_4___namespace_cache || (node_path__WEBPACK_IMPORTED_MODULE_4___namespace_cache = __webpack_require__.t(node_path__WEBPACK_IMPORTED_MODULE_4__, 2))) +/* harmony export */ }); +/* harmony import */ var node_child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31421); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77598); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(73024); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48161); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(76760); +/* harmony import */ var node_stream__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(57075); +/* harmony import */ var node_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(57975); +/** + * The one module under `src/` that may import Node built-ins (eslint enforces this). + * The package.json `browser` field swaps it for `./node.browser`, so only touch its + * exports on code paths that run on Node-compatible runtimes. + */ + + + + + + + + +//# sourceMappingURL=node.mjs.map + +/***/ }) + +}; diff --git a/dist/action/144.index.js b/dist/action/144.index.js new file mode 100644 index 000000000..1e3f269b7 --- /dev/null +++ b/dist/action/144.index.js @@ -0,0 +1,458 @@ +export const id = 144; +export const ids = [144]; +export const modules = { + +/***/ 27144: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ stream: () => (/* binding */ stream), +/* harmony export */ streamSimple: () => (/* binding */ streamSimple) +/* harmony export */ }); +/* harmony import */ var _google_genai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(74751); +/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25941); +/* harmony import */ var _utils_error_body_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(20372); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45174); +/* harmony import */ var _utils_headers_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(82003); +/* harmony import */ var _utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(55278); +/* harmony import */ var _utils_provider_env_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(67982); +/* harmony import */ var _utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(43780); +/* harmony import */ var _utils_text_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(65678); +/* harmony import */ var _utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19883); +/* harmony import */ var _google_shared_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(81247); +/* harmony import */ var _simple_options_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(18296); + + + + + + + + + + + + +const API_VERSION = "v1"; +const GCP_VERTEX_CREDENTIALS_MARKER = "gcp-vertex-credentials"; +// Counter for generating unique tool call IDs +let toolCallCounter = 0; +const stream = (model, context, options) => { + const stream = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_1__/* .AssistantMessageEventStream */ .Q2(); + const normalizedContext = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__/* .collapseSystemMessages */ .zI)(context); + (async () => { + const output = { + role: "assistant", + content: [], + api: "google-vertex", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + try { + if (options?.fetch && options.fetch !== globalThis.fetch) { + throw new Error("Custom fetch is not supported by the Google Vertex adapter"); + } + const apiKey = resolveApiKey(options); + // Create the client using either a Vertex API key, if provided, or ADC with project and location + const client = apiKey + ? createClientWithApiKey(model, apiKey, options?.headers) + : createClient(model, resolveProject(options), resolveLocation(options), options?.headers, options?.env); + let params = buildParams(model, normalizedContext, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== undefined) { + params = nextParams; + } + const googleStream = await (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .retryGoogleRequest */ .rM)(() => client.models.generateContentStream(params), options); + stream.push({ type: "start", partial: output }); + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + for await (const chunk of googleStream) { + // Vertex uses the same @google/genai GenerateContentResponse type as Gemini. + // responseId is documented there as an output-only identifier for each response. + output.responseId ||= chunk.responseId; + const candidate = chunk.candidates?.[0]; + if (candidate?.content?.parts) { + for (const part of candidate.content.parts) { + if (part.text !== undefined) { + const isThinking = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .isThinkingPart */ .oH)(part); + if (!currentBlock || + (isThinking && currentBlock.type !== "thinking") || + (!isThinking && currentBlock.type !== "text")) { + if (currentBlock) { + if (currentBlock.type === "text") { + stream.push({ + type: "text_end", + contentIndex: blocks.length - 1, + content: currentBlock.text, + partial: output, + }); + } + else { + stream.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output, + }); + } + } + if (isThinking) { + currentBlock = { type: "thinking", thinking: "", thinkingSignature: undefined }; + output.content.push(currentBlock); + stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } + else { + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + } + if (currentBlock.type === "thinking") { + currentBlock.thinking += part.text; + currentBlock.thinkingSignature = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .retainThoughtSignature */ .pc)(currentBlock.thinkingSignature, part.thoughtSignature); + stream.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output, + }); + } + else { + currentBlock.text += part.text; + currentBlock.textSignature = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .retainThoughtSignature */ .pc)(currentBlock.textSignature, part.thoughtSignature); + stream.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output, + }); + } + } + if (part.functionCall) { + if (currentBlock) { + if (currentBlock.type === "text") { + stream.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output, + }); + } + else { + stream.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output, + }); + } + currentBlock = null; + } + const providedId = part.functionCall.id; + const needsNewId = !providedId || output.content.some((b) => b.type === "toolCall" && b.id === providedId); + const toolCallId = needsNewId + ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}` + : providedId; + const toolCall = { + type: "toolCall", + id: toolCallId, + name: part.functionCall.name || "", + arguments: part.functionCall.args ?? {}, + ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }), + }; + output.content.push(toolCall); + stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + stream.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta: JSON.stringify(toolCall.arguments), + partial: output, + }); + stream.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output }); + } + } + } + if (candidate?.finishReason) { + output.rawStopReason = candidate.finishReason; + output.stopReason = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .mapStopReason */ .f7)(candidate.finishReason); + if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") { + output.stopReason = "toolUse"; + } + } + if (chunk.usageMetadata) { + output.usage = { + input: (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0), + output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0), + cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0, + cacheWrite: 0, + reasoning: chunk.usageMetadata.thoughtsTokenCount || 0, + totalTokens: chunk.usageMetadata.totalTokenCount || 0, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0, + }, + }; + (0,_models_js__WEBPACK_IMPORTED_MODULE_4__/* .calculateCost */ .yN)(model, output.usage); + } + } + if (currentBlock) { + if (currentBlock.type === "text") { + stream.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output, + }); + } + else { + stream.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output, + }); + } + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "pending") { + throw new Error("Google Vertex stream ended without a finish reason"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + const errorMessage = output.rawStopReason + ? `Provider stopped with: ${output.rawStopReason}` + : "An unknown error occurred"; + throw new Error(errorMessage); + } + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + // Remove internal index property used during streaming + for (const block of output.content) { + if ("index" in block) { + delete block.index; + } + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = (0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_5__/* .formatProviderError */ .lR)((0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_5__/* .normalizeProviderError */ .Jo)(error)); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +const streamSimple = (model, context, options) => { + const base = { + ...(0,_simple_options_js__WEBPACK_IMPORTED_MODULE_6__/* .buildBaseOptions */ .QP)(model, context, options, undefined), + toolChoice: options?.toolChoice, + }; + if (!options?.reasoning) { + return stream(model, context, { + ...base, + thinking: { enabled: false }, + }); + } + const clampedReasoning = (0,_models_js__WEBPACK_IMPORTED_MODULE_4__/* .clampThinkingLevel */ .Kt)(model, options.reasoning); + if (clampedReasoning === "off") { + return stream(model, context, { + ...base, + thinking: { enabled: false }, + }); + } + const resolvedLevel = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveGoogleThinkingLevel */ .O5)(model, clampedReasoning); + if ((0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .usesGoogleThinkingLevel */ .Ih)(model)) { + return stream(model, context, { + ...base, + thinking: { + enabled: true, + level: (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .toGoogleThinkingLevel */ .ng)(resolvedLevel), + }, + }); + } + return stream(model, context, { + ...base, + thinking: { + enabled: true, + budgetTokens: getGoogleBudget(model, resolvedLevel, options.thinkingBudgets), + }, + }); +}; +function createClient(model, project, location, optionsHeaders, env) { + const googleAuthOptions = buildGoogleAuthOptions(env); + return new _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .GoogleGenAI */ .M4({ + vertexai: true, + project, + location, + apiVersion: API_VERSION, + ...(googleAuthOptions ? { googleAuthOptions } : {}), + httpOptions: buildHttpOptions(model, optionsHeaders), + }); +} +function createClientWithApiKey(model, apiKey, optionsHeaders) { + return new _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .GoogleGenAI */ .M4({ + vertexai: true, + apiKey, + apiVersion: API_VERSION, + httpOptions: buildHttpOptions(model, optionsHeaders), + }); +} +function buildHttpOptions(model, optionsHeaders) { + const httpOptions = {}; + const baseUrl = resolveCustomBaseUrl(model.baseUrl); + if (baseUrl) { + httpOptions.baseUrl = baseUrl; + httpOptions.baseUrlResourceScope = _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ResourceScope */ .r.COLLECTION; + if (baseUrlIncludesApiVersion(baseUrl)) { + httpOptions.apiVersion = ""; + } + } + const headers = (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_7__/* .providerHeadersToRecord */ .m)({ "User-Agent": (0,_utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_8__/* .getPiUserAgent */ .w)(), ...model.headers, ...optionsHeaders }); + if (headers) { + httpOptions.headers = headers; + } + return Object.keys(httpOptions).length > 0 ? httpOptions : undefined; +} +function resolveCustomBaseUrl(baseUrl) { + const trimmed = baseUrl.trim(); + if (!trimmed || trimmed.includes("{location}")) { + return undefined; + } + return trimmed; +} +function baseUrlIncludesApiVersion(baseUrl) { + try { + const url = new URL(baseUrl); + return url.pathname.split("/").some((part) => /^v\d+(?:beta\d*)?$/.test(part)); + } + catch { + return /(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl); + } +} +function buildGoogleAuthOptions(env) { + const keyFilename = (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_9__/* .getProviderEnvValue */ .Y)("GOOGLE_APPLICATION_CREDENTIALS", env); + return keyFilename ? { keyFilename } : undefined; +} +function resolveApiKey(options) { + const apiKey = options?.apiKey?.trim(); + if (!apiKey || apiKey === GCP_VERTEX_CREDENTIALS_MARKER || isPlaceholderApiKey(apiKey)) { + return undefined; + } + return apiKey; +} +function isPlaceholderApiKey(apiKey) { + return /^<[^>]+>$/.test(apiKey); +} +function resolveProject(options) { + const project = options?.project || + (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_9__/* .getProviderEnvValue */ .Y)("GOOGLE_CLOUD_PROJECT", options?.env) || + (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_9__/* .getProviderEnvValue */ .Y)("GCLOUD_PROJECT", options?.env); + if (!project) { + throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options."); + } + return project; +} +function resolveLocation(options) { + const location = options?.location || (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_9__/* .getProviderEnvValue */ .Y)("GOOGLE_CLOUD_LOCATION", options?.env); + if (!location) { + throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options."); + } + return location; +} +function buildParams(model, context, options = {}) { + const contents = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .convertMessages */ ._0)(model, context); + const initialSystemMessage = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__/* .getInitialSystemMessage */ .xF)(context.messages); + const currentTools = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__/* .getCurrentTools */ .Fh)(context.messages); + const generationConfig = {}; + if (options.temperature !== undefined) { + generationConfig.temperature = options.temperature; + } + if (options.maxTokens !== undefined) { + generationConfig.maxOutputTokens = options.maxTokens; + } + const supportsStrictMode = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .supportsGoogleStrictToolSampling */ .AT)(model.id); + const functionCallingMode = currentTools.length > 0 + ? (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveGoogleFunctionCallingMode */ .hz)(currentTools, options.toolChoice, supportsStrictMode) + : undefined; + const systemInstruction = initialSystemMessage ? (0,_utils_text_js__WEBPACK_IMPORTED_MODULE_10__/* .getSystemMessageText */ .Y8)(initialSystemMessage) : ""; + const config = { + ...(Object.keys(generationConfig).length > 0 && generationConfig), + ...(systemInstruction && { systemInstruction: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_11__/* .sanitizeSurrogates */ .J)(systemInstruction) }), + ...(currentTools.length > 0 && { + tools: (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .convertTools */ .B1)(currentTools, false, supportsStrictMode), + }), + ...(functionCallingMode !== undefined && { + toolConfig: { functionCallingConfig: { mode: functionCallingMode } }, + }), + }; + if (options.thinking?.enabled && model.reasoning) { + const thinkingConfig = { includeThoughts: true }; + if (options.thinking.level !== undefined) { + thinkingConfig.thinkingLevel = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .toGoogleSdkThinkingLevel */ .RE)(options.thinking.level); + } + else if (options.thinking.budgetTokens !== undefined) { + thinkingConfig.thinkingBudget = options.thinking.budgetTokens; + } + config.thinkingConfig = thinkingConfig; + } + else if (model.reasoning && options.thinking && !options.thinking.enabled) { + config.thinkingConfig = (0,_google_shared_js__WEBPACK_IMPORTED_MODULE_3__/* .getDisabledGoogleThinkingConfig */ .cq)(model); + } + if (options.signal) { + if (options.signal.aborted) { + throw new Error("Request aborted"); + } + config.abortSignal = options.signal; + } + const params = { + model: model.id, + contents, + config, + }; + return params; +} +function getGoogleBudget(model, level, customBudgets) { + if (customBudgets?.[level] !== undefined) { + return customBudgets[level]; + } + if (model.id.includes("2.5-pro")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 32768, + }; + return budgets[level]; + } + if (model.id.includes("2.5-flash")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 24576, + }; + return budgets[level]; + } + return -1; +} +//# sourceMappingURL=google-vertex.js.map + +/***/ }) + +}; diff --git a/dist/action/181.index.js b/dist/action/181.index.js new file mode 100644 index 000000000..600119df1 --- /dev/null +++ b/dist/action/181.index.js @@ -0,0 +1,24 @@ +export const id = 181; +export const ids = [181]; +export const modules = { + +/***/ 51181: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 51181; +module.exports = webpackEmptyAsyncContext; + +/***/ }) + +}; diff --git a/dist/action/192.index.js b/dist/action/192.index.js new file mode 100644 index 000000000..6ac16efa8 --- /dev/null +++ b/dist/action/192.index.js @@ -0,0 +1,78 @@ +export const id = 192; +export const ids = [192,181]; +export const modules = { + +/***/ 51181: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 51181; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 94192: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + createJiti: () => (/* reexport */ createJiti) +}); + +// EXTERNAL MODULE: external "node:module" +var external_node_module_ = __webpack_require__(98995); +// EXTERNAL MODULE: ../../node_modules/.pnpm/jiti@2.7.0/node_modules/jiti/dist/jiti.cjs +var jiti = __webpack_require__(60978); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/jiti@2.7.0/node_modules/jiti/lib/jiti.mjs + + + +function onError(err) { + throw err; /* ↓ Check stack trace ↓ */ +} + +const nativeImport = (id) => __webpack_require__(51181)(id); + +let _transform; +function lazyTransform(...args) { + if (!_transform) { + _transform = (0,external_node_module_.createRequire)(import.meta.url)("../dist/babel.cjs"); + } + return _transform(...args); +} + +function createJiti(id, opts = {}) { + if (!opts.transform) { + opts = { ...opts, transform: lazyTransform }; + } + return jiti(id, opts, { + onError, + nativeImport, + createRequire: external_node_module_.createRequire, + }); +} + +/* harmony default export */ const lib_jiti = ((/* unused pure expression or super */ null && (createJiti))); + +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-coding-agent@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/jiti-loader.js +// Normal Node runtimes use jiti's lazy transform so Babel is loaded only when +// native loading fails and an extension needs transformation. + +//# sourceMappingURL=jiti-loader.js.map + +/***/ }) + +}; diff --git a/dist/action/211.index.js b/dist/action/211.index.js new file mode 100644 index 000000000..ebeb18480 --- /dev/null +++ b/dist/action/211.index.js @@ -0,0 +1,19236 @@ +export const id = 211; +export const ids = [211]; +export const modules = { + +/***/ 47423: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + YX: () => (/* binding */ buildCoreSummaryData), + RR: () => (/* reexport */ createCompletedCoreCheck), + $R: () => (/* reexport */ createCompletedSkillCheck), + c: () => (/* reexport */ createCoreCheck), + xB: () => (/* reexport */ createFailedSkillCheck), + uP: () => (/* reexport */ createSkillCheck), + Hx: () => (/* reexport */ determineConclusion), + ar: () => (/* binding */ determineCoreConclusion), + OZ: () => (/* reexport */ failSkillCheck), + TR: () => (/* reexport */ isBaselineConclusion), + Y9: () => (/* reexport */ markSkillCheckBaseline), + R2: () => (/* reexport */ updateCoreCheck), + Zv: () => (/* reexport */ updateSkillCheck) +}); + +// UNUSED EXPORTS: aggregateSeverityCounts, aggregateUsage + +// EXTERNAL MODULE: ./src/types/index.ts +var types = __webpack_require__(78481); +// EXTERNAL MODULE: ./src/cli/output/formatters.ts +var formatters = __webpack_require__(43171); +// EXTERNAL MODULE: ./src/utils/index.ts + 1 modules +var utils = __webpack_require__(82272); +// EXTERNAL MODULE: ./src/sdk/errors.ts +var errors = __webpack_require__(98229); +;// CONCATENATED MODULE: ./src/output/github-checks.ts + + + + +/** + * Maximum number of annotations per API call (GitHub limit). + */ +const MAX_ANNOTATIONS_PER_REQUEST = 50; +/** + * Point the check-run action at the exact GitHub page created for this check. + */ +async function setCheckDetailsUrl(octokit, options, checkRun) { + if (!checkRun.html_url) + return; + try { + await octokit.checks.update({ + owner: options.owner, + repo: options.repo, + check_run_id: checkRun.id, + details_url: checkRun.html_url, + }); + } + catch (error) { + console.warn(`Failed to set details URL for check ${checkRun.id}: ${error}`); + } +} +/** + * Map severity levels to GitHub annotation levels. + * high -> failure, medium -> warning, low -> notice + */ +function severityToAnnotationLevel(severity) { + switch (severity) { + case 'high': + return 'failure'; + case 'medium': + return 'warning'; + case 'low': + return 'notice'; + } +} +/** + * Convert findings to GitHub Check annotations. + * Only findings with locations can be converted to annotations. + * Returns at most MAX_ANNOTATIONS_PER_REQUEST annotations. + * If reportOn is specified, only include findings at or above that severity. + */ +function findingsToAnnotations(findings, reportOn, minConfidence) { + // Filter by reportOn threshold and confidence if specified + const filtered = (0,types/* filterFindings */.Ni)(findings, reportOn, minConfidence); + // Filter to findings with location using type predicate + const withLocation = filtered.filter((f) => Boolean(f.location)); + // Sort by severity (most severe first) + const sorted = [...withLocation].sort((a, b) => types/* SEVERITY_ORDER */.B[a.severity] - types/* SEVERITY_ORDER */.B[b.severity]); + // Limit to max annotations + const limited = sorted.slice(0, MAX_ANNOTATIONS_PER_REQUEST); + const annotations = []; + for (const finding of limited) { + if (annotations.length >= MAX_ANNOTATIONS_PER_REQUEST) + break; + // Primary location annotation + annotations.push({ + path: finding.location.path, + start_line: finding.location.startLine, + end_line: finding.location.endLine ?? finding.location.startLine, + annotation_level: severityToAnnotationLevel(finding.severity), + message: (0,utils/* escapeHtml */.ZD)(finding.description), + title: (0,utils/* escapeHtml */.ZD)(finding.title), + }); + // Additional location annotations + if (finding.additionalLocations) { + for (const loc of finding.additionalLocations) { + if (annotations.length >= MAX_ANNOTATIONS_PER_REQUEST) + break; + annotations.push({ + path: loc.path, + start_line: loc.startLine, + end_line: loc.endLine ?? loc.startLine, + annotation_level: severityToAnnotationLevel(finding.severity), + message: (0,utils/* escapeHtml */.ZD)(finding.description), + title: `[${finding.id}] ${(0,utils/* escapeHtml */.ZD)(finding.title)} (additional location)`, + }); + } + } + } + return annotations; +} +/** + * Determine the check conclusion based on findings and failOn threshold. + * - No findings: success + * - Findings, none >= failOn: neutral + * - Findings >= failOn threshold: failure + */ +function determineConclusion(findings, failOn, failCheck) { + if (findings.length === 0) { + return 'success'; + } + if (!failOn || failOn === 'off') { + // No failure threshold or disabled, findings exist but don't cause failure + return 'neutral'; + } + const failOnOrder = types/* SEVERITY_ORDER */.B[failOn]; + const hasFailingSeverity = findings.some((f) => types/* SEVERITY_ORDER */.B[f.severity] <= failOnOrder); + return hasFailingSeverity && failCheck ? 'failure' : 'neutral'; +} +/** + * Create a check run for a skill. + * The check is created with status: in_progress. + */ +async function createSkillCheck(octokit, skillName, options) { + const { data } = await octokit.checks.create({ + owner: options.owner, + repo: options.repo, + name: `warden: ${skillName}`, + head_sha: options.headSha, + status: 'in_progress', + started_at: new Date().toISOString(), + }); + await setCheckDetailsUrl(octokit, options, data); + return { + checkRunId: data.id, + url: data.html_url ?? '', + }; +} +function buildSkillCheckPayload(report, options) { + // Conclusion is based on confidence-filtered findings (consistent with CLI path) + const filteredForConclusion = (0,types/* filterFindings */.Ni)(report.findings, undefined, options.minConfidence); + const conclusion = options.conclusion ?? determineConclusion(filteredForConclusion, options.failOn, options.failCheck); + // Annotations are filtered by reportOn threshold and confidence + const annotations = findingsToAnnotations(report.findings, options.reportOn, options.minConfidence); + const summary = buildSkillSummary(report); + const filteredCount = filteredForConclusion.length; + const title = options.title ?? (filteredCount === 0 + ? 'No issues' + : `${filteredCount} issue${filteredCount === 1 ? '' : 's'}`); + return { + conclusion, + output: { + title, + summary, + annotations, + }, + }; +} +/** + * Create a completed skill check with results. + */ +async function createCompletedSkillCheck(octokit, report, options) { + const payload = buildSkillCheckPayload(report, options); + const { data } = await octokit.checks.create({ + owner: options.owner, + repo: options.repo, + name: `warden: ${options.checkName ?? report.skill}`, + head_sha: options.headSha, + status: 'completed', + conclusion: payload.conclusion, + completed_at: new Date().toISOString(), + output: payload.output, + }); + await setCheckDetailsUrl(octokit, options, data); + return { + checkRunId: data.id, + url: data.html_url ?? '', + }; +} +/** + * Update a skill check with results. + * Completes the check with conclusion, summary, and annotations. + */ +async function updateSkillCheck(octokit, checkRunId, report, options) { + const payload = buildSkillCheckPayload(report, options); + await octokit.checks.update({ + owner: options.owner, + repo: options.repo, + check_run_id: checkRunId, + status: 'completed', + conclusion: payload.conclusion, + completed_at: new Date().toISOString(), + output: payload.output, + }); +} +/** + * Whether a skill check with this report concludes success or neutral. A + * failing check must never become an incremental baseline: carrying its + * findings forward would let a later push pass without re-reviewing them. + */ +function isBaselineConclusion(report, options) { + const findings = (0,types/* filterFindings */.Ni)(report.findings, undefined, options.minConfidence); + const conclusion = determineConclusion(findings, options.failOn, options.failCheck); + return conclusion === 'success' || conclusion === 'neutral'; +} +/** + * Mark a completed skill check as an incremental review baseline by setting + * its `external_id`. Call only after the run's feedback reached the PR, so a + * failed write leaves no baseline rather than one for unposted findings. + */ +async function markSkillCheckBaseline(octokit, checkRunId, externalId, options) { + await octokit.checks.update({ + owner: options.owner, + repo: options.repo, + check_run_id: checkRunId, + external_id: externalId, + }); +} +const MAX_CHECK_SUMMARY_BYTES = 65000; +const TRUNCATION_NOTICE = '\n\n[diagnostics truncated]'; +function truncateCheckSummary(summary) { + if (Buffer.byteLength(summary, 'utf8') <= MAX_CHECK_SUMMARY_BYTES) + return summary; + const contentBudget = MAX_CHECK_SUMMARY_BYTES - Buffer.byteLength(TRUNCATION_NOTICE, 'utf8'); + let low = 0; + let high = summary.length; + while (low < high) { + const midpoint = Math.ceil((low + high) / 2); + if (Buffer.byteLength(summary.slice(0, midpoint), 'utf8') <= contentBudget) { + low = midpoint; + } + else { + high = midpoint - 1; + } + } + return summary.slice(0, low) + TRUNCATION_NOTICE; +} +function failureSummary(error) { + const errorMessage = (0,errors/* sanitizeErrorMessage */.$w)(error instanceof Error ? error.message : String(error)); + const rawFailures = error && typeof error === 'object' && 'hunkFailures' in error + ? error.hunkFailures + : undefined; + const parsedFailures = Array.isArray(rawFailures) + ? rawFailures.flatMap((failure) => { + const parsed = types/* HunkFailureSchema */.se.safeParse(failure); + return parsed.success ? [parsed.data] : []; + }) + : []; + if (parsedFailures.length === 0) + return `Error: ${errorMessage}`; + const sanitizedFailures = parsedFailures.map((failure) => ({ + ...failure, + filename: (0,errors/* sanitizeErrorMessage */.$w)(failure.filename), + lineRange: (0,errors/* sanitizeErrorMessage */.$w)(failure.lineRange), + message: (0,errors/* sanitizeErrorMessage */.$w)(failure.message), + preview: failure.preview ? (0,errors/* sanitizeErrorMessage */.$w)(failure.preview).slice(0, 500) : undefined, + })); + const diagnostics = JSON.stringify(sanitizedFailures, null, 2) + .split('\n') + .map((line) => ` ${line}`) + .join('\n'); + return truncateCheckSummary(`Error: ${errorMessage}\n\nHunk failures:\n${diagnostics}`); +} +/** + * Mark a skill check as failed due to execution error. + */ +async function failSkillCheck(octokit, checkRunId, error, options) { + const summary = failureSummary(error); + await octokit.checks.update({ + owner: options.owner, + repo: options.repo, + check_run_id: checkRunId, + status: 'completed', + conclusion: 'failure', + completed_at: new Date().toISOString(), + output: { + title: 'Skill execution failed', + summary, + }, + }); +} +/** + * Create a completed failed skill check without first creating an in-progress check. + */ +async function createFailedSkillCheck(octokit, skillName, error, options) { + const summary = failureSummary(error); + const { data } = await octokit.checks.create({ + owner: options.owner, + repo: options.repo, + name: `warden: ${skillName}`, + head_sha: options.headSha, + status: 'completed', + conclusion: 'failure', + completed_at: new Date().toISOString(), + output: { + title: 'Skill execution failed', + summary, + }, + }); + await setCheckDetailsUrl(octokit, options, data); + return { + checkRunId: data.id, + url: data.html_url ?? '', + }; +} +/** + * Create the core warden check run. + * The check is created with status: in_progress. + */ +async function createCoreCheck(octokit, options) { + const { data } = await octokit.checks.create({ + owner: options.owner, + repo: options.repo, + name: 'warden', + head_sha: options.headSha, + status: 'in_progress', + started_at: new Date().toISOString(), + }); + await setCheckDetailsUrl(octokit, options, data); + return { + checkRunId: data.id, + url: data.html_url ?? '', + }; +} +/** + * Create a completed core warden check with overall summary. + */ +async function createCompletedCoreCheck(octokit, summaryData, conclusion, options) { + const summary = buildCoreSummary(summaryData); + const title = summaryData.title ?? (summaryData.totalFindings === 0 + ? 'No issues' + : `${summaryData.totalFindings} issue${summaryData.totalFindings === 1 ? '' : 's'}`); + const { data } = await octokit.checks.create({ + owner: options.owner, + repo: options.repo, + name: 'warden', + head_sha: options.headSha, + status: 'completed', + conclusion, + completed_at: new Date().toISOString(), + output: { + title, + summary, + }, + }); + await setCheckDetailsUrl(octokit, options, data); + return { + checkRunId: data.id, + url: data.html_url ?? '', + }; +} +/** + * Update the core warden check with overall summary. + */ +async function updateCoreCheck(octokit, checkRunId, summaryData, conclusion, options) { + const summary = buildCoreSummary(summaryData); + const title = summaryData.title ?? (summaryData.totalFindings === 0 + ? 'No issues' + : `${summaryData.totalFindings} issue${summaryData.totalFindings === 1 ? '' : 's'}`); + await octokit.checks.update({ + owner: options.owner, + repo: options.repo, + check_run_id: checkRunId, + status: 'completed', + conclusion, + completed_at: new Date().toISOString(), + output: { + title, + summary, + }, + }); +} +/** + * Format a file location as a markdown code span. + */ +function formatLocation(location) { + const { path, startLine, endLine } = location; + const lineRange = endLine && endLine !== startLine ? `${startLine}-${endLine}` : `${startLine}`; + return `\`${path}:${lineRange}\``; +} +/** + * Render findings grouped by severity as collapsible markdown sections. + */ +function renderFindingsSections(findings) { + const lines = []; + const findingsBySeverity = new Map(); + for (const finding of findings) { + const existing = findingsBySeverity.get(finding.severity) ?? []; + existing.push(finding); + findingsBySeverity.set(finding.severity, existing); + } + const severityOrder = ['high', 'medium', 'low']; + for (const severity of severityOrder) { + const group = findingsBySeverity.get(severity); + if (!group?.length) + continue; + const label = severity.charAt(0).toUpperCase() + severity.slice(1); + lines.push(`### ${label}`, ''); + for (const finding of group) { + const location = finding.location ? ` - ${formatLocation(finding.location)}` : ''; + lines.push('
'); + lines.push(`${(0,utils/* escapeHtml */.ZD)(finding.title)}${location}`, ''); + lines.push((0,utils/* escapeHtml */.ZD)(finding.description), ''); + if (finding.additionalLocations?.length) { + lines.push('Also found at:'); + for (const loc of finding.additionalLocations) { + lines.push(`- ${formatLocation(loc)}`); + } + lines.push(''); + } + lines.push('
', ''); + } + } + return lines; +} +/** + * Render a stats footer line (duration, tokens, cost). + */ +function renderStatsFooter(durationMs, usage, auxiliaryUsage) { + const total = (0,formatters/* totalUsageStats */.Dc)(usage, auxiliaryUsage); + if (durationMs === undefined && !total) + return []; + const parts = []; + if (durationMs !== undefined) { + parts.push(`⏱ ${(0,formatters/* formatDuration */.a3)(durationMs)}`); + } + if (total) { + parts.push(`${(0,formatters/* formatTokens */._y)(total.inputTokens)} in / ${(0,formatters/* formatTokens */._y)(total.outputTokens)} out`); + parts.push((0,formatters/* formatCost */.BD)(total.costUSD)); + } + return ['---', `${parts.join(' · ')}`]; +} +/** + * Build the summary markdown for a skill check. + */ +function buildSkillSummary(report) { + const lines = [(0,utils/* escapeHtml */.ZD)(report.summary), '']; + if (report.findings.length === 0) { + lines.push('No issues found.'); + } + else { + const sortedFindings = [...report.findings].sort((a, b) => types/* SEVERITY_ORDER */.B[a.severity] - types/* SEVERITY_ORDER */.B[b.severity]); + lines.push(...renderFindingsSections(sortedFindings)); + } + lines.push(...renderStatsFooter(report.durationMs, report.usage, report.auxiliaryUsage)); + return lines.join('\n'); +} +/** Maximum findings to show in the summary */ +const MAX_SUMMARY_FINDINGS = 10; +/** + * Build the summary markdown for the core warden check. + */ +function buildCoreSummary(data) { + const lines = []; + // Sort findings by severity and take top N + const sortedFindings = [...data.findings].sort((a, b) => types/* SEVERITY_ORDER */.B[a.severity] - types/* SEVERITY_ORDER */.B[b.severity]); + const topFindings = sortedFindings.slice(0, MAX_SUMMARY_FINDINGS); + if (topFindings.length > 0) { + lines.push(...renderFindingsSections(topFindings)); + if (data.totalFindings > topFindings.length) { + const remaining = data.totalFindings - topFindings.length; + lines.push(`*...and ${remaining} more*`, ''); + } + } + else { + lines.push(data.message ? (0,utils/* escapeHtml */.ZD)(data.message) : 'No issues found.', ''); + } + // Skills table in collapsible section + const hasSkillStats = data.skillResults.some((s) => s.durationMs !== undefined || s.usage || s.auxiliaryUsage); + const skillPlural = data.totalSkills === 1 ? '' : 's'; + lines.push('
'); + lines.push(`${data.totalSkills} skill${skillPlural} analyzed`, ''); + if (hasSkillStats) { + lines.push('| Skill | Findings | Duration | Cost |', '|-------|----------|----------|------|'); + for (const skill of data.skillResults) { + const duration = skill.durationMs !== undefined ? (0,formatters/* formatDuration */.a3)(skill.durationMs) : '-'; + const costUSD = (0,formatters/* totalUsageCost */.lg)(skill.usage, skill.auxiliaryUsage); + const cost = costUSD !== undefined ? (0,formatters/* formatCost */.BD)(costUSD) : '-'; + lines.push(`| ${skill.name} | ${skill.findingCount} | ${duration} | ${cost} |`); + } + } + else { + lines.push('| Skill | Findings |', '|-------|----------|'); + for (const skill of data.skillResults) { + lines.push(`| ${skill.name} | ${skill.findingCount} |`); + } + } + lines.push('', '
', ''); + lines.push(...renderStatsFooter(data.totalDurationMs, data.totalUsage, data.totalAuxiliaryUsage)); + return lines.join('\n'); +} +/** + * Aggregate severity counts from multiple reports. + */ +function aggregateSeverityCounts(reports) { + const counts = { + high: 0, + medium: 0, + low: 0, + }; + for (const report of reports) { + for (const finding of report.findings) { + counts[finding.severity]++; + } + } + return counts; +} + +// EXTERNAL MODULE: ./src/sdk/usage.ts +var usage = __webpack_require__(44759); +;// CONCATENATED MODULE: ./src/action/checks/manager.ts +/** + * Check Manager + * + * Manages GitHub Check runs for Warden triggers. + * Wraps the core github-checks module with action-specific logic. + */ + + +// Re-export types and functions that are used directly + +// ----------------------------------------------------------------------------- +// Aggregate Functions +// ----------------------------------------------------------------------------- +/** + * Aggregate usage stats from multiple reports. + */ +function aggregateUsage(reports) { + const reportsWithUsage = reports.filter((r) => r.usage); + if (reportsWithUsage.length === 0) + return undefined; + const seed = { + inputTokens: 0, + outputTokens: 0, + cacheReadInputTokens: 0, + cacheCreationInputTokens: 0, + cacheCreation5mInputTokens: 0, + cacheCreation1hInputTokens: 0, + webSearchRequests: 0, + costUSD: 0, + }; + return reportsWithUsage.reduce((acc, r) => { + acc.inputTokens += r.usage?.inputTokens ?? 0; + acc.outputTokens += r.usage?.outputTokens ?? 0; + acc.cacheReadInputTokens = (acc.cacheReadInputTokens ?? 0) + (r.usage?.cacheReadInputTokens ?? 0); + acc.cacheCreationInputTokens = (acc.cacheCreationInputTokens ?? 0) + (r.usage?.cacheCreationInputTokens ?? 0); + acc.cacheCreation5mInputTokens = (acc.cacheCreation5mInputTokens ?? 0) + (r.usage?.cacheCreation5mInputTokens ?? 0); + acc.cacheCreation1hInputTokens = (acc.cacheCreation1hInputTokens ?? 0) + (r.usage?.cacheCreation1hInputTokens ?? 0); + acc.webSearchRequests = (acc.webSearchRequests ?? 0) + (r.usage?.webSearchRequests ?? 0); + acc.costUSD += r.usage?.costUSD ?? 0; + return acc; + }, seed); +} +/** + * Build core check summary data from trigger results. + */ +function buildCoreSummaryData(results, reports) { + // Aggregate auxiliary usage across all reports + let totalAuxiliaryUsage; + for (const r of reports) { + if (r.auxiliaryUsage) { + totalAuxiliaryUsage = (0,usage/* mergeAuxiliaryUsage */.wV)(totalAuxiliaryUsage, r.auxiliaryUsage); + } + } + return { + totalSkills: results.length, + totalFindings: reports.reduce((sum, r) => sum + r.findings.length, 0), + findingsBySeverity: aggregateSeverityCounts(reports), + totalDurationMs: reports.some((r) => r.durationMs !== undefined) + ? reports.reduce((sum, r) => sum + (r.durationMs ?? 0), 0) + : undefined, + totalUsage: aggregateUsage(reports), + totalAuxiliaryUsage, + findings: reports.flatMap((r) => r.findings), + skillResults: results.map((r) => ({ + name: r.triggerName, + findingCount: r.report?.findings.length ?? 0, + conclusion: r.report + ? determineConclusion(r.report.findings, r.failOn, r.failCheck) + : 'failure', + durationMs: r.report?.durationMs, + usage: r.report?.usage, + auxiliaryUsage: r.report?.auxiliaryUsage, + })), + }; +} +/** + * Determine overall core check conclusion. + */ +function determineCoreConclusion(shouldFailAction, totalFindings) { + if (shouldFailAction) { + return 'failure'; + } + if (totalFindings > 0) { + return 'neutral'; + } + return 'success'; +} + + +/***/ }), + +/***/ 29547: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ captureActionTriggerError) +/* harmony export */ }); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30340); +/* harmony import */ var _sdk_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(98229); + + +function shouldFingerprintTriggerError(code) { + return (code === 'provider_unavailable' + || code === 'all_hunks_failed' + || code === 'invalid_model_selector'); +} +/** + * Capture trigger failures with stable tags and grouped fingerprints. + */ +function captureActionTriggerError(error, context) { + const { code } = (0,_sdk_errors_js__WEBPACK_IMPORTED_MODULE_1__/* .classifyError */ .fe)(error); + const providerContext = error instanceof _sdk_errors_js__WEBPACK_IMPORTED_MODULE_1__/* .SkillRunnerError */ .cy ? error.providerContext : undefined; + _sentry_js__WEBPACK_IMPORTED_MODULE_0__/* .Sentry.captureException */ .sQ.captureException(error, { + tags: { + 'warden.trigger.name': context.triggerName, + 'gen_ai.agent.name': context.skillName, + 'warden.error.code': code, + ...(providerContext?.provider ? { 'gen_ai.provider.name': providerContext.provider } : {}), + ...(providerContext?.model ? { 'gen_ai.request.model': providerContext.model } : {}), + }, + ...(providerContext ? { contexts: { provider_error: { ...providerContext } } } : {}), + ...(shouldFingerprintTriggerError(code) ? { fingerprint: ['warden', code] } : {}), + }); + return code; +} + + +/***/ }), + +/***/ 45154: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Z: () => (/* binding */ evaluateFixAttempts), + l: () => (/* reexport */ postThreadReply) +}); + +// EXTERNAL MODULE: ./src/output/dedup.ts +var dedup = __webpack_require__(3941); +// EXTERNAL MODULE: ./src/sdk/usage.ts +var usage = __webpack_require__(44759); +// EXTERNAL MODULE: ./src/output/stale.ts +var stale = __webpack_require__(95768); +// EXTERNAL MODULE: ./src/sentry.ts +var sentry = __webpack_require__(30340); +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js + 7 modules +var schemas = __webpack_require__(51737); +// EXTERNAL MODULE: ./src/sdk/prompt-sections.ts +var prompt_sections = __webpack_require__(49893); +// EXTERNAL MODULE: ./src/sdk/runtimes/index.ts + 1 modules +var runtimes = __webpack_require__(23473); +// EXTERNAL MODULE: ./src/types/index.ts +var types = __webpack_require__(78481); +;// CONCATENATED MODULE: ./src/action/fix-evaluation/types.ts + + + +const FixJudgeVerdictSchema = schemas/* object */.Ikc({ + status: types/* FixStatusSchema */.$3, + reasoning: schemas/* string */.YjP(), +}); + +// EXTERNAL MODULE: ./src/cli/output/tty.ts +var tty = __webpack_require__(80029); +;// CONCATENATED MODULE: ./src/action/fix-evaluation/github.ts + +/** + * Fetch the patches and commit messages between two commits. + */ +async function fetchFollowUpChanges(octokit, owner, repo, baseSha, headSha) { + const { data } = await octokit.repos.compareCommits({ + owner, + repo, + base: baseSha, + head: headSha, + }); + const patches = new Map(); + for (const file of data.files ?? []) { + if (file.patch) { + patches.set(file.filename, file.patch); + } + } + const commitMessages = []; + for (const commit of data.commits ?? []) { + if (commit.commit.message) { + commitMessages.push(commit.commit.message); + } + } + return { patches, commitMessages }; +} +/** + * Fetch file content at a specific commit SHA. + */ +async function fetchFileContent(octokit, owner, repo, path, sha) { + const { data } = await octokit.repos.getContent({ + owner, + repo, + path, + ref: sha, + }); + if (Array.isArray(data)) { + throw new Error(`Path "${path}" is a directory, not a file`); + } + if (data.type !== 'file' || !data.content) { + throw new Error(`Path "${path}" is not a file or content unavailable`); + } + return Buffer.from(data.content, 'base64').toString('utf-8'); +} +/** + * Fetch specific lines from a file at a commit. + * startLine and endLine are 1-indexed and inclusive. + */ +async function fetchFileLines(octokit, owner, repo, path, sha, startLine, endLine) { + const content = await fetchFileContent(octokit, owner, repo, path, sha); + const lines = content.split('\n'); + return lines + .slice(startLine - 1, endLine) + .map((line, i) => `${startLine + i}: ${line}`) + .join('\n'); +} +const ADD_THREAD_REPLY_MUTATION = ` + mutation($threadId: ID!, $body: String!) { + addPullRequestReviewThreadReply(input: { + pullRequestReviewThreadId: $threadId, + body: $body + }) { + comment { + id + } + } + } +`; +/** + * Post a reply to a review thread. + */ +async function postThreadReply(octokit, threadId, body) { + try { + await octokit.graphql(ADD_THREAD_REPLY_MUTATION, { + threadId, + body, + }); + } + catch (error) { + (0,tty/* warnAction */.T6)(`Failed to post thread reply: ${error}`); + throw error; + } +} +/** + * Format a reply for a failed fix attempt. + */ +function formatFailedFixReply(commitSha, reasoning) { + const shortSha = commitSha.slice(0, 7); + return `**Fix attempt detected** (commit ${shortSha}) + +${reasoning} + +The original issue appears unresolved. Please review and try again. + +Evaluated by Warden`; +} + +;// CONCATENATED MODULE: ./src/action/fix-evaluation/judge.ts + + + + + + +const TOOL_DEFINITIONS = [ + { + name: 'get_file_diff', + description: 'Get the unified diff showing what changed in a file between the two commits.', + inputSchema: { + type: 'object', + properties: { + path: { type: 'string', description: 'File path to get diff for' }, + }, + required: ['path'], + }, + }, + { + name: 'get_file_at_commit', + description: 'Get file content at a specific commit. Use "before" for pre-fix state, "after" for post-fix state. Optionally specify line range.', + inputSchema: { + type: 'object', + properties: { + path: { type: 'string', description: 'File path to fetch' }, + commit: { type: 'string', enum: ['before', 'after'], description: 'before = pre-fix, after = post-fix' }, + startLine: { type: 'number', description: 'Start line (1-indexed, inclusive)' }, + endLine: { type: 'number', description: 'End line (1-indexed, inclusive)' }, + }, + required: ['path', 'commit'], + }, + }, +]; +function buildPrompt(input) { + const { comment, changedFiles, codeBeforeFix, codeAfterFix, commitMessages } = input; + const afterCodeSection = codeAfterFix + ? (0,prompt_sections/* buildTaggedSection */.sG)('after_code', codeAfterFix) + : undefined; + const commitMessagesSection = commitMessages && commitMessages.length > 0 + ? (0,prompt_sections/* buildTaggedSection */.sG)('developer_intent', [ + ...commitMessages.map((msg, i) => `${i + 1}. ${msg.split('\n')[0]}`), + '', + 'Use these to help understand what the developer was trying to do. A commit mentioning "fix" or the issue topic suggests intent to address it.', + ]) + : undefined; + const investigationStrategy = codeAfterFix + ? `Compare the BEFORE and AFTER code above to determine if the issue was fixed. +Use tools only if you need additional context: + +- \`get_file_diff(path)\` - See unified diff of changes to a file +- \`get_file_at_commit(path, "before"|"after", startLine?, endLine?)\` - Read more file content if needed` + : `Use tools to determine if the issue was fixed: + +1. **Start with get_file_diff** on the issue's file (if changed) to see what was modified +2. **Use get_file_at_commit with "after"** to see the current state at the issue location +3. **Check related files** if the fix might involve changes elsewhere (imports, shared utilities, etc.) + +Tools: +- \`get_file_diff(path)\` - See unified diff of changes to a file +- \`get_file_at_commit(path, "before"|"after", startLine?, endLine?)\` - Read file content at either commit`; + return (0,prompt_sections/* joinPromptSections */.hZ)([ + ` +Judge whether a code change fixed a reported issue. +`, + ` +Does the reported issue still exist in the code after this commit? +`, + ` +Choose ONE verdict based on these criteria: + +resolved - The issue NO LONGER EXISTS. Evidence: +- The problematic code was corrected (directly or via equivalent fix) +- The code was refactored in a way that eliminates the issue by design +- The problematic code was intentionally removed (file deleted, function removed, dead code cleaned up) + +attempted_failed - A fix was CLEARLY ATTEMPTED but the issue PERSISTS. Evidence: +- Changes DIRECTLY modify the reported file at or near the issue location +- AND the changes appear specifically intended to address THIS issue +- BUT the core issue remains (wrong fix, incomplete fix, edge cases missed) +- Use this ONLY when there's clear evidence of intent to fix THIS specific issue +- Do NOT use for general refactoring, unrelated bug fixes, or changes to other files +- When in doubt between attempted_failed and not_attempted, prefer not_attempted + +not_attempted - The issue was NOT ADDRESSED. Evidence: +- No changes to the problematic code or its logic +- Changes are unrelated (different feature, different bug, unrelated refactor) +- The reported code is identical or functionally unchanged +- Changes are in other files with no clear connection to the reported issue +`, + (0,prompt_sections/* buildTaggedSection */.sG)('reported_issue', [ + `${comment.title}`, + `${comment.path}`, + `${comment.line}`, + '', + comment.description, + '', + ]), + (0,prompt_sections/* buildTaggedSection */.sG)('before_code', codeBeforeFix), + afterCodeSection, + (0,prompt_sections/* buildFileListSection */.Oy)('changed_files', changedFiles), + commitMessagesSection, + (0,prompt_sections/* buildTaggedSection */.sG)('investigation_strategy', investigationStrategy), + (0,prompt_sections/* buildJsonOutputSection */.j2)(`{"status": "resolved|attempted_failed|not_attempted", "reasoning": "One sentence explaining your verdict"} +Put your one-sentence explanation in the "reasoning" field.`), + ]); +} +const GetFileDiffInput = schemas/* object */.Ikc({ + path: schemas/* string */.YjP(), +}); +const GetFileAtCommitInput = schemas/* object */.Ikc({ + path: schemas/* string */.YjP(), + commit: schemas/* enum */.k5n(['before', 'after']), + startLine: schemas/* number */.aig().optional(), + endLine: schemas/* number */.aig().optional(), +}); +function createToolExecutor(ctx) { + return async (name, input) => { + if (name === 'get_file_diff') { + const parsed = GetFileDiffInput.safeParse(input); + if (!parsed.success) { + return `Invalid input: ${parsed.error.message}`; + } + const patch = ctx.patches.get(parsed.data.path); + return patch ?? 'No changes found for this file'; + } + if (name === 'get_file_at_commit') { + const parsed = GetFileAtCommitInput.safeParse(input); + if (!parsed.success) { + return `Invalid input: ${parsed.error.message}`; + } + const { path, commit, startLine, endLine } = parsed.data; + const sha = commit === 'before' ? ctx.baseSha : ctx.headSha; + try { + if (startLine !== undefined && endLine !== undefined) { + return await fetchFileLines(ctx.octokit, ctx.owner, ctx.repo, path, sha, startLine, endLine); + } + const content = await fetchFileContent(ctx.octokit, ctx.owner, ctx.repo, path, sha); + const lines = content.split('\n'); + if (lines.length > 100) { + const numbered = lines.slice(0, 100).map((line, i) => `${i + 1}: ${line}`); + return `${numbered.join('\n')}\n\n[... ${lines.length - 100} more lines truncated]`; + } + return lines.map((line, i) => `${i + 1}: ${line}`).join('\n'); + } + catch (error) { + return `Error fetching file: ${error instanceof Error ? error.message : String(error)}`; + } + } + return `Unknown tool: ${name}`; + }; +} +/** + * Evaluate whether a code change fixed a reported issue. + * Uses Haiku with tool use to explore the changes. + */ +async function evaluateFix(input, context, apiKey, runtimeOptionsOrMaxRetries) { + const runtimeOptions = runtimeOptionsOrMaxRetries !== null && typeof runtimeOptionsOrMaxRetries === 'object' + ? runtimeOptionsOrMaxRetries + : runtimeOptionsOrMaxRetries == null + ? {} + : { maxRetries: runtimeOptionsOrMaxRetries }; + const fallback = { + verdict: { status: 'not_attempted', reasoning: 'Evaluation failed' }, + usage: (0,usage/* emptyUsage */.ly)(), + usedFallback: true, + }; + const prompt = buildPrompt(input); + const executeTool = createToolExecutor(context); + const result = await (0,runtimes/* getRuntime */.fr)(runtimeOptions.runtime).runAuxiliary({ + task: 'fix_evaluation', + agentName: input.skillName, + apiKey, + prompt, + schema: FixJudgeVerdictSchema, + tools: TOOL_DEFINITIONS, + executeTool, + model: runtimeOptions.model, + effort: runtimeOptions.effort, + maxIterations: 5, + maxRetries: runtimeOptions.maxRetries, + }); + if (result.success) { + return { verdict: result.data, usage: result.usage, usedFallback: false }; + } + return { ...fallback, usage: result.usage }; +} + +;// CONCATENATED MODULE: ./src/action/fix-evaluation/index.ts + + + + + + + +/** Maximum comments to evaluate per run */ +const MAX_EVALUATIONS = 20; +const EVALUATION_FAILED_REASONING = 'Evaluation failed'; +const RE_DETECTED_REASONING = 'The fix attempt was made, but the same issue was detected again in the updated code.'; +/** Extract finding ID (e.g. "WRZ-XPL") from a comment title like "[WRZ-XPL] Some title" */ +function extractFindingId(title) { + const match = title.match(/^\[([^\]]+)\]\s*/); + return match?.[1]; +} +function getCommentFindingId(comment) { + return comment.findingId ?? extractFindingId(comment.title) ?? (comment.body ? (0,dedup/* parseWardenFindingId */.rW)(comment.body) : undefined); +} +function getCommentSkill(comment) { + return comment.skills?.[0] ?? (comment.body ? (0,dedup/* parseWardenSkills */.dh)(comment.body)[0] : undefined); +} +/** Number of lines of context around the finding location */ +const CONTEXT_LINES = 20; +/** + * Extract numbered lines from content. + */ +function extractLines(content, start, end) { + const lines = content.split('\n'); + return lines + .slice(start - 1, end) + .map((line, i) => `${start + i}: ${line}`) + .join('\n'); +} +/** + * Fetch code snippet at a finding location at a specific commit. + */ +async function fetchCodeAtLocation(octokit, owner, repo, comment, sha, contextLines = CONTEXT_LINES) { + const targetLine = comment.line; + const startLine = Math.max(1, targetLine - contextLines); + const endLine = targetLine + contextLines; + try { + const content = await fetchFileContent(octokit, owner, repo, comment.path, sha); + return extractLines(content, startLine, endLine); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes('Not Found')) { + return '(file does not exist at this commit)'; + } + throw error; + } +} +/** + * Check if an issue was re-detected in the current findings. + */ +function wasReDetected(comment, currentFindings) { + return currentFindings.some((finding) => (0,stale/* findingMatchesComment */.i0)(finding, comment)); +} +function createFallbackEvaluation() { + return { + verdict: { status: 'not_attempted', reasoning: EVALUATION_FAILED_REASONING }, + usage: (0,usage/* emptyUsage */.ly)(), + usedFallback: true, + }; +} +/** + * Apply Warden's final verdict precedence and record the side effects for it. + */ +function recordEvaluationOutcome(args) { + const { result, comment, findingId, skill, context, evalResult, durationMs, reDetected, uniqueCodeChangedThreadIds, uniqueResolvedThreadIds, } = args; + if (evalResult.usedFallback) { + result.failedEvaluations++; + } + let finalVerdict; + let reasoning = evalResult.verdict.reasoning; + if (reDetected) { + finalVerdict = 're_detected'; + reasoning = RE_DETECTED_REASONING; + if (comment.threadId) { + uniqueCodeChangedThreadIds.add(comment.threadId); + } + result.toReply.push({ + comment, + replyBody: formatFailedFixReply(context.headSha, RE_DETECTED_REASONING), + commitSha: context.headSha, + }); + } + else if (evalResult.usedFallback) { + finalVerdict = 'eval_error'; + } + else if (evalResult.verdict.status === 'not_attempted') { + finalVerdict = 'not_attempted'; + } + else if (evalResult.verdict.status === 'resolved') { + finalVerdict = 'resolved'; + if (comment.threadId) { + uniqueCodeChangedThreadIds.add(comment.threadId); + uniqueResolvedThreadIds.add(comment.threadId); + } + result.toResolve.push(comment); + } + else { + finalVerdict = 'attempted_failed'; + if (comment.threadId) { + uniqueCodeChangedThreadIds.add(comment.threadId); + } + result.toReply.push({ + comment, + replyBody: formatFailedFixReply(context.headSha, evalResult.verdict.reasoning), + commitSha: context.headSha, + }); + } + result.evaluations.push({ + findingId, + skill, + path: comment.path, + line: comment.line, + title: comment.title, + verdict: finalVerdict, + reasoning, + durationMs, + usage: evalResult.usage, + usedFallback: evalResult.usedFallback, + }); + (0,sentry/* emitFixEvalVerdictMetric */.E1)(finalVerdict, skill, { usedFallback: evalResult.usedFallback }); + return finalVerdict; +} +/** + * Evaluate fix attempts for all unresolved Warden comments. + * + * Flow: + * 1. Fetch patches between base and head SHAs + * 2. For each unresolved comment, let judge explore changes with tools + * 3. Cross-check against current findings for re-detection (safety override) + * 4. Categorize into toResolve and toReply + * 5. Accumulate usage stats from all evaluations + */ +async function evaluateFixAttempts(octokit, comments, context, currentFindings, apiKey, runtimeOptionsOrMaxRetries) { + const runtimeOptions = runtimeOptionsOrMaxRetries !== null && typeof runtimeOptionsOrMaxRetries === 'object' + ? runtimeOptionsOrMaxRetries + : runtimeOptionsOrMaxRetries == null + ? {} + : { maxRetries: runtimeOptionsOrMaxRetries }; + return sentry/* Sentry.startSpan */.sQ.startSpan({ + op: 'fix_eval.run', + name: 'evaluate fix attempts', + attributes: { + 'warden.fix_eval.comment_count': comments.length, + }, + }, async (outerSpan) => { + const result = { + toResolve: [], + toReply: [], + skipped: 0, + evaluated: 0, + failedEvaluations: 0, + uniqueFindingsEvaluated: 0, + uniqueFindingsCodeChanged: 0, + uniqueFindingsResolved: 0, + usage: (0,usage/* emptyUsage */.ly)(), + evaluations: [], + }; + // Filter to unresolved Warden comments only + const unresolvedComments = comments.filter((c) => c.isWarden && !c.isResolved && c.threadId); + if (unresolvedComments.length === 0) { + return result; + } + // Fetch patches and commit messages between base and head + const { patches, commitMessages } = await fetchFollowUpChanges(octokit, context.owner, context.repo, context.baseSha, context.headSha); + if (patches.size === 0) { + result.skipped = unresolvedComments.length; + return result; + } + // Limit evaluations + const commentsToEvaluate = unresolvedComments.slice(0, MAX_EVALUATIONS); + if (unresolvedComments.length > MAX_EVALUATIONS) { + result.skipped = unresolvedComments.length - MAX_EVALUATIONS; + } + const toolContext = { + octokit, + owner: context.owner, + repo: context.repo, + baseSha: context.baseSha, + headSha: context.headSha, + patches, + }; + const changedFiles = [...patches.keys()]; + const usages = []; + const uniqueEvaluatedThreadIds = new Set(); + const uniqueCodeChangedThreadIds = new Set(); + const uniqueResolvedThreadIds = new Set(); + for (const comment of commentsToEvaluate) { + const findingId = getCommentFindingId(comment); + const skill = getCommentSkill(comment); + // Fetch code at the issue location before the fix + let codeBeforeFix; + try { + codeBeforeFix = await fetchCodeAtLocation(octokit, context.owner, context.repo, comment, context.baseSha); + } + catch (error) { + sentry/* Sentry.captureException */.sQ.captureException(error, { tags: { operation: 'fetch_fix_context' } }); + result.skipped++; + continue; + } + result.evaluated++; + if (comment.threadId) { + uniqueEvaluatedThreadIds.add(comment.threadId); + } + // Fetch code after fix (optional, reduces tool calls) + let codeAfterFix; + try { + codeAfterFix = await fetchCodeAtLocation(octokit, context.owner, context.repo, comment, context.headSha); + } + catch { + // Non-fatal: judge can still use tools to investigate + } + const reDetected = wasReDetected(comment, currentFindings); + await sentry/* Sentry.startSpan */.sQ.startSpan({ + op: 'fix_eval.evaluate', + name: `evaluate fix ${comment.path}:${comment.line}`, + attributes: { + 'code.file.path': comment.path, + 'code.line.number': comment.line, + 'warden.fix_eval.finding_id': findingId ?? 'unknown', + ...(skill && { 'gen_ai.agent.name': skill }), + }, + }, async (evalSpan) => { + const startTime = performance.now(); + let evalResult; + try { + evalResult = await evaluateFix({ comment, skillName: skill, changedFiles, codeBeforeFix, codeAfterFix, commitMessages }, toolContext, apiKey, runtimeOptions); + } + catch (error) { + sentry/* Sentry.captureException */.sQ.captureException(error, { tags: { operation: 'evaluate_fix_attempt' } }); + evalResult = createFallbackEvaluation(); + } + const durationMs = performance.now() - startTime; + evalSpan.setAttribute('warden.fix_eval.raw_verdict', evalResult.verdict.status); + evalSpan.setAttribute('warden.fix_eval.used_fallback', evalResult.usedFallback); + usages.push(evalResult.usage); + const finalVerdict = recordEvaluationOutcome({ + result, + comment, + findingId, + skill, + context, + evalResult, + durationMs, + reDetected, + uniqueCodeChangedThreadIds, + uniqueResolvedThreadIds, + }); + evalSpan.setAttribute('warden.fix_eval.verdict', finalVerdict); + }); + } + result.usage = usages.length > 0 ? (0,usage/* aggregateUsage */.Z$)(usages) : (0,usage/* emptyUsage */.ly)(); + result.uniqueFindingsEvaluated = uniqueEvaluatedThreadIds.size; + result.uniqueFindingsCodeChanged = uniqueCodeChangedThreadIds.size; + result.uniqueFindingsResolved = uniqueResolvedThreadIds.size; + const codeChangeRate = result.uniqueFindingsEvaluated > 0 + ? result.uniqueFindingsCodeChanged / result.uniqueFindingsEvaluated + : 0; + // Set summary attributes and emit metrics + outerSpan.setAttribute('warden.fix_eval.evaluated', result.evaluated); + outerSpan.setAttribute('warden.fix_eval.resolved', result.toResolve.length); + outerSpan.setAttribute('warden.fix_eval.failed', result.failedEvaluations); + outerSpan.setAttribute('warden.fix_eval.skipped', result.skipped); + outerSpan.setAttribute('warden.fix_eval.unique_findings.evaluated', result.uniqueFindingsEvaluated); + outerSpan.setAttribute('warden.fix_eval.unique_findings.code_changed', result.uniqueFindingsCodeChanged); + outerSpan.setAttribute('warden.fix_eval.unique_findings.resolved', result.uniqueFindingsResolved); + outerSpan.setAttribute('warden.fix_eval.unique_findings.code_change_rate', codeChangeRate); + (0,sentry/* emitFixEvalMetrics */.ii)(result.evaluated, result.toResolve.length, result.failedEvaluations, result.skipped, result.uniqueFindingsEvaluated, result.uniqueFindingsCodeChanged, result.uniqueFindingsResolved); + return result; + }); +} + + +/***/ }), + +/***/ 13778: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Bc: () => (/* binding */ incrementalExternalId), +/* harmony export */ Cv: () => (/* binding */ planIncrementalReview), +/* harmony export */ GR: () => (/* binding */ feedbackDelivered), +/* harmony export */ P7: () => (/* binding */ createIncrementalBaselineSource), +/* harmony export */ SW: () => (/* binding */ hasOpenCarriedComment), +/* harmony export */ Z5: () => (/* binding */ collectCarriedRanges), +/* harmony export */ lO: () => (/* binding */ reviewedEverything), +/* harmony export */ qw: () => (/* binding */ baselineExternalId), +/* harmony export */ y3: () => (/* binding */ isOnCarriedHunk) +/* harmony export */ }); +/* unused harmony exports hunkFingerprint, buildReviewedHunkIndex */ +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77598); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_crypto__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _diff_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(96497); +/* harmony import */ var _utils_version_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56317); +/** + * Incremental PR review. + * + * A skill check that completes cleanly records a fingerprint of the skill and + * its effective config in the check run `external_id`. On a later push, Warden + * finds the newest earlier PR commit with a matching check, rebuilds that + * commit's PR diff, and skips current hunks whose content was already + * reviewed there. Hunks match on file path plus hunk body, not line numbers, + * so rebases and merges from the base branch do not trigger re-review of + * code the PR did not change. Only checks written by the GitHub App named in + * `incrementalApp` count, so look-alike checks from other apps cannot skip review. + * + * Every lookup fails open: if the baseline cannot be found or read, the skill + * reviews the full PR as it would without incremental review. + */ + + + +const EXTERNAL_ID_PREFIX = 'warden-incremental:v1:'; +/** Earlier PR commits searched for a baseline check, newest first. */ +const MAX_BASELINE_COMMITS = 10; +function sha256(value) { + return (0,node_crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(value).digest('hex'); +} +/** Fingerprint a hunk by path and body. Line numbers in the @@ header are ignored. */ +function hunkFingerprint(filename, lines) { + let end = lines.length; + while (end > 0 && lines[end - 1] === '') + end--; + return sha256(`${filename}\0${lines.slice(0, end).join('\n')}`); +} +/** Index every hunk in a set of file patches. */ +function buildReviewedHunkIndex(files) { + const index = new Map(); + for (const file of files) { + if (!file.patch) + continue; + for (const hunk of (0,_diff_index_js__WEBPACK_IMPORTED_MODULE_1__/* .parsePatch */ .iz)(file.patch)) { + const key = hunkFingerprint(file.filename, hunk.lines); + index.set(key, (index.get(key) ?? 0) + 1); + } + } + return index; +} +/** + * Decide which current hunks were already reviewed. + * Each baseline hunk covers at most one current hunk with the same content. + */ +function planIncrementalReview(files, reviewed) { + const remaining = new Map(reviewed); + const skipHunks = new Map(); + const carriedRanges = []; + for (const file of files) { + if (!file.patch) + continue; + (0,_diff_index_js__WEBPACK_IMPORTED_MODULE_1__/* .parsePatch */ .iz)(file.patch).forEach((hunk, index) => { + const key = hunkFingerprint(file.filename, hunk.lines); + const available = remaining.get(key) ?? 0; + if (available === 0) + return; + remaining.set(key, available - 1); + let skipped = skipHunks.get(file.filename); + if (!skipped) { + skipped = new Set(); + skipHunks.set(file.filename, skipped); + } + skipped.add(index); + carriedRanges.push({ + path: file.filename, + startLine: hunk.newStart, + endLine: hunk.newStart + Math.max(hunk.newCount, 1) - 1, + }); + }); + } + return { skipHunks, carriedRanges }; +} +/** + * Build the check run external_id for a skill run. + * Any change to the skill prompt, Warden version, or settings that affect + * what gets analyzed or reported yields a new id, which forces a full review. + * The base branch is included because baselines are rebuilt against the + * current base: after a retarget, an old baseline would describe a diff that + * was never reviewed. + */ +function incrementalExternalId(trigger, skill, policy, baseBranch) { + const payload = JSON.stringify({ + warden: (0,_utils_version_js__WEBPACK_IMPORTED_MODULE_2__/* .getVersion */ .H)(), + base: baseBranch, + skill: skill.name, + prompt: sha256(skill.prompt), + remote: trigger.remote ?? null, + filters: trigger.filters, + ignore: trigger.ignore ?? null, + scan: trigger.scan ?? null, + chunking: trigger.chunking ?? null, + model: trigger.model ?? null, + auxiliaryModel: trigger.auxiliaryModel ?? null, + auxiliaryEffort: trigger.auxiliaryEffort ?? null, + synthesisModel: trigger.synthesisModel ?? null, + maxContextFiles: trigger.maxContextFiles ?? null, + runtime: trigger.runtime ?? null, + effort: trigger.effort ?? null, + maxTurns: trigger.maxTurns ?? null, + verifyFindings: trigger.verifyFindings ?? null, + failOn: policy.failOn ?? null, + reportOn: policy.reportOn ?? null, + minConfidence: policy.minConfidence ?? null, + failCheck: policy.failCheck ?? null, + requestChanges: policy.requestChanges ?? null, + maxFindings: policy.maxFindings ?? null, + }); + return `${EXTERNAL_ID_PREFIX}${sha256(payload).slice(0, 32)}`; +} +/** + * Skip reasons decided by path alone. Paths are part of the hunk fingerprint + * and ignore config is part of the external_id, so these files stay skipped + * for as long as a baseline matches. + */ +const PATH_ONLY_SKIPS = new Set(['ignored:builtin', 'ignored:user']); +/** + * Whether a run reviewed every hunk it was given. Failed hunks and files + * dropped by scan limits were never reviewed, so the run cannot be a baseline. + * Content-based skips such as generated files also disqualify it: the baseline + * diff includes those hunks, and the file can stop looking generated later. + * Hunks a skill gate skipped were never read either, and the gate can pass + * them later when PR-wide context (title, body, manifests) changes. + */ +function reviewedEverything(report) { + if (report.error) + return false; + if ((report.failedHunks ?? 0) > 0 || (report.failedExtractions ?? 0) > 0) + return false; + if ((report.hunkGate?.skippedHunks ?? 0) > 0) + return false; + return !report.skippedFiles?.some((file) => !PATH_ONLY_SKIPS.has(file.reason)); +} +/** + * Return the external_id to record on a skill check, or undefined when the + * run must not become a baseline. Report mode only sees the replayed report, + * so completeness is decided in analyze mode and stored on `incremental`. + */ +function baselineExternalId(report) { + return report.incremental?.complete ? report.incremental.externalId : undefined; +} +/** Skip reasons that leave a finding on the check only, never on the PR. */ +const UNDELIVERED_SKIPS = new Set([ + 'max_findings', + 'no_inline_location', + 'pull_request_changed', + 'review_not_posted', +]); +/** + * Whether every reportable finding from one trigger reached the PR, either as + * a new comment or as a match on an existing one. Skipped hunks are never + * re-reported, so a run whose findings did not reach the PR is not a baseline. + */ +function feedbackDelivered(observations) { + return observations.every((o) => o.outcome !== 'failed' && !(o.outcome === 'skipped' && UNDELIVERED_SKIPS.has(o.skippedReason))); +} +/** Carried ranges from all reports, tagged with the skill that carried them. */ +function collectCarriedRanges(reports) { + return reports.flatMap((report) => (report.incremental?.carriedRanges ?? []).map((range) => ({ ...range, skill: report.skill }))); +} +/** + * Whether a comment sits on a hunk its skill carried forward without re-review. + * Carried ranges are in current-diff lines, so GitHub's current line is used + * when present: it follows the hunk when a rebase or base merge shifts it, + * while the Warden marker keeps the line the finding was first posted on and + * could land inside an unrelated carried hunk. The marker line is only a + * fallback when GitHub gives no current line. An outdated comment has no + * current line and its marker line may predate a shift, so it counts as + * carried whenever its skill carried any hunk in the same file. Keeping such + * a comment open is safe; resolving it could hide a finding nobody re-checked. + */ +function isOnCarriedHunk(comment, ranges) { + const line = comment.currentLine ?? comment.line; + return ranges.some((range) => range.path === comment.path && + (comment.isOutdated || (line >= range.startLine && line <= range.endLine)) && + (!comment.skills?.length || comment.skills.includes(range.skill))); +} +/** + * Whether an unresolved Warden comment sits on a carried hunk. Its finding + * was not re-checked, so the run cannot prove a blocking review is clear. + * `undefined` comments means the fetch failed or was skipped; with any + * carried range that counts as open, since an unknown state is not proof. + */ +function hasOpenCarriedComment(comments, ranges) { + if (ranges.length === 0) + return false; + if (comments === undefined) + return true; + return comments.some((c) => c.isWarden && !c.isResolved && isOnCarriedHunk(c, ranges)); +} +/** Baselines are keyed by check id and the app that wrote the check. */ +function baselineKey(externalId, app) { + return `${app}\n${externalId}`; +} +/** + * Create a baseline source for one pull request. Commit and check lookups run + * once per action run and are shared across skills. + * Requires `pull-requests: read`, `checks: read`, and `contents: read`. + */ +function createIncrementalBaselineSource(octokit, options) { + const warn = options.warn ?? ((message) => console.warn(message)); + let baselineShas; + const indexes = new Map(); + const findBaselineShas = async () => { + const found = new Map(); + try { + const commits = await octokit.paginate(octokit.pulls.listCommits, { + owner: options.owner, + repo: options.repo, + pull_number: options.pullNumber, + per_page: 100, + }); + const candidates = commits + .map((commit) => commit.sha) + .filter((sha) => sha !== options.headSha) + .reverse() + .slice(0, MAX_BASELINE_COMMITS); + for (const sha of candidates) { + const { data } = await octokit.checks.listForRef({ + owner: options.owner, + repo: options.repo, + ref: sha, + filter: 'latest', + per_page: 100, + }); + for (const check of data.check_runs) { + const id = check.external_id; + const app = check.app?.slug; + if (!id?.startsWith(EXTERNAL_ID_PREFIX) || !app) + continue; + const key = baselineKey(id, app); + if (found.has(key)) + continue; + if (!check.name.startsWith('warden: ') || check.status !== 'completed') + continue; + if (check.conclusion !== 'success' && check.conclusion !== 'neutral') + continue; + found.set(key, sha); + } + } + } + catch (error) { + warn(`Incremental review: could not read earlier Warden checks, reviewing the full PR: ${error}`); + } + return found; + }; + const loadIndex = async (sha) => { + try { + // Three-dot compare yields the PR diff as it stood at `sha`. Files are + // returned with the first page; per_page only limits the commit list. + const { data } = await octokit.repos.compareCommitsWithBasehead({ + owner: options.owner, + repo: options.repo, + basehead: `${options.baseSha}...${sha}`, + per_page: 1, + }); + return buildReviewedHunkIndex(data.files ?? []); + } + catch (error) { + warn(`Incremental review: could not load the diff at ${sha.slice(0, 7)}, reviewing the full PR: ${error}`); + return undefined; + } + }; + return { + async baselineFor(externalId, trustedApp) { + baselineShas ??= findBaselineShas(); + const sha = (await baselineShas).get(baselineKey(externalId, trustedApp)); + if (!sha) + return undefined; + let index = indexes.get(sha); + if (!index) { + index = loadIndex(sha); + indexes.set(sha, index); + } + const reviewed = await index; + return reviewed ? { sha, reviewed } : undefined; + }, + }; +} + + +/***/ }), + +/***/ 93857: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ C1: () => (/* binding */ validateInputs), +/* harmony export */ HC: () => (/* binding */ parseActionInputs), +/* harmony export */ Tw: () => (/* binding */ setupAuthEnv) +/* harmony export */ }); +/* harmony import */ var _sentry_warden_service_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15747); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(78481); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82272); +/** + * Action Input Parsing and Validation + * + * Handles parsing inputs from GitHub Actions environment and validates them. + */ + + + +// ----------------------------------------------------------------------------- +// Input Parsing +// ----------------------------------------------------------------------------- +/** + * Get an input value from GitHub Actions environment. + * Checks both hyphenated (native) and underscored (composite action) formats. + */ +function getInput(name, required = false) { + // Check both hyphenated (native GitHub Actions) and underscored (composite action) formats + const hyphenEnv = `INPUT_${name.toUpperCase()}`; + const underscoreEnv = `INPUT_${name.toUpperCase().replace(/-/g, '_')}`; + const value = process.env[hyphenEnv] ?? process.env[underscoreEnv] ?? ''; + if (required && !value) { + throw new Error(`Input required and not supplied: ${name}`); + } + return value; +} +/** + * Parse a string input as a boolean, returning undefined for unrecognized values. + */ +function parseBooleanInput(value) { + if (value === 'true') + return true; + if (value === 'false') + return false; + return undefined; +} +function parseModeInput(value) { + const mode = value || 'run'; + if (mode === 'run' || mode === 'analyze' || mode === 'report') { + return mode; + } + throw new Error(`Invalid mode "${mode}". Expected run, analyze, or report.`); +} +/** + * Parse action inputs from the GitHub Actions environment. + * Runtime-specific auth can be absent here; runtime setup validates it when needed. + */ +function parseActionInputs() { + // Check for auth token: supports both API keys and OAuth tokens + // Priority: input > WARDEN_ANTHROPIC_API_KEY > ANTHROPIC_API_KEY > CLAUDE_CODE_OAUTH_TOKEN + const authToken = getInput('anthropic-api-key') || + process.env['WARDEN_ANTHROPIC_API_KEY'] || + process.env['ANTHROPIC_API_KEY'] || + process.env['CLAUDE_CODE_OAUTH_TOKEN'] || + ''; + // Detect token type: OAuth tokens start with 'sk-ant-oat', API keys are other 'sk-ant-' prefixes + const isOAuthToken = authToken.startsWith('sk-ant-oat'); + const anthropicApiKey = isOAuthToken ? '' : authToken; + const oauthToken = isOAuthToken ? authToken : ''; + const failOnInput = getInput('fail-on'); + const failOn = _types_index_js__WEBPACK_IMPORTED_MODULE_1__/* .SeverityThresholdSchema */ .q$.safeParse(failOnInput).success + ? failOnInput + : undefined; + const reportOnInput = getInput('report-on'); + const reportOn = _types_index_js__WEBPACK_IMPORTED_MODULE_1__/* .SeverityThresholdSchema */ .q$.safeParse(reportOnInput).success + ? reportOnInput + : undefined; + const maxFindingsParsed = parseInt(getInput('max-findings') || '50', 10); + const parallelParsed = parseInt(getInput('parallel') || String(_utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .DEFAULT_CONCURRENCY */ .WH), 10); + const requestChanges = parseBooleanInput(getInput('request-changes')); + const failCheck = parseBooleanInput(getInput('fail-check')); + const serviceDataInput = getInput('service-data'); + const serviceData = _sentry_warden_service_api__WEBPACK_IMPORTED_MODULE_0__/* .DataProfileSchema */ .ly.safeParse(serviceDataInput); + const serviceTimeoutInput = getInput('service-timeout-ms'); + const serviceTimeoutParsed = serviceTimeoutInput ? Number(serviceTimeoutInput) : undefined; + const postChecks = parseBooleanInput(getInput('post-checks')) ?? true; + return { + anthropicApiKey, + oauthToken, + githubToken: getInput('github-token') || process.env['GITHUB_TOKEN'] || '', + mode: parseModeInput(getInput('mode')), + findingsFile: getInput('findings-file') || undefined, + baseConfigPath: getInput('base-config-path') || undefined, + baseSkillRoot: getInput('base-skill-root') || undefined, + configPath: getInput('config-path') || 'warden.toml', + failOn, + reportOn, + maxFindings: Number.isNaN(maxFindingsParsed) ? 50 : maxFindingsParsed, + requestChanges, + failCheck, + postChecks, + parallel: Number.isNaN(parallelParsed) ? _utils_index_js__WEBPACK_IMPORTED_MODULE_2__/* .DEFAULT_CONCURRENCY */ .WH : parallelParsed, + actionRef: getInput('action-ref') || undefined, + serviceUrl: getInput('service-url') || undefined, + serviceToken: getInput('service-token') || process.env['WARDEN_SERVICE_TOKEN'] || undefined, + serviceData: serviceData.success ? serviceData.data : undefined, + serviceMemory: parseBooleanInput(getInput('service-memory')), + serviceTimeoutMs: serviceTimeoutParsed === undefined || Number.isNaN(serviceTimeoutParsed) + ? undefined + : serviceTimeoutParsed, + }; +} +/** + * Validate that required inputs are present. + * Throws with a descriptive error if validation fails. + */ +function validateInputs(inputs) { + if (!inputs.githubToken) { + throw new Error('GitHub token is required'); + } + if (inputs.baseSkillRoot && !inputs.baseConfigPath) { + throw new Error('base-skill-root requires base-config-path'); + } + if (inputs.mode === 'report' && !inputs.findingsFile) { + throw new Error('findings-file is required when mode is report'); + } + if (inputs.serviceMemory && inputs.serviceData === 'metrics') { + throw new Error('service-memory requires service-data findings or code'); + } +} +/** + * Set up environment variables for authentication. + * Sets appropriate env vars based on token type (API key vs OAuth). + */ +function setupAuthEnv(inputs) { + delete process.env['CLAUDE_CODE_OAUTH_TOKEN']; + delete process.env['WARDEN_ANTHROPIC_API_KEY']; + delete process.env['ANTHROPIC_API_KEY']; + if (inputs.oauthToken) { + process.env['CLAUDE_CODE_OAUTH_TOKEN'] = inputs.oauthToken; + return; + } + if (inputs.anthropicApiKey) { + process.env['WARDEN_ANTHROPIC_API_KEY'] = inputs.anthropicApiKey; + process.env['ANTHROPIC_API_KEY'] = inputs.anthropicApiKey; + } +} + + +/***/ }), + +/***/ 52552: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ a: () => (/* binding */ findBotReviewState) +/* harmony export */ }); +/** + * GitHub Review State Management + * + * Tracks the bot's previous review state on a PR for dismissal logic. + */ +const VALID_REVIEW_STATES = new Set(['CHANGES_REQUESTED', 'APPROVED', 'COMMENTED']); +function isValidReviewState(state) { + return VALID_REVIEW_STATES.has(state); +} +/** + * Find the bot's most recent review state on a PR. + * + * Used to determine if we should dismiss a previous REQUEST_CHANGES + * when all issues are now resolved. + * + * Returns null if: + * - Bot has no reviews on this PR + * - Bot's most recent review was DISMISSED (user explicitly cleared it) + */ +function findBotReviewState(reviews, botLogin) { + // GitHub API returns reviews in chronological order, search from end + for (let i = reviews.length - 1; i >= 0; i--) { + const review = reviews[i]; + if (!review?.user || review.user.login !== botLogin) { + continue; + } + // User dismissed our review - don't look at older reviews + if (review.state === 'DISMISSED') { + return null; + } + if (isValidReviewState(review.state)) { + return { state: review.state, reviewId: review.id }; + } + } + return null; +} + + +/***/ }), + +/***/ 48352: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ t: () => (/* binding */ shouldResolveStaleComments) +/* harmony export */ }); +/** + * Review Coordination + * + * Safety checks for stale comment resolution across multiple triggers. + */ +// ----------------------------------------------------------------------------- +// Functions +// ----------------------------------------------------------------------------- +/** + * Check if stale comment resolution should proceed. + * + * Returns false if any trigger failed, because failed triggers may have + * had findings that we can no longer verify are fixed. + */ +function shouldResolveStaleComments(results) { + return results.every((r) => !r.error); +} + + +/***/ }), + +/***/ 44602: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ v: () => (/* binding */ postTriggerReview) +/* harmony export */ }); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78481); +/* harmony import */ var _triggers_matcher_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49431); +/* harmony import */ var _output_renderer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(21242); +/* harmony import */ var _output_dedup_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3941); +/* harmony import */ var _sdk_usage_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(44759); +/* harmony import */ var _sdk_extract_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(29709); +/* harmony import */ var _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(80029); +/** + * Review Poster + * + * Handles posting GitHub PR reviews with deduplication. + * Extracted from main.ts to isolate the complex review posting state machine. + */ + + + + + + + +function emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations = []) { + return { posted: false, newComments, activeWardenCommentIds, findingObservations, shouldFail: false }; +} +function buildDedupeObservations(actions, skill, skillExecutionId) { + return actions.map((action) => ({ + outcome: 'deduped', + finding: action.finding, + skill, + skillExecutionId, + dedupe: { + source: action.existingComment.isWarden ? 'warden' : 'external', + matchType: action.matchType, + existingFindingId: action.existingComment.findingId, + ...(action.existingComment.id > 0 ? { existingCommentId: action.existingComment.id } : {}), + existingThreadId: action.existingComment.threadId, + existingResolved: action.existingComment.isResolved, + existingSkills: action.existingComment.skills, + actor: action.existingComment.actor, + }, + })); +} +function recenterReportFindingIds(reportFindings, actions) { + const idMap = new Map(actions + .filter((action) => action.originalFindingId !== action.finding.id) + .map((action) => [action.originalFindingId, action.finding.id])); + if (idMap.size === 0) { + return { findings: reportFindings, idMap }; + } + const findings = reportFindings.map((finding) => { + const recenteredId = idMap.get(finding.id); + return recenteredId ? { ...finding, id: recenteredId, reportedId: recenteredId } : finding; + }); + return { findings, idMap }; +} +function remapFindingId(finding, idMap) { + const recenteredId = idMap.get(finding.id); + return recenteredId ? { ...finding, id: recenteredId, reportedId: recenteredId } : finding; +} +/** + * Keep captured `FindingProcessingEvent`s in sync with a recenter so + * `provenance.ts`'s id-keyed lookup doesn't miss: those events were captured + * during skill execution, before cross-run dedupe could recenter a finding's + * id onto a pre-existing comment's id. + */ +function remapFindingProcessingEvents(events, idMap) { + return events.map((event) => ({ + ...event, + finding: remapFindingId(event.finding, idMap), + ...(event.replacement && { replacement: remapFindingId(event.replacement, idMap) }), + })); +} +/** + * Post a PR review to GitHub. + */ +async function postReviewToGitHub(octokit, context, result, feedbackGate) { + if (!context.pullRequest) { + return 'no_review'; + } + if (!result.review) { + return 'no_review'; + } + const { owner, name: repo } = context.repository; + const pullNumber = context.pullRequest.number; + const commitId = context.pullRequest.headSha; + const reviewComments = result.review.comments + .filter((c) => Boolean(c.path && c.line)) + .map((c) => ({ + path: c.path, + line: c.line, + side: c.side ?? 'RIGHT', + body: c.body, + start_line: c.start_line, + start_side: c.start_line ? c.start_side ?? 'RIGHT' : undefined, + })); + // Non-blocking body-only reviews cannot be resolved as review threads. + // Keep those findings in Checks instead of leaving stale PR timeline entries. + if (reviewComments.length === 0 && result.review.event === 'COMMENT') { + return 'checks_only'; + } + // Duplicate-action comment updates between the poster's gate check and this + // write can outlive the gate's cache window; verify once more. + const writability = await feedbackGate.check(); + if (writability === 'blocked') + return 'pull_request_changed'; + if (writability === 'unknown') + return 'review_not_posted'; + await octokit.pulls.createReview({ + owner, + repo, + pull_number: pullNumber, + commit_id: commitId, + event: result.review.event, + body: result.review.event === 'COMMENT' ? '' : result.review.body, + comments: reviewComments, + }); + return 'posted'; +} +/** + * Move inline comments into the review body as markdown. + * Used as a fallback when GitHub rejects inline comments (e.g. lines outside the diff). + */ +function moveCommentsToBody(renderResult, findings, skill) { + if (!renderResult.review) { + return renderResult; + } + const body = (0,_output_renderer_js__WEBPACK_IMPORTED_MODULE_2__/* .renderFindingsBody */ .D)(findings, skill); + return { + ...renderResult, + review: { + ...renderResult.review, + body, + comments: [], + }, + }; +} +/** + * Check if an error is a GitHub 422 "line could not be resolved" error. + */ +function isLineResolutionError(error) { + if (!(error instanceof Error)) + return false; + const msg = error.message.toLowerCase(); + return msg.includes('pull_request_review_thread.line') || + msg.includes('line must be part of the diff') || + msg.includes('line could not be resolved'); +} +// ----------------------------------------------------------------------------- +// Main Review Posting Logic +// ----------------------------------------------------------------------------- +/** + * Post a review for a single trigger result. + * + * Handles: + * - Filtering findings by reportOn threshold + * - Deduplicating against existing comments + * - Processing duplicate actions (reactions, updates) + * - Posting the final review + */ +async function postTriggerReview(ctx, deps) { + const { result, existingComments, apiKey } = ctx; + const { octokit, context } = deps; + const newComments = []; + const activeWardenCommentIds = new Set(); + const findingObservations = []; + if (!result.report) { + return emptyReviewPostResult(newComments, activeWardenCommentIds); + } + const skill = result.report.skill; + // Filter findings by reportOn threshold and confidence + const filteredFindings = (0,_types_index_js__WEBPACK_IMPORTED_MODULE_0__/* .filterFindings */ .Ni)(result.report.findings, result.reportOn, result.minConfidence); + const reportOnSuccess = result.reportOnSuccess ?? false; + // Skip if review rendering is disabled. In the normal action path this is + // only possible when reportOn is "off", which leaves no filtered findings. + if (!result.renderResult) { + if (filteredFindings.length > 0) { + console.warn(`::warning::Trigger ${result.triggerName} produced reportable findings without a render result`); + } + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + if (filteredFindings.length === 0 && !reportOnSuccess) { + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + let findingsToMarkFailed = filteredFindings; + try { + // Cross-location merging already happened in runSkillTask(). + // Consolidate findings within this batch (intra-batch dedup). + let findingsToPost = filteredFindings; + const canUseAuxiliaryRuntime = (0,_sdk_extract_js__WEBPACK_IMPORTED_MODULE_4__/* .canUseRuntimeAuth */ .ad)({ apiKey, runtime: ctx.runtime }); + if (findingsToPost.length > 1) { + const consolidateResult = await (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_3__/* .consolidateBatchFindings */ .aw)(findingsToPost, { + apiKey, + runtime: ctx.runtime, + model: ctx.model, + effort: ctx.effort, + hashOnly: !canUseAuxiliaryRuntime, + maxRetries: ctx.maxRetries, + agentName: skill, + }); + findingsToPost = consolidateResult.findings; + findingsToMarkFailed = findingsToPost; + for (const finding of consolidateResult.removedFindings ?? []) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason: 'duplicate_in_batch', + }); + } + if (consolidateResult.usage) { + const consolidateAux = { consolidate: consolidateResult.usage }; + result.report.auxiliaryUsage = (0,_sdk_usage_js__WEBPACK_IMPORTED_MODULE_5__/* .mergeAuxiliaryUsage */ .wV)(result.report.auxiliaryUsage, consolidateAux); + result.report.auxiliaryUsageAttribution = (0,_sdk_usage_js__WEBPACK_IMPORTED_MODULE_5__/* .mergeAuxiliaryUsageAttribution */ .vd)(result.report.auxiliaryUsageAttribution, { consolidate: { model: ctx.model, runtime: ctx.runtime } }); + } + if (consolidateResult.removedCount > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .logAction */ .d5)(`Consolidated ${consolidateResult.removedCount} duplicate findings within batch for ${result.triggerName}`); + } + } + // Deduplicate findings against existing comments + let dedupResult; + if (existingComments.length > 0 && findingsToPost.length > 0) { + dedupResult = await (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_3__/* .deduplicateFindings */ .v9)(findingsToPost, existingComments, { + apiKey, + runtime: ctx.runtime, + model: ctx.model, + effort: ctx.effort, + currentSkill: skill, + maxRetries: ctx.maxRetries, + }); + const recentered = recenterReportFindingIds(result.report.findings, dedupResult.duplicateActions); + result.report.findings = recentered.findings; + if (recentered.idMap.size > 0 && result.findingProcessingEvents) { + result.findingProcessingEvents = remapFindingProcessingEvents(result.findingProcessingEvents, recentered.idMap); + } + findingsToPost = dedupResult.newFindings; + findingsToMarkFailed = findingsToPost; + findingObservations.push(...buildDedupeObservations(dedupResult.duplicateActions, skill, result.skillExecutionId)); + // Merge dedup usage into the report's auxiliary usage + if (dedupResult.dedupUsage) { + const dedupAux = { dedup: dedupResult.dedupUsage }; + result.report.auxiliaryUsage = (0,_sdk_usage_js__WEBPACK_IMPORTED_MODULE_5__/* .mergeAuxiliaryUsage */ .wV)(result.report.auxiliaryUsage, dedupAux); + result.report.auxiliaryUsageAttribution = (0,_sdk_usage_js__WEBPACK_IMPORTED_MODULE_5__/* .mergeAuxiliaryUsageAttribution */ .vd)(result.report.auxiliaryUsageAttribution, { dedup: { model: ctx.model, runtime: ctx.runtime } }); + } + if (dedupResult.duplicateActions.length > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .logAction */ .d5)(`Found ${dedupResult.duplicateActions.length} duplicate findings for ${result.triggerName}`); + } + for (const action of dedupResult.duplicateActions) { + if (action.existingComment.isWarden && action.existingComment.id > 0) { + activeWardenCommentIds.add(action.existingComment.id); + } + } + } + // Consolidation and dedup above can spend minutes in LLM calls. Re-verify + // head freshness before the first GitHub write (duplicate-action comment + // updates below, then the review itself). + const writability = await deps.feedbackGate.check(); + if (writability !== 'writable') { + const skippedReason = writability === 'blocked' + ? 'pull_request_changed' + : 'review_not_posted'; + for (const finding of findingsToPost) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason, + }); + } + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + // Process duplicate actions (update Warden comments, add reactions) + if (dedupResult?.duplicateActions.length) { + const actionCounts = await (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_3__/* .processDuplicateActions */ .G$)(octokit, context.repository.owner, context.repository.name, dedupResult.duplicateActions, skill); + if (actionCounts.updated > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .logAction */ .d5)(`Updated ${actionCounts.updated} existing Warden comments with skill attribution`); + } + if (actionCounts.reacted > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .logAction */ .d5)(`Added reactions to ${actionCounts.reacted} existing external comments`); + } + if (actionCounts.failed > 0) { + const message = `Failed to process ${actionCounts.failed} duplicate actions`; + if (ctx.failOnPostError) { + throw new Error(message); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .warnAction */ .T6)(message); + } + } + // Check if failOn threshold is met (even if all findings deduplicated, we still need REQUEST_CHANGES) + // Filter by confidence first so low-confidence findings don't trigger REQUEST_CHANGES + const useRequestChanges = result.requestChanges ?? false; + const reportForFail = { ...result.report, findings: (0,_types_index_js__WEBPACK_IMPORTED_MODULE_0__/* .filterFindings */ .Ni)(result.report.findings, undefined, result.minConfidence) }; + const needsRequestChanges = useRequestChanges && result.failOn && (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_1__/* .shouldFail */ .W9)(reportForFail, result.failOn); + // Only post if we have non-duplicate findings, reportOnSuccess, or REQUEST_CHANGES needed + if (findingsToPost.length > 0 || reportOnSuccess || needsRequestChanges) { + // Re-render with deduplicated findings if any were removed + const renderResultToPost = findingsToPost.length !== filteredFindings.length + ? (0,_output_renderer_js__WEBPACK_IMPORTED_MODULE_2__/* .renderSkillReport */ .K)({ ...result.report, findings: findingsToPost }, { + maxFindings: result.maxFindings, + reportOn: result.reportOn, + minConfidence: result.minConfidence, + failOn: result.failOn, + requestChanges: result.requestChanges, + checkRunUrl: result.checkRunUrl, + totalFindings: result.report.findings.length, + // Pass original findings for failOn evaluation (not affected by dedup) + allFindings: result.report.findings, + }) + : result.renderResult; + // Apply maxFindings limit consistently for both the fallback body and dedup tracking + const postedFindings = result.maxFindings + ? findingsToPost.slice(0, result.maxFindings) + : findingsToPost; + const skippedFindings = result.maxFindings + ? findingsToPost.slice(result.maxFindings) + : []; + // Only overflow-eligible findings should be marked failed if posting throws + findingsToMarkFailed = postedFindings; + for (const finding of skippedFindings) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason: 'max_findings', + }); + } + let postOutcome = 'no_review'; + try { + postOutcome = await postReviewToGitHub(octokit, context, renderResultToPost, deps.feedbackGate); + } + catch (error) { + if (!isLineResolutionError(error)) { + throw error; + } + if (renderResultToPost.review?.event === 'REQUEST_CHANGES') { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .warnAction */ .T6)(`Inline comments failed for ${result.triggerName}, posting findings in review body`); + const fallback = moveCommentsToBody(renderResultToPost, postedFindings, skill); + postOutcome = await postReviewToGitHub(octokit, context, fallback, deps.feedbackGate); + } + else { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .warnAction */ .T6)(`Inline comments failed for ${result.triggerName}, falling back to checks only`); + postOutcome = 'checks_only'; + } + } + if (postOutcome === 'checks_only') { + for (const finding of postedFindings) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason: 'no_inline_location', + }); + } + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + if (postOutcome !== 'posted') { + if (postOutcome === 'pull_request_changed' || postOutcome === 'review_not_posted') { + for (const finding of postedFindings) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason: postOutcome, + }); + } + } + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + result.reviewEventPosted = renderResultToPost.review?.event; + // COMMENT reviews post with an empty body, so locationless findings that + // the renderer placed in the body never reach the PR. Record them as + // checks-only instead of claiming they were posted. + const bodyStripped = renderResultToPost.review?.event === 'COMMENT'; + for (const finding of postedFindings) { + if (bodyStripped && !finding.location) { + findingObservations.push({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason: 'no_inline_location', + }); + continue; + } + findingObservations.push({ outcome: 'posted', finding, skill, skillExecutionId: result.skillExecutionId }); + const comment = (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_3__/* .findingToExistingComment */ .Xi)(finding, skill); + if (comment) { + newComments.push(comment); + } + } + return { + posted: true, + newComments, + activeWardenCommentIds, + findingObservations, + shouldFail: false, + }; + } + return emptyReviewPostResult(newComments, activeWardenCommentIds, findingObservations); + } + catch (error) { + if (ctx.failOnPostError) { + throw error; + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_6__/* .warnAction */ .T6)(`Failed to post review for ${result.triggerName}: ${error}`); + return { + posted: false, + newComments, + activeWardenCommentIds, + findingObservations: [ + ...findingObservations, + ...findingsToMarkFailed.map((finding) => ({ outcome: 'failed', finding, skill, skillExecutionId: result.skillExecutionId })), + ], + shouldFail: false, + }; + } +} + + +/***/ }), + +/***/ 6643: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ d: () => (/* binding */ ReviewFeedbackGate) +/* harmony export */ }); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30340); +/* harmony import */ var _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(80029); +/* harmony import */ var _sdk_retry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2022); +/** + * Review Feedback Gate + * + * Single owner of the "is this run still analyzing the current PR head?" + * check that guards every PR review feedback mutation (posting reviews, + * resolving threads, replying, dismissing reviews). + */ + + + +const FRESHNESS_TTL_MS = 10_000; +const HEAD_FETCH_ATTEMPTS = 3; +const HEAD_FETCH_RETRY_DELAY_MS = 500; +/** + * Guards PR review feedback writes behind a head-freshness check. + * + * States returned by {@link ReviewFeedbackGate.check}: + * - `writable`: the PR head matched this run's head within the TTL window. + * - `blocked`: no PR context, or the head advanced past this run. Permanent + * for the run; a head that advanced never becomes current again. + * - `unknown`: the head could not be verified after retries. Writes must be + * skipped (fail closed), but the state is cached only briefly so later + * phases retry instead of disabling feedback for the whole run. Callers + * that suppress a blocking review because of `unknown` must fail the run + * instead of letting it pass silently. + * + * Results are memoized for a short TTL so bursts of writes share one + * `pulls.get` call while long LLM phases still trigger a fresh check. + */ +class ReviewFeedbackGate { + octokit; + context; + options; + blocked = false; + cached; + constructor(octokit, context, options = {}) { + this.octokit = octokit; + this.context = context; + this.options = options; + } + /** Report whether this run may still mutate PR review feedback. */ + async check() { + const pullRequest = this.context.pullRequest; + if (!pullRequest || this.blocked) { + return 'blocked'; + } + const ttlMs = this.options.ttlMs ?? FRESHNESS_TTL_MS; + if (this.cached && Date.now() - this.cached.at < ttlMs) { + return this.cached.status; + } + const attempts = this.options.attempts ?? HEAD_FETCH_ATTEMPTS; + const retryDelayMs = this.options.retryDelayMs ?? HEAD_FETCH_RETRY_DELAY_MS; + let lastError; + for (let attempt = 1; attempt <= attempts; attempt++) { + try { + const { data } = await this.octokit.pulls.get({ + owner: this.context.repository.owner, + repo: this.context.repository.name, + pull_number: pullRequest.number, + }); + if (data.head.sha !== pullRequest.headSha) { + this.blocked = true; + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_2__/* .warnAction */ .T6)(`Skipping PR review feedback because run head ${pullRequest.headSha} is no longer the PR head ${data.head.sha}`); + return 'blocked'; + } + this.cached = { status: 'writable', at: Date.now() }; + return 'writable'; + } + catch (error) { + lastError = error; + if (attempt < attempts) { + await (0,_sdk_retry_js__WEBPACK_IMPORTED_MODULE_1__/* .sleep */ .yy)(retryDelayMs * attempt); + } + } + } + _sentry_js__WEBPACK_IMPORTED_MODULE_0__/* .Sentry.captureException */ .sQ.captureException(lastError, { tags: { operation: 'fetch_current_pr_head' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_2__/* .warnAction */ .T6)(`Could not verify the current PR head after ${attempts} attempts; skipping review feedback writes: ${lastError}`); + this.cached = { status: 'unknown', at: Date.now() }; + return 'unknown'; + } + /** True when review feedback writes are allowed right now. */ + async canWrite() { + return (await this.check()) === 'writable'; + } +} + + +/***/ }), + +/***/ 61211: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30340); +/* harmony import */ var _workflow_base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(98514); +/* harmony import */ var _runner_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47626); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_runner_js__WEBPACK_IMPORTED_MODULE_2__]); +_runner_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; +/** + * GitHub Action Runner + * + * main.ts installs action-bundle compatibility hooks before loading this + * module. Workflow modules own trigger-level error handling. + */ + + + +async function flushActionTelemetry() { + if (!(await (0,_sentry_js__WEBPACK_IMPORTED_MODULE_0__/* .flushSentry */ .KR)())) { + console.warn('::warning::Timed out while flushing Sentry telemetry'); + } +} +(0,_sentry_js__WEBPACK_IMPORTED_MODULE_0__/* .initSentry */ .ig)('action'); +(0,_runner_js__WEBPACK_IMPORTED_MODULE_2__/* .runAction */ .C)() + .then(() => flushActionTelemetry()) + .catch(async (error) => { + if (error instanceof _workflow_base_js__WEBPACK_IMPORTED_MODULE_1__/* .ActionFailedError */ .Ah) { + console.error(`::error::${error.message}`); + } + else { + console.error(`::error::Unexpected error: ${error}`); + } + await flushActionTelemetry(); + process.exit(1); +}); + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 47626: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ C: () => (/* binding */ runAction) +/* harmony export */ }); +/* harmony import */ var _octokit_rest__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(5798); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(70155); +/* harmony import */ var _sdk_errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(98229); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30340); +/* harmony import */ var _inputs_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(93857); +/* harmony import */ var _workflow_base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98514); +/* harmony import */ var _workflow_pr_workflow_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(39422); +/* harmony import */ var _workflow_schedule_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(30517); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_workflow_pr_workflow_js__WEBPACK_IMPORTED_MODULE_4__, _workflow_schedule_js__WEBPACK_IMPORTED_MODULE_5__]); +([_workflow_pr_workflow_js__WEBPACK_IMPORTED_MODULE_4__, _workflow_schedule_js__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__); +/** + * GitHub Action dispatcher. + * + * Parses action inputs, builds the GitHub client, and selects the workflow for + * the current GitHub event. The top-level run module owns process exit handling. + */ + + + + + + + + +function isPullRequestEvent(eventName) { + return eventName === 'pull_request'; +} +/** Run the GitHub Action dispatcher once. */ +async function runAction() { + const eventName = process.env['GITHUB_EVENT_NAME']; + const actionAttributes = (0,_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .setGitHubActionScope */ .gs)(eventName); + return _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'cicd.workflow', name: 'run Warden action', attributes: actionAttributes }, async (span) => { + // Advance this before each phase so failures retain their startup stage. + let stage = 'input'; + try { + const inputs = (0,_inputs_js__WEBPACK_IMPORTED_MODULE_2__/* .parseActionInputs */ .HC)(); + (0,_inputs_js__WEBPACK_IMPORTED_MODULE_2__/* .validateInputs */ .C1)(inputs); + stage = 'environment'; + const eventPath = process.env['GITHUB_EVENT_PATH']; + const repoPath = process.env['GITHUB_WORKSPACE']; + if (!eventName || !eventPath || !repoPath) { + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_3__/* .setFailed */ .C1)('This action must be run in a GitHub Actions environment'); + } + (0,_inputs_js__WEBPACK_IMPORTED_MODULE_2__/* .setupAuthEnv */ .Tw)(inputs); + const octokit = new _octokit_rest__WEBPACK_IMPORTED_MODULE_6__/* .Octokit */ .E({ auth: inputs.githubToken }); + stage = 'dispatch'; + if (eventName === 'schedule' || eventName === 'workflow_dispatch') { + if (inputs.mode !== 'run') { + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_3__/* .setFailed */ .C1)(`${inputs.mode} mode is only supported for pull request workflows`); + } + await (0,_workflow_schedule_js__WEBPACK_IMPORTED_MODULE_5__/* .runScheduleWorkflow */ .y)(octokit, inputs, repoPath); + } + else { + if (inputs.mode !== 'run' && !isPullRequestEvent(eventName)) { + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_3__/* .setFailed */ .C1)(`${inputs.mode} mode is only supported for pull request workflows`); + } + await (0,_workflow_pr_workflow_js__WEBPACK_IMPORTED_MODULE_4__/* .runPRWorkflow */ .r)(octokit, inputs, eventName, eventPath, repoPath); + } + span.setAttribute('warden.action.outcome', 'success'); + span.setStatus({ code: _sentry_core__WEBPACK_IMPORTED_MODULE_7__/* .SPAN_STATUS_OK */ .F3 }); + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .emitActionRunMetric */ .B4)('success', stage); + } + catch (error) { + const { code } = (0,_sdk_errors_js__WEBPACK_IMPORTED_MODULE_0__/* .classifyError */ .fe)(error); + span.setAttribute('warden.action.outcome', 'failure'); + span.setAttribute('warden.action.stage', stage); + span.setAttribute('warden.error.code', code); + span.setStatus({ code: _sentry_core__WEBPACK_IMPORTED_MODULE_7__/* .SPAN_STATUS_ERROR */ .TJ, message: code }); + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .emitActionRunMetric */ .B4)('failure', stage, code); + // Expected action failures are outcomes, not Sentry Issues. + if (!(error instanceof _workflow_base_js__WEBPACK_IMPORTED_MODULE_3__/* .ActionFailedError */ .Ah)) { + _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.captureException */ .sQ.captureException(error, { + tags: { + 'warden.error.code': code, + 'warden.action.stage': stage, + }, + }); + } + throw error; + } + }); +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 19197: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ P$: () => (/* binding */ publishActionEarlyFailureFailOpen), +/* harmony export */ iZ: () => (/* binding */ resolveActionServiceOptions), +/* harmony export */ pp: () => (/* binding */ publishActionRunFailOpen), +/* harmony export */ t4: () => (/* binding */ recallActionMemoryFailOpen) +/* harmony export */ }); +/* unused harmony export publishActionFindingsFailOpen */ +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77598); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_crypto__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80029); +/* harmony import */ var _service_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33941); + + + + +/** Recall repository memory once after Action paths and selected skills are known. */ +async function recallActionMemoryFailOpen(service, context, skills) { + if (!service?.memory) + return { memories: [] }; + const paths = context.pullRequest?.files.map((file) => file.filename) ?? []; + const response = await (0,_service_index_js__WEBPACK_IMPORTED_MODULE_2__/* .recallMemoryFailOpen */ .zq)(service, { + protocolVersion: 1, + clientRecallId: (0,node_crypto__WEBPACK_IMPORTED_MODULE_0__.randomUUID)(), + repository: { + provider: 'github', + owner: context.repository.owner, + name: context.repository.name, + fullName: context.repository.fullName, + }, + skills: [...new Set(skills)], + languages: [...new Set(paths.map((path) => (0,node_path__WEBPACK_IMPORTED_MODULE_1__.extname)(path).slice(1)).filter(Boolean))], + paths, + }); + const memories = response?.memories ?? []; + return { + memories, + historicalEvidence: (0,_service_index_js__WEBPACK_IMPORTED_MODULE_2__/* .renderHistoricalMemory */ .iH)(memories), + ...(response ? { clientRecallId: response.clientRecallId } : {}), + }; +} +/** Resolve Action options without trusting repository configuration to choose the authenticated endpoint. */ +function resolveActionServiceOptions(inputs, config) { + return (0,_service_index_js__WEBPACK_IMPORTED_MODULE_2__/* .resolveServiceOptions */ .I5)({ + explicit: { + url: inputs.serviceUrl, + token: inputs.serviceToken, + data: inputs.serviceData, + memory: inputs.serviceMemory, + timeoutMs: inputs.serviceTimeoutMs, + }, + config: config ? { + data: config.data, + memory: config.memory, + timeoutMs: config.timeoutMs, + } : undefined, + onWarning: _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_3__/* .warnAction */ .T6, + }); +} +/** Publish the final in-memory Action result after GitHub and artifact writes have completed. */ +async function publishActionFindingsFailOpen(service, output) { + if (!service) + return; + try { + const envelope = (0,_service_index_js__WEBPACK_IMPORTED_MODULE_2__/* .buildFindingsServiceRunEnvelope */ .PX)(output, service, 'action'); + const published = await (0,_service_index_js__WEBPACK_IMPORTED_MODULE_2__/* .publishRunFailOpen */ .j7)(service, envelope); + if (!published) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_3__/* .warnAction */ .T6)(`Warden service could not publish run ${output.runId}. Action results are unchanged.`); + } + } + catch { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_3__/* .warnAction */ .T6)(`Warden service could not publish run ${output.runId}. Action results are unchanged.`); + } +} +/** Build and publish an Action result while isolating projection failures from workflow behavior. */ +async function publishActionRunFailOpen(service, buildOutput) { + if (!service) + return; + try { + await publishActionFindingsFailOpen(service, buildOutput()); + } + catch { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_3__/* .warnAction */ .T6)('Warden service could not build the Action run envelope. Action results are unchanged.'); + } +} +/** Publish an early Action failure using the metrics-only profile. */ +async function publishActionEarlyFailureFailOpen(service, buildOutput) { + if (!service) + return; + await publishActionRunFailOpen({ + ...service, + data: 'metrics', + memory: false, + }, buildOutput); +} + + +/***/ }), + +/***/ 19533: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ k: () => (/* binding */ executeTrigger) +/* harmony export */ }); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30340); +/* harmony import */ var _workflow_base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(98514); +/* harmony import */ var _skills_loader_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34691); +/* harmony import */ var _triggers_matcher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(49431); +/* harmony import */ var _cli_output_tasks_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5836); +/* harmony import */ var _output_renderer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21242); +/* harmony import */ var _sdk_errors_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(98229); +/* harmony import */ var _cli_output_verbosity_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(21307); +/* harmony import */ var _sdk_runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(85286); +/* harmony import */ var _sdk_offline_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(8695); +/* harmony import */ var _error_reporting_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(29547); +/* harmony import */ var _incremental_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(13778); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_cli_output_tasks_js__WEBPACK_IMPORTED_MODULE_4__]); +_cli_output_tasks_js__WEBPACK_IMPORTED_MODULE_4__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; +/** + * Trigger Executor + * + * Executes a single trigger. GitHub check writes are optional and must be + * injected by legacy run mode; split analyze mode omits that capability. + * Extracted from main.ts to enable isolated testing and clearer dependencies. + */ + + + + + + + + + + + + + +/** Log-mode output for CI: no TTY, no color. */ +const CI_OUTPUT_MODE = { isTTY: false, supportsColor: false, columns: 120 }; +function toAnalysisChunkingConfig(chunking) { + if (!chunking) { + return undefined; + } + const analysisChunking = {}; + if (chunking.filePatterns) { + analysisChunking.filePatterns = chunking.filePatterns; + } + if (chunking.coalesce) { + analysisChunking.coalesce = chunking.coalesce; + } + return analysisChunking.filePatterns || analysisChunking.coalesce + ? analysisChunking + : undefined; +} +// ----------------------------------------------------------------------------- +// Executor +// ----------------------------------------------------------------------------- +/** + * Execute a single trigger and return results. + * + * Handles: + * - Running the skill via Claude Code SDK + * - Rendering results for GitHub review + * - Creating/updating GitHub check runs only when a check reporter is provided + */ +async function executeTrigger(trigger, deps) { + return _sentry_js__WEBPACK_IMPORTED_MODULE_0__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'trigger.execute', name: `execute ${trigger.name}` }, async (span) => { + span.setAttribute('gen_ai.agent.name', trigger.skill); + span.setAttribute('warden.trigger.name', trigger.name); + const { context, anthropicApiKey, claudePath } = deps; + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_1__/* .logGroup */ .QT)(`Running trigger: ${trigger.name} (skill: ${trigger.skill})`); + // Create skill check (only for PRs) + let skillCheck; + let skillCheckUrl; + let skillCheckRunId; + if (deps.checks && context.pullRequest) { + try { + skillCheck = await deps.checks.start(trigger.skill); + skillCheckUrl = skillCheck.url; + skillCheckRunId = skillCheck.checkRunId; + } + catch (error) { + console.error(`::warning::Failed to create skill check for ${trigger.skill}: ${error}`); + } + } + const failOn = trigger.failOn ?? deps.globalFailOn; + const reportOn = trigger.reportOn ?? deps.globalReportOn; + const minConfidence = trigger.minConfidence ?? 'medium'; + const requestChanges = trigger.requestChanges ?? deps.globalRequestChanges; + const failCheck = trigger.failCheck ?? deps.globalFailCheck; + const maxFindings = trigger.maxFindings ?? deps.globalMaxFindings; + const skillRoot = trigger.useBuiltinSkill ? undefined : (trigger.skillRoot ?? context.repoPath); + const resolveSkill = () => (0,_skills_loader_js__WEBPACK_IMPORTED_MODULE_2__/* .resolveSkillAsync */ .Cy)(trigger.skill, skillRoot, { + remote: trigger.remote, + offline: (0,_sdk_offline_js__WEBPACK_IMPORTED_MODULE_11__/* .isWardenOffline */ .XK)(), + }); + const triggerContext = (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_3__/* .filterContextByPaths */ .Lb)(context, trigger.filters); + try { + (0,_sdk_runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_8__/* .assertValidPiModelSelectors */ .lG)([trigger]); + const incremental = deps.incremental && trigger.incremental + ? await prepareIncrementalReview(deps.incremental, trigger, triggerContext, resolveSkill, { + failOn, + reportOn, + minConfidence, + failCheck, + requestChanges, + maxFindings, + }) + : undefined; + const taskOptions = { + name: trigger.name, + displayName: trigger.skill, + triggerName: trigger.name, + failOn, + resolveSkill: incremental ? () => Promise.resolve(incremental.skill) : resolveSkill, + context: triggerContext, + runnerOptions: { + apiKey: anthropicApiKey, + model: trigger.model, + runtime: trigger.runtime, + effort: trigger.effort, + auxiliaryModel: trigger.auxiliaryModel, + auxiliaryEffort: trigger.auxiliaryEffort, + synthesisModel: trigger.synthesisModel, + maxTurns: trigger.maxTurns, + batchDelayMs: trigger.batchDelayMs, + maxContextFiles: trigger.maxContextFiles, + ignore: trigger.ignore, + scan: trigger.scan, + chunking: toAnalysisChunkingConfig(trigger.chunking), + pathToClaudeCodeExecutable: claudePath, + auxiliaryMaxRetries: trigger.auxiliaryMaxRetries, + verifyFindings: trigger.verifyFindings, + abortController: deps.abortController, + circuitBreaker: deps.circuitBreaker, + historicalEvidence: deps.historicalEvidence, + skipHunks: incremental?.skipHunks, + }, + }; + const defaultCallbacks = (0,_cli_output_tasks_js__WEBPACK_IMPORTED_MODULE_4__/* .createDefaultCallbacks */ .O7)([taskOptions], CI_OUTPUT_MODE, _cli_output_verbosity_js__WEBPACK_IMPORTED_MODULE_7__/* .Verbosity */ .W.Normal); + const findingProcessingEvents = []; + const callbacks = { + ...defaultCallbacks, + onFindingProcessing: (skillName, event) => { + findingProcessingEvents.push(event); + defaultCallbacks.onFindingProcessing?.(skillName, event); + }, + }; + const result = await (0,_cli_output_tasks_js__WEBPACK_IMPORTED_MODULE_4__/* .runSkillTask */ .UG)(taskOptions, callbacks, deps.analysisQueue); + const report = result.report; + if (!report) { + throw result.error ?? new Error('Skill task returned no report'); + } + // runSkillTask now synthesizes a report even on failure so the CLI + // can log it as JSONL. The action's fail-check path still expects a + // thrown error, so re-throw when the report carries one. Preserve + // the ErrorCode in the fallback so Sentry / failSkillCheck see a + // typed error. + if (report.error) { + throw (result.error ?? + new _sdk_errors_js__WEBPACK_IMPORTED_MODULE_6__/* .SkillRunnerError */ .cy(report.error.message, { + code: report.error.code, + hunkFailures: report.hunkFailures, + })); + } + if (incremental) { + // A shared abort (circuit breaker or sibling failure) drops queued hunks + // without recording them as failed, so an aborted run is never a baseline. + const aborted = deps.abortController?.signal.aborted ?? false; + report.incremental = { ...incremental.review, complete: !aborted && (0,_incremental_js__WEBPACK_IMPORTED_MODULE_10__/* .reviewedEverything */ .lO)(report) }; + } + console.log(`Found ${report.findings.length} findings`); + // Update skill check with results + if (skillCheck && context.pullRequest) { + try { + await skillCheck.complete(report, { + failOn, + reportOn, + minConfidence, + failCheck, + }); + } + catch (error) { + console.error(`::warning::Failed to update skill check for ${trigger.skill}: ${error}`); + } + } + const renderResult = reportOn !== 'off' + ? (0,_output_renderer_js__WEBPACK_IMPORTED_MODULE_5__/* .renderSkillReport */ .K)(report, { + maxFindings, + reportOn, + minConfidence, + failOn, + requestChanges, + checkRunUrl: skillCheckUrl, + totalFindings: report.findings.length, + }) + : undefined; + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_1__/* .logGroupEnd */ .TN)(); + return { + triggerId: trigger.id, + skillExecutionId: trigger.skillExecutionId, + triggerName: trigger.name, + skillName: trigger.skill, + report, + renderResult, + failOn, + reportOn, + minConfidence, + reportOnSuccess: trigger.reportOnSuccess, + requestChanges, + failCheck, + checkRunUrl: skillCheckUrl, + checkRunId: skillCheckRunId, + maxFindings, + auxiliaryModel: trigger.auxiliaryModel, + synthesisModel: trigger.synthesisModel, + findingProcessingEvents, + }; + } + catch (error) { + if (error instanceof _workflow_base_js__WEBPACK_IMPORTED_MODULE_1__/* .ActionFailedError */ .Ah) + throw error; + (0,_error_reporting_js__WEBPACK_IMPORTED_MODULE_9__/* .captureActionTriggerError */ .T)(error, { + triggerName: trigger.name, + skillName: trigger.skill, + }); + // Mark skill check as failed + if (skillCheck && context.pullRequest) { + try { + await skillCheck.fail(error); + } + catch (checkError) { + console.error(`::warning::Failed to mark skill check as failed: ${checkError}`); + } + } + console.error(`::warning::Trigger ${trigger.name} failed: ${error}`); + (0,_workflow_base_js__WEBPACK_IMPORTED_MODULE_1__/* .logGroupEnd */ .TN)(); + return { + triggerId: trigger.id, + skillExecutionId: trigger.skillExecutionId, + triggerName: trigger.name, + skillName: trigger.skill, + error, + }; + } + }); +} +/** + * Resolve the skill early to fingerprint it, then match the PR diff against + * the newest baseline. Returns undefined when the skill cannot be resolved so + * the normal path reports the resolution error. + */ +async function prepareIncrementalReview(source, trigger, context, resolveSkill, policy) { + if (!context.pullRequest) + return undefined; + if (!trigger.incrementalApp) { + console.error(`::warning::Incremental review for ${trigger.name} needs defaults.incrementalApp to know which checks to trust, reviewing the full PR`); + return undefined; + } + let skill; + try { + skill = await resolveSkill(); + } + catch { + return undefined; + } + const externalId = (0,_incremental_js__WEBPACK_IMPORTED_MODULE_10__/* .incrementalExternalId */ .Bc)(trigger, skill, policy, context.pullRequest.baseBranch); + const baseline = await source.baselineFor(externalId, trigger.incrementalApp); + if (!baseline) { + console.log('Incremental review: no earlier baseline for this skill config, reviewing the full PR'); + return { skill, skipHunks: new Map(), review: { externalId, carriedRanges: [] } }; + } + const plan = (0,_incremental_js__WEBPACK_IMPORTED_MODULE_10__/* .planIncrementalReview */ .Cv)(context.pullRequest.files, baseline.reviewed); + console.log(`Incremental review: ${plan.carriedRanges.length} hunk(s) unchanged since ${baseline.sha.slice(0, 7)}`); + return { + skill, + skipHunks: plan.skipHunks, + review: { externalId, baselineSha: baseline.sha, carriedRanges: plan.carriedRanges }, + }; +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 98514: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Ah: () => (/* binding */ ActionFailedError), + GF: () => (/* binding */ FINDINGS_OUTPUT_DONE_FILENAME), + X0: () => (/* binding */ FINDINGS_OUTPUT_FILENAME), + mG: () => (/* binding */ clearStaleFindingsOutput), + sl: () => (/* binding */ collectTriggerErrors), + dV: () => (/* binding */ computeWorkflowOutputs), + $m: () => (/* binding */ ensureClaudeAuth), + Uf: () => (/* binding */ getAuthenticatedBotLogin), + YL: () => (/* binding */ getDefaultBranchFromAPI), + Rr: () => (/* binding */ getFindingsOutputPath), + a3: () => (/* binding */ handleTriggerErrors), + QT: () => (/* binding */ logGroup), + TN: () => (/* binding */ logGroupEnd), + bZ: () => (/* binding */ prepareRuntimeEnvironment), + C1: () => (/* binding */ setFailed), + uH: () => (/* binding */ setOutput), + wZ: () => (/* binding */ setWorkflowOutputs), + JR: () => (/* binding */ writeFindingsOutput), + ZU: () => (/* binding */ writeFindingsOutputLive) +}); + +// UNUSED EXPORTS: clearStaleDoneMarker, findClaudeCodeExecutable + +// EXTERNAL MODULE: external "node:fs" +var external_node_fs_ = __webpack_require__(73024); +// EXTERNAL MODULE: external "node:os" +var external_node_os_ = __webpack_require__(48161); +// EXTERNAL MODULE: external "node:path" +var external_node_path_ = __webpack_require__(76760); +// EXTERNAL MODULE: external "node:crypto" +var external_node_crypto_ = __webpack_require__(77598); +// EXTERNAL MODULE: ./src/utils/exec.ts +var exec = __webpack_require__(82224); +// EXTERNAL MODULE: ./src/utils/path.ts +var path = __webpack_require__(60702); +;// CONCATENATED MODULE: ./src/utils/fs.ts + + +/** + * Write a file atomically: content lands at `path` all-or-nothing, so + * concurrent or interrupted readers never observe a partially written file. + * Writes to a uniquely named temp file in the same directory, then renames + * it into place (rename is atomic on the same filesystem). + */ +function writeFileAtomic(path, content) { + (0,external_node_fs_.mkdirSync)((0,external_node_path_.dirname)(path), { recursive: true }); + const tmpPath = (0,external_node_path_.join)((0,external_node_path_.dirname)(path), `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`); + try { + (0,external_node_fs_.writeFileSync)(tmpPath, content); + (0,external_node_fs_.renameSync)(tmpPath, path); + } + catch (error) { + try { + (0,external_node_fs_.unlinkSync)(tmpPath); + } + catch { + // Temp file may not have been created yet; nothing to clean up. + } + throw error; + } +} + +// EXTERNAL MODULE: ./src/reporting/output.ts + 2 modules +var reporting_output = __webpack_require__(4169); +// EXTERNAL MODULE: ./src/triggers/matcher.ts +var matcher = __webpack_require__(49431); +;// CONCATENATED MODULE: ./src/action/workflow/base.ts +/** + * Workflow Base + * + * Shared infrastructure for PR and schedule workflows. + */ + + + + + + + + + +/** + * Sentinel error thrown by setFailed() so the top-level catch handler + * can distinguish expected failures from unexpected crashes. + */ +class ActionFailedError extends Error { + constructor(message) { + super(message); + this.name = 'ActionFailedError'; + } +} +// ----------------------------------------------------------------------------- +// GitHub Actions Helpers +// ----------------------------------------------------------------------------- +/** + * Set a GitHub Actions output variable. + */ +function setOutput(name, value) { + const outputFile = process.env['GITHUB_OUTPUT']; + if (outputFile) { + const stringValue = String(value); + // Use heredoc format with random delimiter for multiline values + // Random delimiter prevents injection if value contains the delimiter + if (stringValue.includes('\n')) { + const delimiter = `ghadelim_${(0,external_node_crypto_.randomUUID)()}`; + (0,external_node_fs_.appendFileSync)(outputFile, `${name}<<${delimiter}\n${stringValue}\n${delimiter}\n`); + } + else { + (0,external_node_fs_.appendFileSync)(outputFile, `${name}=${stringValue}\n`); + } + } +} +/** + * Fail the GitHub Action with an error message. + * Throws ActionFailedError so spans end cleanly before the process exits. + */ +function setFailed(message) { + throw new ActionFailedError(message); +} +/** Validate Claude runtime auth before invoking the Claude Code SDK. */ +function ensureClaudeAuth(inputs) { + if (inputs.anthropicApiKey || inputs.oauthToken) { + return; + } + setFailed('Authentication not found. Provide an API key via anthropic-api-key input, ' + + 'WARDEN_ANTHROPIC_API_KEY env var, or OAuth token via CLAUDE_CODE_OAUTH_TOKEN env var.'); +} +/** + * Start a collapsible log group. + */ +function logGroup(name) { + console.log(`::group::${name}`); +} +/** + * End a collapsible log group. + */ +function logGroupEnd() { + console.log('::endgroup::'); +} +/** Prepare runtime-specific process dependencies required by matched triggers. */ +async function prepareRuntimeEnvironment(triggers, inputs) { + const runtimes = new Set(); + for (const trigger of triggers) { + runtimes.add(trigger.runtime ?? 'pi'); + } + const env = {}; + for (const runtime of runtimes) { + switch (runtime) { + case 'pi': + break; + case 'claude': + ensureClaudeAuth(inputs); + env.pathToClaudeCodeExecutable = await findClaudeCodeExecutable(); + break; + } + } + return env; +} +// ----------------------------------------------------------------------------- +// Claude Code CLI +// ----------------------------------------------------------------------------- +const CLAUDE_CODE_VERSION = '2.1.32'; +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +/** + * Test whether a path is an executable file. + */ +function isExecutable(path) { + try { + (0,exec/* execFileNonInteractive */.FR)('test', ['-x', path]); + return true; + } + catch { + return false; + } +} +function findInstalledClaudeCodeExecutable() { + const envPath = process.env['CLAUDE_CODE_PATH']; + if (envPath && isExecutable(envPath)) { + return envPath; + } + // Standard install location from claude.ai/install.sh + const home = process.env['HOME']; + const homeLocalBin = home ? `${home}/.local/bin/claude` : undefined; + if (homeLocalBin && isExecutable(homeLocalBin)) { + return homeLocalBin; + } + // Try which command + try { + const path = (0,exec/* execFileNonInteractive */.FR)('which', ['claude']); + if (path) + return path; + } + catch { + // which command failed + } + // Other common installation paths as fallback + const commonPaths = ['/usr/local/bin/claude', '/usr/bin/claude']; + for (const p of commonPaths) { + if (isExecutable(p)) + return p; + } + return undefined; +} +async function installClaudeCodeExecutable() { + console.log(`Installing Claude Code v${CLAUDE_CODE_VERSION}...`); + for (let attempt = 1; attempt <= 3; attempt++) { + console.log(`Installation attempt ${attempt}...`); + try { + const output = (0,exec/* execNonInteractive */.zt)(`curl -fsSL https://claude.ai/install.sh | bash -s -- "${CLAUDE_CODE_VERSION}"`, { timeout: 120_000 }); + if (output) { + console.log(output); + } + console.log('Claude Code installed successfully'); + return; + } + catch (error) { + if (attempt === 3) { + setFailed(`Failed to install Claude Code after 3 attempts: ${error}`); + } + console.log('Installation failed, retrying...'); + await sleep(5000); + } + } +} +/** + * Find the Claude Code CLI executable path, installing it on demand when the + * selected runtime needs Claude Code in CI. + */ +async function findClaudeCodeExecutable() { + const existingPath = findInstalledClaudeCodeExecutable(); + if (existingPath) { + return existingPath; + } + await installClaudeCodeExecutable(); + const installedPath = findInstalledClaudeCodeExecutable(); + if (installedPath) { + return installedPath; + } + setFailed('Claude Code CLI not found after installation. Ensure Claude Code is installed via https://claude.ai/install.sh'); +} +// ----------------------------------------------------------------------------- +// Trigger Error Handling +// ----------------------------------------------------------------------------- +/** + * Log trigger error summary and, by default, fail if all triggers failed. + */ +function handleTriggerErrors(triggerErrors, totalTriggers, options = {}) { + if (triggerErrors.length === 0) { + return; + } + logGroup('Trigger Errors Summary'); + for (const err of triggerErrors) { + console.error(` - ${err}`); + } + logGroupEnd(); + // Fail if ALL triggers failed (no successful analysis was performed) + if ((options.failAll ?? true) && triggerErrors.length === totalTriggers && totalTriggers > 0) { + setFailed(`All ${totalTriggers} trigger(s) failed: ${triggerErrors.join('; ')}`); + } +} +/** + * Collect error messages from trigger results. + */ +function collectTriggerErrors(results) { + return results + .filter((r) => r.error) + .map((r) => { + const errorMessage = r.error instanceof Error ? r.error.message : String(r.error); + return `${r.triggerName}: ${errorMessage}`; + }); +} +/** + * Compute workflow outputs from reports. + */ +function computeWorkflowOutputs(reports) { + return { + findingsCount: reports.reduce((sum, r) => sum + r.findings.length, 0), + highCount: (0,matcher/* countSeverity */.jC)(reports, 'high'), + summary: reports.map((r) => r.summary).join('\n'), + }; +} +/** + * Set workflow output variables. + */ +function setWorkflowOutputs(outputs) { + setOutput('findings-count', outputs.findingsCount); + setOutput('high-count', outputs.highCount); + setOutput('summary', outputs.summary); +} +// ----------------------------------------------------------------------------- +// GitHub API Helpers +// ----------------------------------------------------------------------------- +/** + * Get the authenticated bot's login name. + * + * Tries three strategies in order: + * 1. GraphQL `viewer` query (works for both installation tokens and PATs) + * 2. `octokit.apps.getAuthenticated()` → `${slug}[bot]` (GitHub App JWT fallback) + * 3. `octokit.users.getAuthenticated()` (PAT fallback) + */ +async function getAuthenticatedBotLogin(octokit) { + // Strategy 1: GraphQL viewer (works for installation tokens and PATs) + try { + const result = await octokit.graphql('query { viewer { login } }'); + if (result.viewer?.login) { + return result.viewer.login; + } + } + catch { + // GraphQL may not be available or may fail for certain token types + } + // Strategy 2: GitHub App JWT endpoint + try { + const { data: app } = await octokit.apps.getAuthenticated(); + if (app?.slug) { + return `${app.slug}[bot]`; + } + } + catch { + // Not a GitHub App token + } + // Strategy 3: PAT user endpoint + try { + const { data: user } = await octokit.users.getAuthenticated(); + return user.login; + } + catch { + // Token doesn't have user scope + } + return null; +} +/** + * Get the default branch for a repository from the GitHub API. + */ +async function getDefaultBranchFromAPI(octokit, owner, repo) { + const { data } = await octokit.repos.get({ owner, repo }); + return data.default_branch; +} +// ----------------------------------------------------------------------------- +// Findings Output File +// ----------------------------------------------------------------------------- +const FINDINGS_OUTPUT_FILENAME = 'warden-findings.json'; +const FINDINGS_OUTPUT_DONE_FILENAME = `${FINDINGS_OUTPUT_FILENAME}.done`; +function getFindingsOutputValue(filePath, repoPath) { + const relativePath = (0,path/* normalizePath */.Fd)((0,external_node_path_.relative)(repoPath, filePath)); + return (0,path/* isRepoRelativePath */.Ms)(relativePath) ? relativePath : filePath; +} +/** + * Get the path for the findings output file. + * + * Uses the GitHub Actions workspace when available so action consumers can pass + * the output to upload actions that expect repo-relative paths. Falls back to + * RUNNER_TEMP for local callers and tests. + */ +function getFindingsOutputPath(repoPath) { + if (repoPath && process.env['GITHUB_WORKSPACE']) { + return (0,external_node_path_.join)(repoPath, FINDINGS_OUTPUT_FILENAME); + } + const tmpDir = process.env['RUNNER_TEMP'] ?? (0,external_node_os_.tmpdir)(); + return (0,external_node_path_.join)(tmpDir, FINDINGS_OUTPUT_FILENAME); +} +/** + * Remove a `.done` marker left over from a previous write at this same path. + * Used by workflow-start cleanup and as a defensive backstop before live + * writes. + */ +function clearStaleDoneMarker(repoPath) { + const filePath = getFindingsOutputPath(repoPath); + if (!(0,external_node_fs_.existsSync)(`${filePath}.done`)) { + return; + } + try { + (0,external_node_fs_.unlinkSync)(`${filePath}.done`); + } + catch { + // Best-effort cleanup; a stale marker left behind is not fatal. + } +} +/** + * Clear findings state left at the canonical output path by an earlier action + * invocation. Report mode may preserve the payload when it is also the replay + * artifact that the current invocation must consume. + */ +function clearStaleFindingsOutput(repoPath, options = {}) { + const filePath = getFindingsOutputPath(repoPath); + clearStaleDoneMarker(repoPath); + if (options.preservePayload || !(0,external_node_fs_.existsSync)(filePath)) { + return; + } + try { + (0,external_node_fs_.unlinkSync)(filePath); + } + catch { + // Best-effort cleanup; live output remains non-fatal by design. + } +} +/** + * Write structured findings data to a JSON file for external export (GCS, S3, etc.). + * + * Sets `findings-file` to a repo-relative path when possible so downstream + * steps can reference the path without tripping ignore processors on absolute + * runner temp paths. This is always a run's true final write — a `.done` + * sidecar is written alongside it so a local follower (see + * `writeFindingsOutputLive`) can tell a finished run from one still in + * progress. + */ +function writeFindingsOutput(reports, context, findingObservations = [], options = {}) { + const filePath = getFindingsOutputPath(context.repoPath); + const output = (0,reporting_output/* buildFindingsOutput */.Cs)(reports, context, findingObservations, options); + writeFileAtomic(filePath, JSON.stringify(output, null, 2)); + writeFileAtomic(`${filePath}.done`, ''); + setOutput('findings-file', getFindingsOutputValue(filePath, context.repoPath)); + return filePath; +} +/** + * Write the findings file as an in-progress snapshot: no `.done` sidecar, no + * `findings-file` action output (that must only ever reflect the run's one + * true final write, never race a downstream step reading it mid-run). Never + * throws — a transient write hiccup here must not abort a run the way a + * final-write failure legitimately can. + * + * Also clears a stale `.done` sidecar as a defensive backstop. Workflow + * entrypoints call `clearStaleFindingsOutput` before fallible setup. + */ +function writeFindingsOutputLive(reports, context, findingObservations = [], options = {}) { + try { + clearStaleDoneMarker(context.repoPath); + const filePath = getFindingsOutputPath(context.repoPath); + const output = (0,reporting_output/* buildFindingsOutput */.Cs)(reports, context, findingObservations, options); + writeFileAtomic(filePath, JSON.stringify(output, null, 2)); + } + catch (error) { + console.error(`::warning::Failed to write live findings output: ${error}`); + } +} + + +/***/ }), + +/***/ 39422: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ r: () => (/* binding */ runPRWorkflow) +/* harmony export */ }); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30340); +/* harmony import */ var _config_loader_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(77695); +/* harmony import */ var _event_context_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(58147); +/* harmony import */ var _triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(49431); +/* harmony import */ var _output_dedup_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(3941); +/* harmony import */ var _output_stale_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(95768); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(78481); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(82272); +/* harmony import */ var _fix_evaluation_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(45154); +/* harmony import */ var _sdk_usage_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(44759); +/* harmony import */ var _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(80029); +/* harmony import */ var _cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(43171); +/* harmony import */ var _review_state_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(52552); +/* harmony import */ var _service_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(19197); +/* harmony import */ var _triggers_executor_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(19533); +/* harmony import */ var _incremental_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(13778); +/* harmony import */ var _review_poster_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(44602); +/* harmony import */ var _review_coordination_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(48352); +/* harmony import */ var _review_review_feedback_gate_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(6643); +/* harmony import */ var _sdk_offline_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(8695); +/* harmony import */ var _sdk_extract_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(29709); +/* harmony import */ var _sdk_circuit_breaker_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(71794); +/* harmony import */ var _checks_manager_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(47423); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(98514); +/* harmony import */ var _output_renderer_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(21242); +/* harmony import */ var _reporting_output_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(4169); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_triggers_executor_js__WEBPACK_IMPORTED_MODULE_14__]); +_triggers_executor_js__WEBPACK_IMPORTED_MODULE_14__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; +/** + * PR Workflow + * + * Handles pull_request and push events. PR runs may execute in legacy `run` + * mode or the split `analyze`/`report` flow: analyze owns skill execution and + * artifact creation, while report owns GitHub writes and must only replay an + * artifact that matches the current PR context. + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +class ReportWriteError extends Error { + constructor(operation, error) { + super(`${operation}: ${error instanceof Error ? error.message : String(error)}`); + this.name = 'ReportWriteError'; + } +} +function existingCommentToFinding(comment) { + const location = comment.path && comment.line > 0 + ? { + path: comment.path, + startLine: comment.line, + endLine: comment.line, + } + : undefined; + return { + id: comment.findingId ?? `comment-${comment.id}`, + severity: comment.severity ?? 'low', + title: comment.title, + description: comment.description, + ...(comment.confidence ? { confidence: comment.confidence } : {}), + ...(location ? { location } : {}), + }; +} +function reportsPullRequestCheck(trigger, context) { + return (Boolean(context.pullRequest) && + (trigger.type === 'pull_request' || trigger.type === '*')); +} +function checkOptionsForPullRequest(context, postChecks) { + if (!context.pullRequest || !postChecks) { + return undefined; + } + return { + owner: context.repository.owner, + repo: context.repository.name, + headSha: context.pullRequest.headSha, + }; +} +/** + * The only caller, `toSkippedTriggers`, is always fed a list pre-filtered by + * `reportsPullRequestCheck` to `pull_request`/`'*'`-type triggers, so this + * only ever needs to explain why a PR-scoped trigger didn't fire this run — + * not schedule/local triggers, which never reach this function. + */ +function deriveSkippedReason(trigger, context) { + if (trigger.type === 'pull_request') { + if (context.eventType !== 'pull_request') + return 'no_event_match'; + if (!trigger.actions?.includes(context.action)) + return 'no_event_match'; + if (!(0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .matchPullRequestState */ .xf)(trigger, context)) { + if (context.action === 'labeled' && trigger.labels !== undefined) { + const eventLabelMatches = context.label !== undefined && trigger.labels.includes(context.label); + if (!eventLabelMatches) + return 'label_mismatch'; + } + const labels = context.pullRequest?.labels ?? []; + const labelMatches = trigger.labels?.some((label) => labels.includes(label)); + if (trigger.labels !== undefined && !labelMatches) + return 'label_mismatch'; + return 'draft_state'; + } + } + return 'path_filter'; +} +function toSkippedTriggers(skippedTriggers, context) { + return skippedTriggers.map((t) => ({ + skillName: t.skill, + triggerId: t.id, + triggerName: t.name, + reason: deriveSkippedReason(t, context), + })); +} +/** + * A trigger that threw before producing a report has no `report`, so + * `toSkillExecutions`'s filter (which requires one) can never include it — + * without this, an errored trigger vanishes from the export entirely aside + * from a console warning and (in analyze/report mode) a `triggerResults` + * row. Surfacing it here instead keeps it visible in the same place a + * schedule-mode trigger error is now surfaced. + */ +function toErroredSkippedTriggers(results) { + return results + .filter((r) => r.error && !r.report) + .map((r) => ({ + skillName: r.skillName, + triggerId: r.triggerId, + triggerName: r.triggerName, + reason: 'error', + })); +} +/** Build per-execution metadata for the findings output from settled trigger results. */ +function toSkillExecutions(results) { + return results + .filter((r) => Boolean(r.report)) + .map((r) => ({ + report: r.report, + skillExecutionId: r.skillExecutionId, + triggerId: r.triggerId, + triggerName: r.triggerName, + checkRunUrl: r.checkRunUrl, + checkRunId: r.checkRunId, + auxiliaryModel: r.auxiliaryModel, + synthesisModel: r.synthesisModel, + reviewEvent: r.reviewEventPosted, + // Matches buildSkillCheckPayload's own conclusion computation + // (confidence-filtered first) so this mirrors what actually posted to + // the check run at checkRunUrl/checkRunId. determineConclusion never + // returns 'cancelled' — that value exists on CheckConclusion for actual + // check-run API responses (aborted runs), which this export doesn't + // currently read from. + checkConclusion: (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .determineConclusion */ .Hx)((0,_types_index_js__WEBPACK_IMPORTED_MODULE_8__/* .filterFindings */ .Ni)(r.report.findings, undefined, r.minConfidence), r.failOn, r.failCheck), + findingProcessingEvents: r.findingProcessingEvents, + })); +} +function resolveWorkflowAuxiliaryOptions(layered) { + const baseDefaults = layered.baseConfig?.defaults; + const repoDefaults = layered.repoConfig?.defaults ?? layered.config.defaults; + return { + // These workflow-scoped auxiliary calls are not tied to an individual + // trigger, so the org base config remains the enforced baseline and the + // repo layer only fills fields the base omits. + runtime: baseDefaults?.runtime ?? repoDefaults?.runtime ?? 'pi', + model: (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .emptyToUndefined */ .Zu)(baseDefaults?.auxiliary?.model) ?? + (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .emptyToUndefined */ .Zu)(repoDefaults?.auxiliary?.model), + effort: baseDefaults?.auxiliary?.effort ?? repoDefaults?.auxiliary?.effort, + maxRetries: baseDefaults?.auxiliary?.maxRetries ?? + baseDefaults?.auxiliaryMaxRetries ?? + repoDefaults?.auxiliary?.maxRetries ?? + repoDefaults?.auxiliaryMaxRetries, + }; +} +// ----------------------------------------------------------------------------- +// Fix Evaluation Logging +// ----------------------------------------------------------------------------- +function logFixEvaluation(ev, index, total) { + const totalTokens = ev.usage.inputTokens + ev.usage.outputTokens; + const costStr = ev.usage.costUSD > 0 ? `, ${(0,_cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__/* .formatCost */ .BD)(ev.usage.costUSD)}` : ''; + const idPrefix = ev.findingId ? `${ev.findingId} ` : ''; + const verdict = ev.verdict; + const line = ` [${index + 1}/${total}] ${idPrefix}${ev.path}:${ev.line} → ${verdict} (${(0,_cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__/* .formatDuration */ .a3)(ev.durationMs)}, ${(0,_cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__/* .formatTokens */ ._y)(totalTokens)} tok${costStr})`; + if (ev.usedFallback) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(line); + } + else { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(line); + } + if (ev.verdict === 'attempted_failed' && ev.reasoning) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(` reason: "${ev.reasoning}"`); + } +} +function groupCommentsForFixEvaluation(comments, headSha) { + const groups = new Map(); + let currentHeadCount = 0; + let missingOriginalCommitCount = 0; + for (const comment of comments) { + const originalCommitSha = comment.originalCommitSha; + if (!originalCommitSha) { + missingOriginalCommitCount++; + continue; + } + if (originalCommitSha === headSha) { + currentHeadCount++; + continue; + } + const group = groups.get(originalCommitSha); + if (group) { + group.push(comment); + } + else { + groups.set(originalCommitSha, [comment]); + } + } + return { groups, currentHeadCount, missingOriginalCommitCount }; +} +function mergeFixEvaluationResults(results) { + return { + toResolve: results.flatMap((result) => result.toResolve), + toReply: results.flatMap((result) => result.toReply), + skipped: results.reduce((total, result) => total + result.skipped, 0), + evaluated: results.reduce((total, result) => total + result.evaluated, 0), + failedEvaluations: results.reduce((total, result) => total + result.failedEvaluations, 0), + uniqueFindingsEvaluated: results.reduce((total, result) => total + result.uniqueFindingsEvaluated, 0), + uniqueFindingsCodeChanged: results.reduce((total, result) => total + result.uniqueFindingsCodeChanged, 0), + uniqueFindingsResolved: results.reduce((total, result) => total + result.uniqueFindingsResolved, 0), + usage: (0,_sdk_usage_js__WEBPACK_IMPORTED_MODULE_25__/* .aggregateUsage */ .Z$)(results.map((result) => result.usage)), + evaluations: results.flatMap((result) => result.evaluations), + }; +} +// ----------------------------------------------------------------------------- +// Phase Functions +// ----------------------------------------------------------------------------- +/** + * Parse event payload, build context, load config, match triggers. + */ +async function initializeWorkflow(octokit, inputs, eventName, eventPath, repoPath) { + let eventPayload; + try { + eventPayload = JSON.parse((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(eventPath, 'utf-8')); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'read_event_payload' } }); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Failed to read event payload: ${error}`); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroup */ .QT)('Building event context'); + console.log(`Event: ${eventName}`); + console.log(`Workspace: ${repoPath}`); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + let context; + try { + context = await (0,_event_context_js__WEBPACK_IMPORTED_MODULE_4__/* .buildEventContext */ .e)(eventName, eventPayload, repoPath, octokit); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'build_event_context' } }); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Failed to build event context: ${error}`); + } + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .setRepositoryScope */ .vx)(context.repository.fullName); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroup */ .QT)('Loading configuration'); + if (inputs.baseConfigPath) { + console.log(`Base config path: ${inputs.baseConfigPath}`); + } + if (inputs.baseSkillRoot) { + console.log(`Base skill root: ${inputs.baseSkillRoot}`); + } + console.log(`Repo config path: ${inputs.configPath}`); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + let runnerConcurrency; + let auxiliaryOptions = { runtime: 'pi' }; + let skillRootsByName; + try { + const layered = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .loadLayeredWardenConfig */ .M3)(repoPath, { + baseConfigPath: inputs.baseConfigPath, + configPath: inputs.configPath, + onWarning: (message) => console.log(`::warning::${message}`), + }); + (0,_sdk_offline_js__WEBPACK_IMPORTED_MODULE_26__/* .configureWardenOffline */ .zV)(layered.baseConfig?.defaults?.offline === true + || layered.repoConfig?.defaults?.offline === true + || layered.config.defaults?.offline === true); + // The org base config is an enforced baseline. Repo config extends the run + // with additional repo-local triggers, but does not override these + // action-level settings for the global workflow. + runnerConcurrency = + layered.baseConfig?.runner?.concurrency ?? + layered.repoConfig?.runner?.concurrency ?? + layered.config.runner?.concurrency; + auxiliaryOptions = resolveWorkflowAuxiliaryOptions(layered); + skillRootsByName = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .buildSkillRootsByName */ .hd)(repoPath, layered, inputs.baseSkillRoot); + // Same enforced-baseline precedence as runnerConcurrency/auxiliaryOptions above: + // this is a workflow-level setting, not a per-trigger one, so the org base + // config wins over the repo config. + const postChecks = layered.baseConfig?.defaults?.postChecks ?? + layered.repoConfig?.defaults?.postChecks ?? + layered.config.defaults?.postChecks ?? + inputs.postChecks; + const resolvedTriggers = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveLayeredSkillConfigs */ .Ln)(layered, undefined, skillRootsByName); + const matchedTriggers = resolvedTriggers.filter((t) => (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .matchTrigger */ .QW)(t, context, 'github')); + const skippedTriggers = resolvedTriggers.filter((t) => reportsPullRequestCheck(t, context) && !matchedTriggers.includes(t)); + if (matchedTriggers.length > 0) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroup */ .QT)('Matched triggers'); + for (const trigger of matchedTriggers) { + console.log(`- ${trigger.name}: ${trigger.skill}`); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + } + else { + console.log('No triggers matched for this event'); + } + const service = (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .resolveActionServiceOptions */ .iZ)(inputs, layered.config.service); + const memoryRecall = inputs.mode === 'report' || matchedTriggers.length === 0 + ? undefined + : await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .recallActionMemoryFailOpen */ .t4)(service, context, matchedTriggers.map((trigger) => trigger.skill)); + return { + context, + service, + runnerConcurrency, + auxiliaryOptions, + resolvedTriggers, + matchedTriggers, + skippedTriggers, + memoryRecall, + postChecks, + }; + } + catch (error) { + if (error instanceof _config_loader_js__WEBPACK_IMPORTED_MODULE_3__/* .ConfigLoadError */ .tx && + error.message.includes('not found') && + !inputs.baseConfigPath) { + const message = 'No warden.toml found. Skipping analysis.'; + console.log(`::warning::${message}`); + return { + context, + service: (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .resolveActionServiceOptions */ .iZ)(inputs), + runnerConcurrency, + auxiliaryOptions, + resolvedTriggers: [], + matchedTriggers: [], + skippedTriggers: [], + skipCoreCheck: { + title: 'No warden.toml found', + message, + }, + postChecks: inputs.postChecks, + }; + } + throw error; + } +} +/** + * Fetch the bot's previous review state on a PR. + * Returns null if the bot has no actionable reviews or identity cannot be determined. + */ +async function fetchPreviousReviewInfo(octokit, context) { + if (!context.pullRequest) { + return null; + } + try { + const botLogin = await (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .getAuthenticatedBotLogin */ .Uf)(octokit); + if (!botLogin) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Skipping dismiss flow: cannot identify bot (using PAT or GITHUB_TOKEN instead of GitHub App)'); + return null; + } + // Note: No pagination. PRs with 100+ reviews are rare; if Warden's review + // is beyond page 1, user can manually dismiss. Not worth the complexity. + const { data: reviews } = await octokit.pulls.listReviews({ + owner: context.repository.owner, + repo: context.repository.name, + pull_number: context.pullRequest.number, + per_page: 100, + }); + return (0,_review_state_js__WEBPACK_IMPORTED_MODULE_12__/* .findBotReviewState */ .a)(reviews, botLogin); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to fetch previous review info: ${error}`); + return null; + } +} +/** + * Create core check and fetch previous review info. PR-only. + */ +async function setupGitHubState(octokit, context, postChecks) { + if (!context.pullRequest) { + return { previousReviewInfo: null }; + } + let coreCheckId; + let previousReviewInfo = null; + // Create core warden check + const checkOptions = checkOptionsForPullRequest(context, postChecks); + if (checkOptions) { + try { + const coreCheck = await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createCoreCheck */ .c)(octokit, checkOptions); + coreCheckId = coreCheck.checkRunId; + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Created core check: ${coreCheck.url}`); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'create_core_check' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to create core check: ${error}`); + } + } + previousReviewInfo = await fetchPreviousReviewInfo(octokit, context); + if (previousReviewInfo) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Previous Warden review state: ${previousReviewInfo.state}`); + } + return { coreCheckId, previousReviewInfo }; +} +/** + * Build the context-bound check lifecycle used by legacy run mode. + * Analyze mode omits this capability so trigger execution cannot write checks. + */ +function createTriggerCheckReporter(octokit, context, postChecks) { + const checkOptions = checkOptionsForPullRequest(context, postChecks); + if (!checkOptions) { + return undefined; + } + return { + async start(skillName) { + const check = await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createSkillCheck */ .uP)(octokit, skillName, checkOptions); + return { + url: check.url, + checkRunId: check.checkRunId, + complete: (report, options) => (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .updateSkillCheck */ .Zv)(octokit, check.checkRunId, report, { + ...checkOptions, + ...options, + }), + fail: (error) => (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .failSkillCheck */ .OZ)(octokit, check.checkRunId, error, checkOptions), + }; + }, + }; +} +/** Build the incremental baseline source when any matched trigger has `incremental` on. */ +function incrementalSourceFor(octokit, context, matchedTriggers) { + if (context.eventType !== 'pull_request' || !context.pullRequest) + return undefined; + if (!matchedTriggers.some((trigger) => trigger.incremental)) + return undefined; + return (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .createIncrementalBaselineSource */ .P7)(octokit, { + owner: context.repository.owner, + repo: context.repository.name, + pullNumber: context.pullRequest.number, + headSha: context.pullRequest.headSha, + baseSha: context.pullRequest.baseSha, + warn: _cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6, + }); +} +async function executeAllTriggers(matchedTriggers, context, runnerConcurrency, inputs, options = {}) { + const concurrency = runnerConcurrency ?? inputs.parallel; + const runtimeEnv = await (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .prepareRuntimeEnvironment */ .bZ)(matchedTriggers, inputs); + const analysisQueue = new _utils_index_js__WEBPACK_IMPORTED_MODULE_9__/* .AsyncWorkQueue */ .Z_(concurrency); + const abortController = new AbortController(); + const circuitBreaker = new _sdk_circuit_breaker_js__WEBPACK_IMPORTED_MODULE_19__/* .ProviderFailureCircuitBreaker */ .j({ abortController }); + const completedSoFar = []; + // Limit trigger dispatch too; the analysis queue only gates work after a trigger starts. + const results = await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_9__/* .runPool */ .kD)(matchedTriggers, concurrency, async (trigger) => { + const result = await (0,_triggers_executor_js__WEBPACK_IMPORTED_MODULE_14__/* .executeTrigger */ .k)(trigger, { + context, + anthropicApiKey: inputs.anthropicApiKey, + claudePath: runtimeEnv.pathToClaudeCodeExecutable, + globalFailOn: inputs.failOn, + globalReportOn: inputs.reportOn, + globalMaxFindings: inputs.maxFindings, + globalRequestChanges: inputs.requestChanges, + globalFailCheck: inputs.failCheck, + analysisQueue, + abortController, + circuitBreaker, + checks: options.checks, + historicalEvidence: options.memoryRecall?.historicalEvidence, + incremental: options.incremental, + }); + completedSoFar.push(result); + options.onTriggerComplete?.([...completedSoFar]); + return result; + }, { shouldAbort: () => abortController.signal.aborted }); + // `runPool` never dispatches work items past an abort, so a matched trigger + // the circuit breaker aborted before it started doesn't appear in `results` + // at all — not even as an error. Synthesize an aborted result for each one + // so it's still accounted for in `skippedTriggers`/`triggerResults`, and so + // an all-dropped run can't look like zero errors occurred. + const dispatchedTriggerIds = new Set(results.map((result) => result.triggerId)); + const undispatched = matchedTriggers.filter((trigger) => !dispatchedTriggerIds.has(trigger.id)); + if (undispatched.length === 0) { + return results; + } + const abortedResults = undispatched.map((trigger) => ({ + triggerId: trigger.id, + skillExecutionId: trigger.skillExecutionId, + triggerName: trigger.name, + skillName: trigger.skill, + error: new Error('Trigger execution aborted before dispatch (circuit breaker tripped)'), + })); + completedSoFar.push(...abortedResults); + options.onTriggerComplete?.([...completedSoFar]); + return [...results, ...abortedResults]; +} +/** + * Whether a trigger's findings meet its `failOn` with `requestChanges` on, + * so the run asks for changes on the PR. + */ +function requestsChanges(result) { + if (!result.failOn || result.failOn === 'off' || !(result.requestChanges ?? false) || !result.report) + return false; + const filtered = { ...result.report, findings: (0,_types_index_js__WEBPACK_IMPORTED_MODULE_8__/* .filterFindings */ .Ni)(result.report.findings, undefined, result.minConfidence) }; + return (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .shouldFail */ .W9)(filtered, result.failOn); +} +/** + * Mark a trigger's skill check as an incremental baseline once its findings + * reached the PR. A run that requested changes is never a baseline: skipping + * its hunks later would let the blocking review be dismissed without the + * finding being checked again. A write failure leaves no baseline, so the + * next run is full. + */ +async function recordIncrementalBaseline(octokit, context, result, observations) { + const externalId = result.report ? (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .baselineExternalId */ .qw)(result.report) : undefined; + if (!externalId || !result.report || result.checkRunId === undefined) + return; + if (!(0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .isBaselineConclusion */ .TR)(result.report, result)) + return; + if (requestsChanges(result)) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`${result.triggerName}: not recording an incremental baseline; findings requested changes`); + return; + } + if (!(0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .feedbackDelivered */ .GR)(observations)) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`${result.triggerName}: not recording an incremental baseline; some findings did not reach the PR`); + return; + } + try { + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .markSkillCheckBaseline */ .Y9)(octokit, result.checkRunId, externalId, { + owner: context.repository.owner, + repo: context.repository.name, + }); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'mark_incremental_baseline' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to record incremental baseline for ${result.triggerName}: ${error}`); + } +} +/** + * Fetch existing comments, post reviews with cross-trigger dedup, accumulate failure state. + */ +async function postReviewsAndTrackFailures(octokit, context, results, inputs, auxiliaryOptions, gate, options = {}) { + // Skip the comment fetch only when the head has definitively advanced; on an + // unverifiable head the fetch is a harmless read and keeps later phases able + // to resolve comments once the API recovers. + // Keep original list separate for stale detection (modified list includes newly posted comments) + let fetchedComments = []; + let commentsFetched = false; + let existingComments = []; + let writability = await gate.check(); + if (writability !== 'blocked' && context.pullRequest) { + try { + fetchedComments = await (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_6__/* .fetchExistingComments */ .kX)(octokit, context.repository.owner, context.repository.name, context.pullRequest.number); + commentsFetched = true; + existingComments = [...fetchedComments]; + if (fetchedComments.length > 0) { + const wardenCount = fetchedComments.filter((c) => c.isWarden).length; + const externalCount = fetchedComments.length - wardenCount; + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Found ${fetchedComments.length} existing comments for deduplication (${wardenCount} Warden, ${externalCount} external)`); + } + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'fetch_existing_comments' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to fetch existing comments for deduplication: ${error}`); + } + } + // Post reviews to GitHub (sequentially to avoid rate limits) + const reports = []; + const activeWardenCommentIds = new Set(); + const findingObservations = []; + let shouldFailAction = false; + const failureReasons = []; + for (const result of results) { + if (result.report) { + reports.push(result.report); + const observationStart = findingObservations.length; + // Post review. The gate memoizes briefly, so this stays cheap between + // writes but re-verifies after slow phases (LLM dedup, consolidation). + if (writability !== 'blocked') { + writability = await gate.check(); + } + let reviewPosted = false; + if (writability === 'writable') { + const postResult = await (0,_review_poster_js__WEBPACK_IMPORTED_MODULE_16__/* .postTriggerReview */ .v)({ + result, + existingComments, + apiKey: inputs.anthropicApiKey, + runtime: auxiliaryOptions.runtime, + model: auxiliaryOptions.model, + effort: auxiliaryOptions.effort, + maxRetries: auxiliaryOptions.maxRetries, + failOnPostError: options.failOnPostError, + }, { octokit, context, feedbackGate: gate }); + // Add newly posted comments to existing comments for cross-trigger deduplication + existingComments.push(...postResult.newComments); + postResult.activeWardenCommentIds.forEach((id) => activeWardenCommentIds.add(id)); + findingObservations.push(...postResult.findingObservations); + reviewPosted = postResult.posted; + } + else { + const skippedReason = writability === 'blocked' + ? 'pull_request_changed' + : 'review_not_posted'; + const reportableFindings = (0,_types_index_js__WEBPACK_IMPORTED_MODULE_8__/* .filterFindings */ .Ni)(result.report.findings, result.reportOn, result.minConfidence); + const skill = result.report.skill; + findingObservations.push(...reportableFindings.map((finding) => ({ + outcome: 'skipped', + finding, + skill, + skillExecutionId: result.skillExecutionId, + skippedReason, + }))); + } + await recordIncrementalBaseline(octokit, context, result, findingObservations.slice(observationStart)); + // A stale head skips silently (the newer run owns feedback), but an + // unverifiable head must not silently swallow a blocking review. + // Evaluated after the post attempt so a head that becomes unverifiable + // during the poster's own LLM phases is escalated too. + if (!reviewPosted && wouldPostBlockingReview(result) && (await gate.check()) === 'unknown') { + shouldFailAction = true; + failureReasons.push(`${result.triggerName}: Could not verify the PR head; blocking review was not posted`); + } + // Check if we should fail based on this trigger's config + // Filter by confidence first so low-confidence findings don't cause failure + const failCheck = result.failCheck ?? false; + const reportForFail = { ...result.report, findings: (0,_types_index_js__WEBPACK_IMPORTED_MODULE_8__/* .filterFindings */ .Ni)(result.report.findings, undefined, result.minConfidence) }; + if (failCheck && result.failOn && (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .shouldFail */ .W9)(reportForFail, result.failOn)) { + shouldFailAction = true; + const count = (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .countFindingsAtOrAbove */ .tH)(reportForFail, result.failOn); + failureReasons.push(`${result.triggerName}: Found ${count} ${result.failOn}+ severity issues`); + } + } + } + return { + reports, + fetchedComments, + commentsFetched, + existingComments, + activeWardenCommentIds, + findingObservations, + shouldFailAction, + failureReasons, + }; +} +/** + * Whether posting this trigger's review would produce a blocking + * REQUEST_CHANGES review. Mirrors the poster's posting predicate: the + * renderer can emit a REQUEST_CHANGES render result with zero reportable + * findings (reportOn stricter than failOn), which the poster never posts — + * its reportOn early return runs before the needsRequestChanges branch, so + * that branch is only reachable when this predicate is already true (the + * pre-dedup filtered set was non-empty or reportOnSuccess is set). + */ +function wouldPostBlockingReview(result) { + if (!result.report || result.renderResult?.review?.event !== 'REQUEST_CHANGES') { + return false; + } + const filteredFindings = (0,_types_index_js__WEBPACK_IMPORTED_MODULE_8__/* .filterFindings */ .Ni)(result.report.findings, result.reportOn, result.minConfidence); + return filteredFindings.length > 0 || (result.reportOnSuccess ?? false); +} +/** Skills whose reports covered only the triggering push, not the whole PR diff. */ +function pushScopedSkills(reports) { + return new Set(reports.filter((r) => r.hunkGate?.pushScoped).map((r) => r.skill)); +} +/** + * Evaluate fix attempts on unresolved comments and resolve stale comments. + * + * Returns whether all Warden comments are resolved after evaluation. + * Report mode passes failOnWriteError so GitHub write failures abort delivery. + */ +async function evaluateFixesAndResolveStale(octokit, context, fetchedComments, allFindings, activeWardenCommentIds, canResolveStale, anthropicApiKey, auxiliaryOptions, gate, options = {}) { + const wardenComments = fetchedComments.filter((c) => c.isWarden); + const commentsResolvedByFixEval = new Set(); + const commentsEvaluatedByFixEval = new Set(); + const commentsResolvedByStale = new Set(); + const findingObservations = []; + const blockedReviewFeedbackWriteResult = () => ({ + allResolved: false, + autoResolvedByFixEvaluation: commentsResolvedByFixEval.size, + autoResolvedByStaleCheck: commentsResolvedByStale.size, + findingObservations, + }); + // Comments on hunks that incremental review skipped were not re-checked, + // so treat them like re-detected comments: no fix evaluation, no stale pass. + const carriedCommentIds = new Set(wardenComments + .filter((c) => (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .isOnCarriedHunk */ .y3)(c, options.carriedRanges ?? [])) + .map((c) => c.id)); + if (carriedCommentIds.size > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Incremental review: keeping ${carriedCommentIds.size} comment(s) on unchanged hunks open`); + } + const commentsForFixEvaluation = wardenComments.filter((c) => !activeWardenCommentIds.has(c.id) && !carriedCommentIds.has(c.id)); + const fixEvaluationRuntime = auxiliaryOptions.runtime ?? 'pi'; + const canUseFixEvaluationRuntime = (0,_sdk_extract_js__WEBPACK_IMPORTED_MODULE_18__/* .canUseRuntimeAuth */ .ad)({ + apiKey: anthropicApiKey, + runtime: fixEvaluationRuntime, + }); + // Check head freshness up front so a stale or unverifiable run skips the + // LLM fix evaluation entirely, not just the writes it would produce. + let writability = 'blocked'; + if (wardenComments.length > 0) { + if (!canResolveStale) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Skipping stale comment resolution due to trigger failures'); + } + else if (context.pullRequest) { + writability = await gate.check(); + if (writability === 'blocked') { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Skipping stale comment resolution because this run is no longer analyzing the current PR head'); + } + else if (writability === 'unknown') { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Skipping stale comment resolution because the current PR head could not be verified'); + } + } + } + const canMutateFeedback = writability === 'writable'; + // Evaluate follow-up commit fix attempts + if (context.pullRequest && + commentsForFixEvaluation.length > 0 && + canMutateFeedback && + canUseFixEvaluationRuntime) { + try { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroup */ .QT)('Fix evaluation'); + // Only evaluate comments that were posted on an earlier commit. If a comment was + // posted on the current headSha there are no follow-up changes to evaluate yet, and + // running fix evaluation would compare the entire PR diff (PR base to head) against a + // finding from this same run, producing spurious "Fix attempt detected" replies. + const headSha = context.pullRequest.headSha; + const { groups: commentsByOriginalCommit, currentHeadCount, missingOriginalCommitCount, } = groupCommentsForFixEvaluation(commentsForFixEvaluation, headSha); + const unresolvedCount = [...commentsByOriginalCommit.values()] + .flat() + .filter((c) => !c.isResolved && c.threadId).length; + if (unresolvedCount > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Fix evaluation: evaluating ${unresolvedCount} unresolved comments`); + } + else { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Fix evaluation: no eligible comments (${currentHeadCount} current head, ` + + `${missingOriginalCommitCount} missing original commit)`); + } + const groupResults = []; + for (const [commentBaseSha, groupComments] of commentsByOriginalCommit) { + groupResults.push(await (0,_fix_evaluation_index_js__WEBPACK_IMPORTED_MODULE_10__/* .evaluateFixAttempts */ .Z)(octokit, groupComments, { + owner: context.repository.owner, + repo: context.repository.name, + baseSha: commentBaseSha, + headSha, + }, allFindings, anthropicApiKey, { ...auxiliaryOptions, runtime: fixEvaluationRuntime })); + } + const fixEvaluation = mergeFixEvaluationResults(groupResults); + // Log per-evaluation details + fixEvaluation.evaluations.forEach((ev, i) => logFixEvaluation(ev, i, fixEvaluation.evaluations.length)); + // Resolve successful fixes + if (fixEvaluation.toResolve.length > 0) { + if (!await gate.canWrite()) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + return blockedReviewFeedbackWriteResult(); + } + const { resolvedCount, resolvedIds } = await (0,_output_stale_js__WEBPACK_IMPORTED_MODULE_7__/* .resolveStaleComments */ .AG)(octokit, fixEvaluation.toResolve, { failOnError: options.failOnWriteError }).catch((error) => { + if (options.failOnWriteError) { + throw new ReportWriteError('Failed to resolve comments via fix evaluation', error); + } + throw error; + }); + if (resolvedCount > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Resolved ${resolvedCount} comments via fix evaluation`); + } + // Track only actually resolved comments for allResolved check + resolvedIds.forEach((id) => commentsResolvedByFixEval.add(id)); + for (const comment of fixEvaluation.toResolve) { + if (!resolvedIds.has(comment.id)) + continue; + findingObservations.push({ + outcome: 'resolved', + finding: existingCommentToFinding(comment), + skill: comment.skills?.[0], + resolvedReason: 'fix_evaluation', + }); + } + } + // Post replies for failed fixes and track them so stale pass doesn't override + if (fixEvaluation.toReply.length > 0 && !await gate.canWrite()) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + return blockedReviewFeedbackWriteResult(); + } + for (const reply of fixEvaluation.toReply) { + commentsEvaluatedByFixEval.add(reply.comment.id); + if (reply.comment.threadId) { + try { + await (0,_fix_evaluation_index_js__WEBPACK_IMPORTED_MODULE_10__/* .postThreadReply */ .l)(octokit, reply.comment.threadId, reply.replyBody); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'post_thread_reply' } }); + if (options.failOnWriteError) { + throw new ReportWriteError('Failed to post fix evaluation reply', error); + } + } + } + } + if (fixEvaluation.evaluated > 0) { + const totalTokens = fixEvaluation.usage.inputTokens + fixEvaluation.usage.outputTokens; + let usageStr = ''; + if (totalTokens > 0) { + usageStr = `, ${(0,_cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__/* .formatTokens */ ._y)(totalTokens)} tok, ${(0,_cli_output_formatters_js__WEBPACK_IMPORTED_MODULE_11__/* .formatCost */ .BD)(fixEvaluation.usage.costUSD)}`; + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Fix evaluation: ${fixEvaluation.toResolve.length} resolved, ` + + `${fixEvaluation.toReply.length} need attention, ` + + `${fixEvaluation.skipped} skipped` + + usageStr); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'evaluate_fix_attempts' } }); + if (error instanceof ReportWriteError) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + throw error; + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to evaluate fix attempts: ${error}`); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .logGroupEnd */ .TN)(); + } + } + // Resolve stale Warden comments (comments that no longer have matching findings) + // Exclude comments already handled by fix evaluation (resolved or flagged as needing attention) + if (context.pullRequest && wardenComments.length > 0 && canMutateFeedback) { + try { + const scope = (0,_output_stale_js__WEBPACK_IMPORTED_MODULE_7__/* .buildAnalyzedScope */ .B8)(context.pullRequest.files, options.partialScopeSkills); + const commentsForStaleCheck = wardenComments.filter((c) => !activeWardenCommentIds.has(c.id) && + !carriedCommentIds.has(c.id) && + !commentsResolvedByFixEval.has(c.id) && + !commentsEvaluatedByFixEval.has(c.id)); + const staleComments = (0,_output_stale_js__WEBPACK_IMPORTED_MODULE_7__/* .findStaleComments */ .t8)(commentsForStaleCheck, allFindings, scope); + if (staleComments.length > 0) { + if (!await gate.canWrite()) { + return blockedReviewFeedbackWriteResult(); + } + const { resolvedCount, resolvedIds } = await (0,_output_stale_js__WEBPACK_IMPORTED_MODULE_7__/* .resolveStaleComments */ .AG)(octokit, staleComments, { failOnError: options.failOnWriteError }).catch((error) => { + if (options.failOnWriteError) { + throw new ReportWriteError('Failed to resolve stale comments', error); + } + throw error; + }); + if (resolvedCount > 0) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Resolved ${resolvedCount} stale Warden comments`); + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .emitStaleResolutionMetric */ .fL)(resolvedCount); + // Emit per-skill breakdown (only count actually resolved comments) + const bySkill = new Map(); + for (const c of staleComments) { + if (!resolvedIds.has(c.id)) + continue; + const skill = c.skills?.[0]; + if (skill) { + bySkill.set(skill, (bySkill.get(skill) ?? 0) + 1); + } + } + for (const [skill, count] of bySkill) { + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .emitStaleResolutionMetric */ .fL)(count, skill); + } + } + resolvedIds.forEach((id) => commentsResolvedByStale.add(id)); + for (const comment of staleComments) { + if (!resolvedIds.has(comment.id)) + continue; + findingObservations.push({ + outcome: 'resolved', + finding: existingCommentToFinding(comment), + skill: comment.skills?.[0], + resolvedReason: 'stale_check', + }); + } + } + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'resolve_stale_comments' } }); + if (error instanceof ReportWriteError) { + throw error; + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to resolve stale comments: ${error}`); + } + } + // Determine if all unresolved Warden comments were resolved during this run + const unresolvedBefore = wardenComments.filter((c) => !c.isResolved); + const allResolved = unresolvedBefore.every((c) => commentsResolvedByFixEval.has(c.id) || commentsResolvedByStale.has(c.id)); + return { + allResolved, + autoResolvedByFixEvaluation: commentsResolvedByFixEval.size, + autoResolvedByStaleCheck: commentsResolvedByStale.size, + findingObservations, + }; +} +/** + * Dismiss a prior blocking Warden review only when current results prove it is clear. + * Report mode sets failOnWriteError so dismissal write failures fail delivery. + */ +async function dismissPreviousReviewIfResolved(octokit, context, previousReviewInfo, results, canResolveStale, gate, options = {}) { + // Dismiss previous CHANGES_REQUESTED if all blocking issues are resolved. + // Requires: all triggers succeeded, current run would not request changes, + // and at least one trigger has an active failOn (prevents accidental dismiss when config changes). + const wouldRequestChanges = results.some(requestsChanges); + const hasActiveFailOn = results.some((r) => r.failOn && r.failOn !== 'off'); + if (context.pullRequest && + previousReviewInfo?.state === 'CHANGES_REQUESTED' && + canResolveStale && + !wouldRequestChanges && + hasActiveFailOn) { + if (options.carriedFindingsOpen) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Keeping previous CHANGES_REQUESTED review: comments on unchanged hunks are still open'); + return; + } + if (!await gate.canWrite()) { + return; + } + try { + await octokit.pulls.dismissReview({ + owner: context.repository.owner, + repo: context.repository.name, + pull_number: context.pullRequest.number, + review_id: previousReviewInfo.reviewId, + message: 'All previously reported issues have been resolved.', + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Dismissed previous CHANGES_REQUESTED review'); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'dismiss_review' } }); + if (options.failOnWriteError) { + throw new ReportWriteError('Failed to dismiss previous review', error); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to dismiss previous review: ${error}`); + } + } +} +/** + * Dismiss review, set outputs, update core check, fail action. + */ +async function finalizeWorkflow(octokit, context, previousReviewInfo, coreCheckId, results, reports, findingObservations, shouldFailAction, failureReasons, canResolveStale, gate, triggerErrors, skippedTriggers, inputs, service, memoryRecall, postChecks, matchedTriggers, resolvedTriggers, carriedFindingsOpen = false) { + await dismissPreviousReviewIfResolved(octokit, context, previousReviewInfo, results, canResolveStale, gate, { carriedFindingsOpen }); + // Set outputs + const outputs = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .computeWorkflowOutputs */ .dV)(reports); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setWorkflowOutputs */ .wZ)(outputs); + // Write structured findings to file for external export (GCS, S3, etc.) + const findingsOptions = { + triggerResults: toReplayTriggerResults(results), + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, [ + ...toSkippedTriggers(skippedTriggers, context), + ...toErroredSkippedTriggers(results), + ]), + skillExecutions: toSkillExecutions(results), + recalledMemories: memoryRecall?.memories.map(({ id, version }) => ({ id, version })), + memoryRecallId: memoryRecall?.clientRecallId, + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)(reports, context, findingObservations, findingsOptions); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + // Update core check with overall summary + if (coreCheckId) { + const checkOptions = checkOptionsForPullRequest(context, postChecks); + if (checkOptions) { + try { + const summaryData = (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .buildCoreSummaryData */ .YX)(results, reports); + const coreConclusion = (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .determineCoreConclusion */ .ar)(shouldFailAction || triggerErrors.length > 0, outputs.findingsCount); + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .updateCoreCheck */ .R2)(octokit, coreCheckId, summaryData, coreConclusion, checkOptions); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'update_core_check' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to update core check: ${error}`); + } + } + } + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)(reports, context, findingObservations, findingsOptions)); + if (shouldFailAction) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(failureReasons.join('; ')); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Analysis complete: ${outputs.findingsCount} total findings`); +} +/** Complete the core check for a PR run that intentionally skipped analysis. */ +async function completeSkippedCoreCheck(octokit, context, coreCheckId, skipped, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!coreCheckId || !options) { + return; + } + try { + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .updateCoreCheck */ .R2)(octokit, coreCheckId, { + ...(0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .buildCoreSummaryData */ .YX)([], []), + title: skipped.title, + message: skipped.message, + }, 'neutral', options); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { tags: { operation: 'update_core_check_skipped' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to update core check: ${error}`); + } +} +/** Complete per-skill checks for configured PR triggers that did not run. */ +async function completeSkippedSkillChecks(octokit, context, skippedTriggers, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!options || skippedTriggers.length === 0) { + return; + } + for (const trigger of skippedTriggers) { + try { + const skillCheck = await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createSkillCheck */ .uP)(octokit, trigger.skill, options); + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .updateSkillCheck */ .Zv)(octokit, skillCheck.checkRunId, { + skill: trigger.skill, + summary: 'Trigger did not run for this event.', + findings: [], + }, { + ...options, + failOn: trigger.failOn, + reportOn: trigger.reportOn, + minConfidence: trigger.minConfidence ?? 'medium', + failCheck: trigger.failCheck, + conclusion: 'neutral', + title: 'Skipped', + }); + } + catch (error) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(error, { + tags: { + operation: 'update_skipped_skill_check', + trigger_name: trigger.name, + skill_name: trigger.skill, + }, + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to update skipped skill check for ${trigger.skill}: ${error}`); + } + } +} +/** + * Fail per-skill checks when workflow setup fails before triggers are dispatched. + */ +async function failUndispatchedSkillChecks(octokit, context, triggers, error, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!options || triggers.length === 0) { + return; + } + for (const trigger of triggers) { + try { + const skillCheck = await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createSkillCheck */ .uP)(octokit, trigger.skill, options); + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .failSkillCheck */ .OZ)(octokit, skillCheck.checkRunId, error, options); + } + catch (checkError) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(checkError, { + tags: { + operation: 'fail_undispatched_skill_check', + trigger_name: trigger.name, + skill_name: trigger.skill, + }, + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to mark skill check as failed for ${trigger.skill}: ${checkError}`); + } + } +} +/** + * Mark the core check failed when an early PR workflow phase fails after check creation. + */ +async function failCoreCheck(octokit, context, coreCheckId, error, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!coreCheckId || !options) { + return; + } + const errorMessage = error instanceof Error ? error.message : String(error); + try { + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .updateCoreCheck */ .R2)(octokit, coreCheckId, { + ...(0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .buildCoreSummaryData */ .YX)([], []), + title: 'Warden failed', + message: `Error: ${errorMessage}`, + }, 'failure', options); + } + catch (checkError) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(checkError, { tags: { operation: 'fail_core_check' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to mark core check as failed: ${checkError}`); + } +} +async function runOrFailCore(octokit, context, coreCheckId, postChecks, operation) { + try { + return await operation(); + } + catch (error) { + await failCoreCheck(octokit, context, coreCheckId, error, postChecks); + throw error; + } +} +function resolveFindingsFilePath(inputPath, repoPath) { + if (!inputPath) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)('findings-file is required when mode is report'); + } + return (0,node_path__WEBPACK_IMPORTED_MODULE_1__.isAbsolute)(inputPath) ? inputPath : (0,node_path__WEBPACK_IMPORTED_MODULE_1__.join)(repoPath, inputPath); +} +/** + * Reads the analyze-mode findings artifact that report mode replays. + */ +function readFindingsFile(inputPath, repoPath) { + const filePath = resolveFindingsFilePath(inputPath, repoPath); + try { + return _reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .FindingsOutputSchema */ .DF.parse(JSON.parse((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(filePath, 'utf-8'))); + } + catch (error) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Failed to read findings file ${filePath}: ${error}`); + } +} +/** + * Ensures a replay artifact was produced for the same repository, event, PR, + * and head SHA before report mode performs GitHub writes. + */ +function validateFindingsMatchContext(output, context) { + if (output.repository.fullName !== context.repository.fullName) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Findings file is for ${output.repository.fullName}, but this workflow is for ${context.repository.fullName}`); + } + if (output.event !== context.eventType) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Findings file event ${output.event} does not match ${context.eventType}`); + } + if (!context.pullRequest) { + return; + } + if (!output.pullRequest) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)('Findings file is missing pull request metadata'); + } + if (output.pullRequest.number !== context.pullRequest.number) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Findings file is for PR #${output.pullRequest.number}, but this workflow is for PR #${context.pullRequest.number}`); + } + if (output.pullRequest.headSha !== context.pullRequest.headSha) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Findings file head SHA ${output.pullRequest.headSha} does not match current head SHA ${context.pullRequest.headSha}`); + } +} +function deserializeTriggerError(error, fallback) { + const deserialized = new Error(error?.message ?? fallback); + if (error?.name) { + deserialized.name = error.name; + } + return deserialized; +} +function resultKey(triggerName, skillName) { + return `${triggerName}\0${skillName}`; +} +function replayKey(result) { + return result.triggerId ?? resultKey(result.triggerName, result.skillName); +} +function triggerReplayKey(trigger) { + return trigger.id; +} +function describeResultKey(result) { + return `${result.triggerName} (${result.skillName})`; +} +function toReplayTriggerResults(results) { + return results.map((result) => ({ + triggerId: result.triggerId, + triggerName: result.triggerName, + skillName: result.skillName, + report: result.report, + error: result.error, + findingProcessingEvents: result.findingProcessingEvents, + auxiliaryModel: result.auxiliaryModel, + synthesisModel: result.synthesisModel, + })); +} +/** + * Rebuild report-mode trigger results by joining artifact rows to the current + * configured trigger name and skill identity. + */ +function buildReportModeResults(output, matchedTriggers, inputs) { + if (!output.triggerResults) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)('Findings file was not produced by mode: analyze; missing triggerResults'); + } + const outputResults = new Map(); + for (const result of output.triggerResults) { + const key = replayKey(result); + const existing = outputResults.get(key); + if (existing) { + existing.push(result); + } + else { + outputResults.set(key, [result]); + } + } + const duplicateConfiguredResults = new Map(); + for (const trigger of matchedTriggers) { + const key = triggerReplayKey(trigger); + const existing = duplicateConfiguredResults.get(key); + if (existing) { + existing.push(trigger); + } + else { + duplicateConfiguredResults.set(key, [trigger]); + } + } + const ambiguousKeys = [ + ...new Set([ + ...[...outputResults.entries()] + .filter(([, results]) => results.length > 1) + .map(([key]) => key), + ...[...duplicateConfiguredResults.entries()] + .filter(([, triggers]) => triggers.length > 1) + .map(([key]) => key), + ]), + ]; + if (ambiguousKeys.length > 0) { + const triggerList = ambiguousKeys + .map((key) => { + const result = outputResults.get(key)?.[0]; + const trigger = duplicateConfiguredResults.get(key)?.[0]; + return result + ? describeResultKey(result) + : `${trigger?.name ?? 'unknown'} (${trigger?.skill ?? 'unknown'})`; + }) + .join(', '); + throw new Error(`Findings file contains ambiguous duplicate trigger result(s): ${triggerList}`); + } + const results = matchedTriggers.map((trigger) => { + const failOn = trigger.failOn ?? inputs.failOn; + const reportOn = trigger.reportOn ?? inputs.reportOn; + const minConfidence = trigger.minConfidence ?? 'medium'; + const requestChanges = trigger.requestChanges ?? inputs.requestChanges; + const failCheck = trigger.failCheck ?? inputs.failCheck; + const maxFindings = trigger.maxFindings ?? inputs.maxFindings; + const baseResult = { + triggerId: trigger.id, + skillExecutionId: trigger.skillExecutionId, + triggerName: trigger.name, + skillName: trigger.skill, + failOn, + reportOn, + minConfidence, + reportOnSuccess: trigger.reportOnSuccess, + requestChanges, + failCheck, + maxFindings, + }; + let outputResult = outputResults.get(triggerReplayKey(trigger))?.shift(); + if (!outputResult) { + // Only a legacy artifact (predating triggerId) reaches this fallback. + // If 2+ current triggers share this name+skill, the fallback can't + // tell them apart — fail loudly instead of silently binding a report + // to the wrong trigger's policy (failOn/reportOn/etc). + const fallbackKey = resultKey(trigger.name, trigger.skill); + const sameFallbackKeyTriggers = matchedTriggers.filter((t) => resultKey(t.name, t.skill) === fallbackKey); + if (sameFallbackKeyTriggers.length > 1) { + throw new Error(`Findings file has no triggerId-matched result for trigger ${trigger.name} (${trigger.skill}), ` + + `and the legacy name/skill fallback is ambiguous: multiple current triggers share this name and skill`); + } + outputResult = outputResults.get(fallbackKey)?.shift(); + } + if (!outputResult) { + return { + ...baseResult, + error: new Error(`Findings file has no result for trigger ${trigger.name} (${trigger.skill})`), + }; + } + if (outputResult.status === 'error' || !outputResult.report) { + return { + ...baseResult, + error: deserializeTriggerError(outputResult.error, `Trigger ${trigger.name} (${trigger.skill}) failed during analysis`), + }; + } + return { + ...baseResult, + report: outputResult.report, + findingProcessingEvents: outputResult.findingProcessingEvents, + auxiliaryModel: outputResult.auxiliaryModel, + synthesisModel: outputResult.synthesisModel, + }; + }); + const unreportedResults = [...outputResults.values()].flat(); + if (unreportedResults.length > 0) { + const triggerList = unreportedResults + .map(describeResultKey) + .join(', '); + throw new Error(`Findings file contains ${unreportedResults.length} result(s) that do not match current config: ${triggerList}`); + } + return results; +} +function withRenderedReviewResult(result) { + if (!result.report) { + return result; + } + return { + ...result, + renderResult: result.reportOn !== 'off' + ? (0,_output_renderer_js__WEBPACK_IMPORTED_MODULE_22__/* .renderSkillReport */ .K)(result.report, { + maxFindings: result.maxFindings, + reportOn: result.reportOn, + minConfidence: result.minConfidence, + failOn: result.failOn, + requestChanges: result.requestChanges, + checkRunUrl: result.checkRunUrl, + totalFindings: result.report.findings.length, + }) + : undefined, + }; +} +/** + * Create report-mode skill checks directly as completed check runs. + */ +async function createCompletedSkillChecksForReport(octokit, context, results, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!options) { + return results.map(withRenderedReviewResult); + } + const updatedResults = []; + for (const result of results) { + if (result.report) { + const check = await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createCompletedSkillCheck */ .$R)(octokit, result.report, { + ...options, + checkName: result.skillName, + failOn: result.failOn, + reportOn: result.reportOn, + minConfidence: result.minConfidence, + failCheck: result.failCheck, + }); + updatedResults.push(withRenderedReviewResult({ ...result, checkRunUrl: check.url, checkRunId: check.checkRunId })); + continue; + } + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createFailedSkillCheck */ .xB)(octokit, result.skillName, result.error ?? new Error('Trigger did not produce a report'), options); + updatedResults.push(result); + } + return updatedResults; +} +/** + * Create neutral completed checks for triggers report mode intentionally skipped. + */ +async function createCompletedSkippedSkillChecks(octokit, context, skippedTriggers, postChecks) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!options || skippedTriggers.length === 0) { + return; + } + for (const trigger of skippedTriggers) { + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createCompletedSkillCheck */ .$R)(octokit, { + skill: trigger.skill, + summary: 'Trigger did not run for this event.', + findings: [], + }, { + ...options, + failOn: trigger.failOn, + reportOn: trigger.reportOn, + minConfidence: trigger.minConfidence ?? 'medium', + failCheck: trigger.failCheck, + conclusion: 'neutral', + title: 'Skipped', + }); + } +} +/** + * Create the report-mode core check directly as a completed check run. + */ +async function createCompletedCoreCheckForReport(octokit, context, results, reports, shouldFailAction, outputs, postChecks, overrides = {}, conclusion) { + const options = checkOptionsForPullRequest(context, postChecks); + if (!options) { + return; + } + await (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .createCompletedCoreCheck */ .RR)(octokit, { + ...(0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .buildCoreSummaryData */ .YX)(results, reports), + ...overrides, + }, conclusion ?? (0,_checks_manager_js__WEBPACK_IMPORTED_MODULE_20__/* .determineCoreConclusion */ .ar)(shouldFailAction, outputs.findingsCount), options); +} +/** + * Create the report-mode core failure check directly as a completed check run. + */ +async function createFailedCoreCheckForReport(octokit, context, error, postChecks) { + const errorMessage = error instanceof Error ? error.message : String(error); + try { + await createCompletedCoreCheckForReport(octokit, context, [], [], true, { findingsCount: 0 }, postChecks, { + title: 'Warden failed', + message: `Error: ${errorMessage}`, + }, 'failure'); + } + catch (checkError) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.captureException */ .sQ.captureException(checkError, { tags: { operation: 'create_failed_core_check_report' } }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to create failed core check: ${checkError}`); + } +} +/** + * Finalize report mode after replay: write outputs, handle review dismissal, + * create direct completed checks, and fail the action when policy requires it. + */ +async function finalizeReportWorkflow(octokit, context, previousReviewInfo, results, reports, findingObservations, shouldFailAction, failureReasons, canResolveStale, gate, triggerErrors, options) { + await dismissPreviousReviewIfResolved(octokit, context, previousReviewInfo, results, canResolveStale, gate, { failOnWriteError: options.failOnWriteError, carriedFindingsOpen: options.carriedFindingsOpen }); + const outputs = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .computeWorkflowOutputs */ .dV)(reports); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setWorkflowOutputs */ .wZ)(outputs); + const findingsOptions = { + triggerResults: toReplayTriggerResults(results), + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(options.inputs, [ + ...toSkippedTriggers(options.skippedTriggers ?? [], context), + ...toErroredSkippedTriggers(results), + ]), + skillExecutions: toSkillExecutions(results), + recalledMemories: options.recalledMemories, + memoryRecallId: options.memoryRecallId, + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ + allTriggers: options.resolvedTriggers, + matchedTriggers: options.matchedTriggers, + }), + }; + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)(reports, context, findingObservations, findingsOptions); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + await createCompletedCoreCheckForReport(octokit, context, results, reports, shouldFailAction || triggerErrors.length > 0, outputs, options.postChecks); + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(options.service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)(reports, context, findingObservations, findingsOptions)); + if (shouldFailAction) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(failureReasons.join('; ')); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Analysis complete: ${outputs.findingsCount} total findings`); +} +/** + * Clean up orphaned Warden comments when no triggers matched. + * + * Runs fix evaluation and stale resolution on existing comments so that + * comments from earlier pushes get resolved even when the current push + * only touches files outside all skills' paths filters. + * Skips cleanup when this run is no longer analyzing the current PR head. + */ +async function cleanupOrphanedComments(octokit, context, inputs, auxiliaryOptions, options = {}) { + if (!context.pullRequest) { + return []; + } + const gate = new _review_review_feedback_gate_js__WEBPACK_IMPORTED_MODULE_17__/* .ReviewFeedbackGate */ .d(octokit, context); + if (!await gate.canWrite()) { + return []; + } + let existingComments; + try { + existingComments = await (0,_output_dedup_js__WEBPACK_IMPORTED_MODULE_6__/* .fetchExistingComments */ .kX)(octokit, context.repository.owner, context.repository.name, context.pullRequest.number); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to fetch existing comments for cleanup: ${error}`); + return []; + } + const wardenComments = existingComments.filter((c) => c.isWarden); + if (wardenComments.length === 0) { + return []; + } + if ((auxiliaryOptions.runtime ?? 'pi') === 'claude') { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .ensureClaudeAuth */ .$m)(inputs); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`No triggers matched, but found ${wardenComments.length} existing Warden comments. Running cleanup.`); + const { allResolved, autoResolvedByFixEvaluation, autoResolvedByStaleCheck, findingObservations } = await evaluateFixesAndResolveStale(octokit, context, existingComments, [], new Set(), true, inputs.anthropicApiKey, auxiliaryOptions, gate, { + failOnWriteError: options.failOnWriteError, + }); + const activeSpan = _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.getActiveSpan */ .sQ.getActiveSpan(); + activeSpan?.setAttribute('warden.feedback.auto_resolve.fix_eval_count', autoResolvedByFixEvaluation); + activeSpan?.setAttribute('warden.feedback.auto_resolve.stale_count', autoResolvedByStaleCheck); + // Dismiss CHANGES_REQUESTED only if every unresolved comment was resolved + if (allResolved) { + const previousReviewInfo = await fetchPreviousReviewInfo(octokit, context); + if (previousReviewInfo?.state === 'CHANGES_REQUESTED') { + if (!await gate.canWrite()) { + return findingObservations; + } + try { + await octokit.pulls.dismissReview({ + owner: context.repository.owner, + repo: context.repository.name, + pull_number: context.pullRequest.number, + review_id: previousReviewInfo.reviewId, + message: 'All previously reported issues have been resolved.', + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Dismissed previous CHANGES_REQUESTED review'); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to dismiss previous review: ${error}`); + if (options.failOnWriteError) { + throw new ReportWriteError('Failed to dismiss previous review', error); + } + } + } + } + return findingObservations; +} +/** + * Run the analysis phase without GitHub reporting writes. + * It executes matched triggers and writes the replay artifact for report mode. + */ +async function runAnalyzeMode(octokit, inputs, initResult, span) { + const { context, runnerConcurrency, resolvedTriggers, matchedTriggers, skippedTriggers, skipCoreCheck, memoryRecall, } = initResult; + if (skipCoreCheck || matchedTriggers.length === 0) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('findings-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('high-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('summary', skipCoreCheck?.title ?? 'No triggers matched'); + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, [], { + triggerResults: [], + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, toSkippedTriggers(skippedTriggers, context)), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Failed to write findings output: ${error}`); + } + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Analysis complete: 0 total findings'); + return; + } + const results = await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ + op: 'workflow.execute', + name: 'execute triggers', + attributes: { 'warden.trigger.count': matchedTriggers.length }, + }, () => executeAllTriggers(matchedTriggers, context, runnerConcurrency, inputs, { + memoryRecall, + incremental: incrementalSourceFor(octokit, context, matchedTriggers), + onTriggerComplete: (completedSoFar) => { + const reportsSoFar = completedSoFar.flatMap((r) => (r.report ? [r.report] : [])); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutputLive */ .ZU)(reportsSoFar, context, [], { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, [ + ...toSkippedTriggers(skippedTriggers, context), + ...toErroredSkippedTriggers(completedSoFar), + ]), + skillExecutions: toSkillExecutions(completedSoFar), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }); + }, + })); + const reports = results.flatMap((result) => (result.report ? [result.report] : [])); + const outputs = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .computeWorkflowOutputs */ .dV)(reports); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setWorkflowOutputs */ .wZ)(outputs); + span.setAttribute('warden.finding.count', reports.flatMap((r) => r.findings).length); + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)(reports, context, [], { + triggerResults: toReplayTriggerResults(results), + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, [ + ...toSkippedTriggers(skippedTriggers, context), + ...toErroredSkippedTriggers(results), + ]), + skillExecutions: toSkillExecutions(results), + recalledMemories: memoryRecall?.memories.map(({ id, version }) => ({ id, version })), + memoryRecallId: memoryRecall?.clientRecallId, + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setFailed */ .C1)(`Failed to write findings output: ${error}`); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .handleTriggerErrors */ .a3)((0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .collectTriggerErrors */ .sl)(results), matchedTriggers.length, { failAll: false }); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Analysis complete: ${outputs.findingsCount} total findings`); +} +/** + * Run the reporting phase without rerunning skills. + * It replays analyze output against the current PR config and owns GitHub writes. + */ +async function runReportMode(octokit, inputs, initResult, repoPath, span) { + const { context, service, auxiliaryOptions, resolvedTriggers, matchedTriggers, skippedTriggers, skipCoreCheck, postChecks, } = initResult; + const findingsOutput = readFindingsFile(inputs.findingsFile, repoPath); + validateFindingsMatchContext(findingsOutput, context); + const replayMemoryOptions = { + recalledMemories: findingsOutput.recalledMemories, + memoryRecallId: findingsOutput.memoryRecallId, + }; + let results = []; + let previousReviewInfo = null; + let reviewPhase; + let triggerErrors; + let canResolveStale; + try { + results = buildReportModeResults(findingsOutput, matchedTriggers, inputs); + await createCompletedSkippedSkillChecks(octokit, context, skippedTriggers, postChecks); + if (skipCoreCheck) { + const outputs = { findingsCount: 0, highCount: 0, summary: skipCoreCheck.title }; + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setWorkflowOutputs */ .wZ)(outputs); + const findingsOptions = { + triggerResults: [], + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, toSkippedTriggers(skippedTriggers, context)), + ...replayMemoryOptions, + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, [], findingsOptions); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + await createCompletedCoreCheckForReport(octokit, context, [], [], false, outputs, postChecks, { + title: skipCoreCheck.title, + message: skipCoreCheck.message, + }, 'neutral'); + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)([], context, [], findingsOptions)); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Analysis complete: 0 total findings'); + return; + } + if (matchedTriggers.length === 0) { + const cleanupFindingObservations = await cleanupOrphanedComments(octokit, context, inputs, auxiliaryOptions, { failOnWriteError: true }); + const outputs = { findingsCount: 0, highCount: 0, summary: 'No triggers matched' }; + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setWorkflowOutputs */ .wZ)(outputs); + const findingsOptions = { + triggerResults: [], + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, toSkippedTriggers(skippedTriggers, context)), + ...replayMemoryOptions, + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, cleanupFindingObservations, findingsOptions); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Findings written to ${findingsPath}`); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + await createCompletedCoreCheckForReport(octokit, context, [], [], false, outputs, postChecks, { + title: 'No triggers matched', + message: 'No triggers matched for this event.', + }, 'neutral'); + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)([], context, cleanupFindingObservations, findingsOptions)); + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)('Analysis complete: 0 total findings'); + return; + } + results = await createCompletedSkillChecksForReport(octokit, context, results, postChecks); + previousReviewInfo = await fetchPreviousReviewInfo(octokit, context); + if (previousReviewInfo) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .logAction */ .d5)(`Previous Warden review state: ${previousReviewInfo.state}`); + } + const gate = new _review_review_feedback_gate_js__WEBPACK_IMPORTED_MODULE_17__/* .ReviewFeedbackGate */ .d(octokit, context); + reviewPhase = await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.review', name: 'post reviews' }, () => postReviewsAndTrackFailures(octokit, context, results, inputs, auxiliaryOptions, gate, { + failOnPostError: true, + })); + triggerErrors = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .collectTriggerErrors */ .sl)(results); + canResolveStale = (0,_review_coordination_js__WEBPACK_IMPORTED_MODULE_27__/* .shouldResolveStaleComments */ .t)(results); + const allFindings = reviewPhase.reports.flatMap((r) => r.findings); + const carriedRanges = (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .collectCarriedRanges */ .Z5)(reviewPhase.reports); + span.setAttribute('warden.finding.count', allFindings.length); + await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.resolve', name: 'resolve stale comments' }, async (resolveSpan) => { + const resolutionResult = await evaluateFixesAndResolveStale(octokit, context, reviewPhase.fetchedComments, allFindings, reviewPhase.activeWardenCommentIds, canResolveStale, inputs.anthropicApiKey, auxiliaryOptions, gate, { + failOnWriteError: true, + partialScopeSkills: pushScopedSkills(reviewPhase.reports), + carriedRanges, + }); + resolveSpan.setAttribute('warden.feedback.auto_resolve.fix_eval_count', resolutionResult.autoResolvedByFixEvaluation); + resolveSpan.setAttribute('warden.feedback.auto_resolve.stale_count', resolutionResult.autoResolvedByStaleCheck); + reviewPhase.findingObservations.push(...resolutionResult.findingObservations); + }); + await finalizeReportWorkflow(octokit, context, previousReviewInfo, results, reviewPhase.reports, reviewPhase.findingObservations, reviewPhase.shouldFailAction, reviewPhase.failureReasons, canResolveStale, gate, triggerErrors, { + failOnWriteError: true, + skippedTriggers, + inputs, + service, + ...replayMemoryOptions, + postChecks, + matchedTriggers, + resolvedTriggers, + carriedFindingsOpen: (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .hasOpenCarriedComment */ .SW)(reviewPhase.commentsFetched ? reviewPhase.fetchedComments : undefined, carriedRanges), + }); + } + catch (error) { + if (error instanceof _base_js__WEBPACK_IMPORTED_MODULE_21__/* .ActionFailedError */ .Ah) { + throw error; + } + await createFailedCoreCheckForReport(octokit, context, error, postChecks); + throw error; + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .handleTriggerErrors */ .a3)(triggerErrors, matchedTriggers.length); +} +// ----------------------------------------------------------------------------- +// Main PR Workflow +// ----------------------------------------------------------------------------- +/** + * Dispatch PR and push events through legacy run mode or split analyze/report mode. + */ +async function runPRWorkflow(octokit, inputs, eventName, eventPath, repoPath) { + const reportInputPath = inputs.mode === 'report' && inputs.findingsFile + ? resolveFindingsFilePath(inputs.findingsFile, repoPath) + : undefined; + const preservePayload = reportInputPath !== undefined + && (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(reportInputPath) === (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)((0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .getFindingsOutputPath */ .Rr)(repoPath)); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .clearStaleFindingsOutput */ .mG)(repoPath, { preservePayload }); + return _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.run', name: 'review pull_request' }, async (span) => { + const initResult = await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.init', name: 'initialize workflow' }, () => initializeWorkflow(octokit, inputs, eventName, eventPath, repoPath)); + const { context, service, runnerConcurrency, auxiliaryOptions, resolvedTriggers, matchedTriggers, skippedTriggers, skipCoreCheck, memoryRecall, postChecks, } = initResult; + span.setAttribute('warden.trigger.count', matchedTriggers.length); + // Set Sentry context after building event context + if (context.pullRequest) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.setUser */ .sQ.setUser({ username: context.pullRequest.author }); + } + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.setContext */ .sQ.setContext('repository', { + owner: context.repository.owner, + name: context.repository.name, + }); + if (context.pullRequest) { + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.setContext */ .sQ.setContext('pull_request', { + number: context.pullRequest.number, + baseBranch: context.pullRequest.baseBranch, + headBranch: context.pullRequest.headBranch, + }); + } + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .emitRunMetric */ .LW)(); + const traceId = span.spanContext().traceId; + _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .logger */ .vF.info('Workflow initialized', { + 'warden.trigger.count': matchedTriggers.length, + 'trace.id': traceId, + }); + if (inputs.mode === 'analyze') { + return runAnalyzeMode(octokit, inputs, initResult, span); + } + if (inputs.mode === 'report') { + return runReportMode(octokit, inputs, initResult, repoPath, span); + } + const { coreCheckId, previousReviewInfo } = await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.setup', name: 'setup github state' }, () => setupGitHubState(octokit, context, postChecks)); + await completeSkippedSkillChecks(octokit, context, skippedTriggers, postChecks); + if (skipCoreCheck) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('findings-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('high-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('summary', skipCoreCheck.title); + const findingsOptions = { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, toSkippedTriggers(skippedTriggers, context)), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, [], findingsOptions); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + await completeSkippedCoreCheck(octokit, context, coreCheckId, skipCoreCheck, postChecks); + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)([], context, [], findingsOptions)); + return; + } + if (matchedTriggers.length === 0) { + await runOrFailCore(octokit, context, coreCheckId, postChecks, async () => { + const cleanupFindingObservations = await cleanupOrphanedComments(octokit, context, inputs, auxiliaryOptions); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('findings-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('high-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .setOutput */ .uH)('summary', 'No triggers matched'); + const findingsOptions = { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, toSkippedTriggers(skippedTriggers, context)), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, cleanupFindingObservations, findingsOptions); + } + catch (error) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${error}`); + } + await completeSkippedCoreCheck(octokit, context, coreCheckId, { + title: 'No triggers matched', + message: 'No triggers matched for this event.', + }, postChecks); + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)([], context, cleanupFindingObservations, findingsOptions)); + }); + return; + } + let results; + try { + results = await _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ + op: 'workflow.execute', + name: 'execute triggers', + attributes: { 'warden.trigger.count': matchedTriggers.length }, + }, () => executeAllTriggers(matchedTriggers, context, runnerConcurrency, inputs, { + checks: createTriggerCheckReporter(octokit, context, postChecks), + memoryRecall, + incremental: incrementalSourceFor(octokit, context, matchedTriggers), + onTriggerComplete: (completedSoFar) => { + const reportsSoFar = completedSoFar.flatMap((r) => (r.report ? [r.report] : [])); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutputLive */ .ZU)(reportsSoFar, context, [], { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, [ + ...toSkippedTriggers(skippedTriggers, context), + ...toErroredSkippedTriggers(completedSoFar), + ]), + skillExecutions: toSkillExecutions(completedSoFar), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }); + }, + })); + } + catch (error) { + await failUndispatchedSkillChecks(octokit, context, matchedTriggers, error, postChecks); + await failCoreCheck(octokit, context, coreCheckId, error, postChecks); + const triggerResults = matchedTriggers.map((trigger) => ({ + triggerId: trigger.id, + triggerName: trigger.name, + skillName: trigger.skill, + error, + })); + const findingsOptions = { + triggerResults, + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildBaseOutputOptions */ .vM)(inputs, [ + ...toSkippedTriggers(skippedTriggers, context), + ...matchedTriggers.map((trigger) => ({ + skillName: trigger.skill, + triggerId: trigger.id, + triggerName: trigger.name, + reason: 'error', + })), + ]), + configuredSkills: (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildConfiguredSkillsList */ .BA)({ allTriggers: resolvedTriggers, matchedTriggers }), + }; + try { + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .writeFindingsOutput */ .JR)([], context, [], findingsOptions); + } + catch (writeError) { + (0,_cli_output_tty_js__WEBPACK_IMPORTED_MODULE_24__/* .warnAction */ .T6)(`Failed to write findings output: ${writeError}`); + } + await (0,_service_js__WEBPACK_IMPORTED_MODULE_13__/* .publishActionEarlyFailureFailOpen */ .P$)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_23__/* .buildFindingsOutput */ .Cs)([], context, [], findingsOptions)); + throw error; + } + const gate = new _review_review_feedback_gate_js__WEBPACK_IMPORTED_MODULE_17__/* .ReviewFeedbackGate */ .d(octokit, context); + const reviewPhase = await runOrFailCore(octokit, context, coreCheckId, postChecks, () => _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.review', name: 'post reviews' }, () => postReviewsAndTrackFailures(octokit, context, results, inputs, auxiliaryOptions, gate))); + const triggerErrors = (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .collectTriggerErrors */ .sl)(results); + const canResolveStale = (0,_review_coordination_js__WEBPACK_IMPORTED_MODULE_27__/* .shouldResolveStaleComments */ .t)(results); + const allFindings = reviewPhase.reports.flatMap((r) => r.findings); + const carriedRanges = (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .collectCarriedRanges */ .Z5)(reviewPhase.reports); + span.setAttribute('warden.finding.count', allFindings.length); + await runOrFailCore(octokit, context, coreCheckId, postChecks, () => _sentry_js__WEBPACK_IMPORTED_MODULE_2__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.resolve', name: 'resolve stale comments' }, async (resolveSpan) => { + const resolutionResult = await evaluateFixesAndResolveStale(octokit, context, reviewPhase.fetchedComments, allFindings, reviewPhase.activeWardenCommentIds, canResolveStale, inputs.anthropicApiKey, auxiliaryOptions, gate, { partialScopeSkills: pushScopedSkills(reviewPhase.reports), carriedRanges }); + resolveSpan.setAttribute('warden.feedback.auto_resolve.fix_eval_count', resolutionResult.autoResolvedByFixEvaluation); + resolveSpan.setAttribute('warden.feedback.auto_resolve.stale_count', resolutionResult.autoResolvedByStaleCheck); + reviewPhase.findingObservations.push(...resolutionResult.findingObservations); + })); + await finalizeWorkflow(octokit, context, previousReviewInfo, coreCheckId, results, reviewPhase.reports, reviewPhase.findingObservations, reviewPhase.shouldFailAction, reviewPhase.failureReasons, canResolveStale, gate, triggerErrors, skippedTriggers, inputs, service, memoryRecall, postChecks, matchedTriggers, resolvedTriggers, (0,_incremental_js__WEBPACK_IMPORTED_MODULE_15__/* .hasOpenCarriedComment */ .SW)(reviewPhase.commentsFetched ? reviewPhase.fetchedComments : undefined, carriedRanges)); + (0,_base_js__WEBPACK_IMPORTED_MODULE_21__/* .handleTriggerErrors */ .a3)(triggerErrors, matchedTriggers.length); + }); +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 30517: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ y: () => (/* binding */ runScheduleWorkflow) +/* harmony export */ }); +/* harmony import */ var _config_loader_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77695); +/* harmony import */ var _event_schedule_context_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65997); +/* harmony import */ var _sdk_runner_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(45452); +/* harmony import */ var _sdk_runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(85286); +/* harmony import */ var _sdk_offline_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(8695); +/* harmony import */ var _output_github_issues_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(67034); +/* harmony import */ var _triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(49431); +/* harmony import */ var _skills_loader_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(34691); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(78481); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(30340); +/* harmony import */ var _reporting_output_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(4169); +/* harmony import */ var _service_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(19197); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(98514); +/* harmony import */ var _error_reporting_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(29547); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_sdk_runner_js__WEBPACK_IMPORTED_MODULE_2__]); +_sdk_runner_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; +/** + * Schedule Workflow + * + * Handles schedule and workflow_dispatch events. + */ + + + + + + + + + + + + + + +async function emitEmptyScheduleRun(inputs, repoPath, service) { + const fullName = process.env['GITHUB_REPOSITORY'] ?? ''; + const [owner = '', name = ''] = fullName.split('/'); + const context = { + eventType: 'schedule', + action: 'scheduled', + repository: { owner, name, fullName, defaultBranch: '' }, + repoPath, + }; + const findingsOptions = (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_9__/* .buildBaseOutputOptions */ .vM)(inputs, []); + try { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .writeFindingsOutput */ .JR)([], context, [], findingsOptions); + } + catch (error) { + console.error(`::warning::Failed to write findings output: ${error}`); + } + await (0,_service_js__WEBPACK_IMPORTED_MODULE_10__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_9__/* .buildFindingsOutput */ .Cs)([], context, [], findingsOptions)); +} +async function runScheduleWorkflow(octokit, inputs, repoPath) { + return _sentry_js__WEBPACK_IMPORTED_MODULE_8__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'workflow.run', name: 'review schedule' }, (span) => runScheduleWorkflowInner(octokit, inputs, repoPath, span)); +} +async function runScheduleWorkflowInner(octokit, inputs, repoPath, workflowSpan) { + const githubRepository = process.env['GITHUB_REPOSITORY']; + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_8__/* .setRepositoryScope */ .vx)(githubRepository); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .clearStaleFindingsOutput */ .mG)(repoPath); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroup */ .QT)('Loading configuration'); + if (inputs.baseConfigPath) { + console.log(`Base config path: ${inputs.baseConfigPath}`); + } + if (inputs.baseSkillRoot) { + console.log(`Base skill root: ${inputs.baseSkillRoot}`); + } + console.log(`Repo config path: ${inputs.configPath}`); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroupEnd */ .TN)(); + let scheduleTriggers; + let runnerConcurrency; + let skillRootsByName; + let service = (0,_service_js__WEBPACK_IMPORTED_MODULE_10__/* .resolveActionServiceOptions */ .iZ)(inputs); + try { + const layered = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_0__/* .loadLayeredWardenConfig */ .M3)(repoPath, { + baseConfigPath: inputs.baseConfigPath, + configPath: inputs.configPath, + onWarning: (message) => console.log(`::warning::${message}`), + }); + (0,_sdk_offline_js__WEBPACK_IMPORTED_MODULE_13__/* .configureWardenOffline */ .zV)(layered.baseConfig?.defaults?.offline === true + || layered.repoConfig?.defaults?.offline === true + || layered.config.defaults?.offline === true); + runnerConcurrency = + layered.baseConfig?.runner?.concurrency ?? + layered.repoConfig?.runner?.concurrency ?? + layered.config.runner?.concurrency; + skillRootsByName = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_0__/* .buildSkillRootsByName */ .hd)(repoPath, layered, inputs.baseSkillRoot); + service = (0,_service_js__WEBPACK_IMPORTED_MODULE_10__/* .resolveActionServiceOptions */ .iZ)(inputs, layered.config.service); + scheduleTriggers = (0,_config_loader_js__WEBPACK_IMPORTED_MODULE_0__/* .resolveLayeredSkillConfigs */ .Ln)(layered, undefined, skillRootsByName) + .filter((t) => t.type === 'schedule'); + } + catch (error) { + if (error instanceof _config_loader_js__WEBPACK_IMPORTED_MODULE_0__/* .ConfigLoadError */ .tx && + error.message.includes('not found') && + !inputs.baseConfigPath) { + console.log('::warning::No warden.toml found. Skipping analysis.'); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('findings-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('high-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('summary', 'No warden.toml found'); + workflowSpan.setAttribute('warden.trigger.count', 0); + workflowSpan.setAttribute('warden.finding.count', 0); + await emitEmptyScheduleRun(inputs, repoPath, service); + return; + } + throw error; + } + workflowSpan.setAttribute('warden.trigger.count', scheduleTriggers.length); + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_8__/* .emitRunMetric */ .LW)(); + const traceId = workflowSpan.spanContext?.().traceId; + _sentry_js__WEBPACK_IMPORTED_MODULE_8__/* .logger */ .vF.info('Workflow initialized', { + 'warden.trigger.count': scheduleTriggers.length, + ...(traceId ? { 'trace.id': traceId } : {}), + }); + if (scheduleTriggers.length === 0) { + console.log('No schedule triggers configured'); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('findings-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('high-count', 0); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('summary', 'No schedule triggers configured'); + workflowSpan.setAttribute('warden.finding.count', 0); + await emitEmptyScheduleRun(inputs, repoPath, service); + return; + } + // Get repo info from environment + if (!githubRepository) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setFailed */ .C1)('GITHUB_REPOSITORY environment variable not set'); + } + const [owner, repo] = githubRepository.split('/'); + if (!owner || !repo) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setFailed */ .C1)('Invalid GITHUB_REPOSITORY format'); + } + const headSha = process.env['GITHUB_SHA'] ?? ''; + if (!headSha) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setFailed */ .C1)('GITHUB_SHA environment variable not set'); + } + const defaultBranch = await (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .getDefaultBranchFromAPI */ .YL)(octokit, owner, repo); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroup */ .QT)('Processing schedule triggers'); + for (const trigger of scheduleTriggers) { + console.log(`- ${trigger.name}: ${trigger.skill}`); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroupEnd */ .TN)(); + const scheduleContext = { + eventType: 'schedule', + action: 'scheduled', + repository: { owner, name: repo, fullName: `${owner}/${repo}`, defaultBranch }, + repoPath, + }; + let memoryRecall; + if (service?.memory) { + try { + const recallContext = await (0,_event_schedule_context_js__WEBPACK_IMPORTED_MODULE_1__/* .buildScheduleEventContext */ .J)({ + patterns: [...new Set(scheduleTriggers.flatMap((trigger) => trigger.filters?.paths ?? ['**/*']))], + ignorePatterns: [_base_js__WEBPACK_IMPORTED_MODULE_11__/* .FINDINGS_OUTPUT_FILENAME */ .X0, _base_js__WEBPACK_IMPORTED_MODULE_11__/* .FINDINGS_OUTPUT_DONE_FILENAME */ .GF], + repoPath, + owner, + name: repo, + defaultBranch, + headSha, + }); + memoryRecall = await (0,_service_js__WEBPACK_IMPORTED_MODULE_10__/* .recallActionMemoryFailOpen */ .t4)(service, recallContext, scheduleTriggers.map((trigger) => trigger.skill)); + } + catch { + console.log('::warning::Warden service memory recall failed. Action results are unchanged.'); + } + } + const allReports = []; + const skillExecutions = []; + const skippedTriggers = []; + let totalFindings = 0; + const failureReasons = []; + const triggerErrors = []; + let shouldFailAction = false; + const writeLiveSnapshot = (processedCount) => { + const pending = scheduleTriggers.slice(processedCount + 1).map((t) => ({ + skillName: t.skill, + triggerId: t.id, + triggerName: t.name, + reason: 'pending', + })); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .writeFindingsOutputLive */ .ZU)([...allReports], scheduleContext, [], { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_9__/* .buildBaseOutputOptions */ .vM)(inputs, [...skippedTriggers, ...pending]), + skillExecutions: [...skillExecutions], + }); + }; + // Process each schedule trigger + for (const [triggerIndex, resolved] of scheduleTriggers.entries()) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroup */ .QT)(`Running trigger: ${resolved.name} (skill: ${resolved.skill})`); + const findingProcessingEvents = []; + let executionRecorded = false; + try { + (0,_sdk_runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_3__/* .assertValidPiModelSelectors */ .lG)([resolved]); + // Build context from paths filter + const patterns = resolved.filters?.paths ?? ['**/*']; + const ignorePatterns = [ + ...(resolved.filters?.ignorePaths ?? []), + _base_js__WEBPACK_IMPORTED_MODULE_11__/* .FINDINGS_OUTPUT_FILENAME */ .X0, + _base_js__WEBPACK_IMPORTED_MODULE_11__/* .FINDINGS_OUTPUT_DONE_FILENAME */ .GF, + ]; + const context = await (0,_event_schedule_context_js__WEBPACK_IMPORTED_MODULE_1__/* .buildScheduleEventContext */ .J)({ + patterns, + ignorePatterns, + ignore: resolved.ignore, + scan: resolved.scan, + repoPath, + owner, + name: repo, + defaultBranch, + headSha, + }); + // Skip if no matching files + if (!context.pullRequest?.files.length) { + console.log(`No files match trigger ${resolved.name}`); + skippedTriggers.push({ skillName: resolved.skill, triggerId: resolved.id, triggerName: resolved.name, reason: 'no_changes' }); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroupEnd */ .TN)(); + writeLiveSnapshot(triggerIndex); + continue; + } + console.log(`Found ${context.pullRequest.files.length} files matching patterns`); + // Run skill + const skillRoot = resolved.useBuiltinSkill ? undefined : (resolved.skillRoot ?? repoPath); + const skill = await (0,_skills_loader_js__WEBPACK_IMPORTED_MODULE_6__/* .resolveSkillAsync */ .Cy)(resolved.skill, skillRoot, { + remote: resolved.remote, + offline: (0,_sdk_offline_js__WEBPACK_IMPORTED_MODULE_13__/* .isWardenOffline */ .XK)(), + }); + const runtimeEnv = await (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .prepareRuntimeEnvironment */ .bZ)([resolved], inputs); + const report = await (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_2__/* .runSkill */ .pd)(skill, context, { + apiKey: inputs.anthropicApiKey, + model: resolved.model, + runtime: resolved.runtime, + effort: resolved.effort, + auxiliaryModel: resolved.auxiliaryModel, + auxiliaryEffort: resolved.auxiliaryEffort, + synthesisModel: resolved.synthesisModel, + maxTurns: resolved.maxTurns, + concurrency: runnerConcurrency ?? inputs.parallel, + batchDelayMs: resolved.batchDelayMs, + maxContextFiles: resolved.maxContextFiles, + ignore: resolved.ignore, + scan: resolved.scan, + chunking: resolved.chunking, + auxiliaryMaxRetries: resolved.auxiliaryMaxRetries, + verifyFindings: resolved.verifyFindings, + triggerName: resolved.name, + historicalEvidence: memoryRecall?.historicalEvidence, + pathToClaudeCodeExecutable: runtimeEnv.pathToClaudeCodeExecutable, + callbacks: { + onFindingProcessing: (event) => findingProcessingEvents.push(event), + }, + }); + console.log(`Found ${report.findings.length} findings`); + allReports.push(report); + totalFindings += report.findings.length; + // Pushed before the fallible issue write below: if createOrUpdateIssue + // throws, allReports (and thus the final export) already has this + // report, so its execution metadata (join key, model lanes, captured + // provenance events) must already be recorded too, not lost with it. + const executionMeta = { + report, + skillExecutionId: resolved.skillExecutionId, + triggerId: resolved.id, + triggerName: resolved.name, + auxiliaryModel: resolved.auxiliaryModel, + synthesisModel: resolved.synthesisModel, + findingProcessingEvents, + }; + skillExecutions.push(executionMeta); + executionRecorded = true; + // Create/update issue with findings + const scheduleConfig = resolved.schedule ?? {}; + const issueTitle = scheduleConfig.issueTitle ?? `Warden: ${resolved.name}`; + const issueResult = await (0,_output_github_issues_js__WEBPACK_IMPORTED_MODULE_4__/* .createOrUpdateIssue */ .w)(octokit, owner, repo, [report], { + title: issueTitle, + commitSha: headSha, + }); + if (issueResult) { + console.log(`${issueResult.created ? 'Created' : 'Updated'} issue #${issueResult.issueNumber}`); + console.log(`Issue URL: ${issueResult.issueUrl}`); + executionMeta.issueNumber = issueResult.issueNumber; + executionMeta.issueUrl = issueResult.issueUrl; + } + // Check failure condition + // Filter by confidence first so low-confidence findings don't cause failure + const failOn = resolved.failOn ?? inputs.failOn; + const failCheck = resolved.failCheck ?? inputs.failCheck ?? false; + const reportForFail = { ...report, findings: (0,_types_index_js__WEBPACK_IMPORTED_MODULE_7__/* .filterFindings */ .Ni)(report.findings, undefined, resolved.minConfidence ?? 'medium') }; + if (failCheck && failOn && (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .shouldFail */ .W9)(reportForFail, failOn)) { + shouldFailAction = true; + const count = (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .countFindingsAtOrAbove */ .tH)(reportForFail, failOn); + failureReasons.push(`${resolved.name}: Found ${count} ${failOn}+ severity issues`); + } + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroupEnd */ .TN)(); + writeLiveSnapshot(triggerIndex); + } + catch (error) { + if (error instanceof _base_js__WEBPACK_IMPORTED_MODULE_11__/* .ActionFailedError */ .Ah) + throw error; + (0,_error_reporting_js__WEBPACK_IMPORTED_MODULE_12__/* .captureActionTriggerError */ .T)(error, { + triggerName: resolved.name, + skillName: resolved.skill, + }); + const errorMessage = error instanceof Error ? error.message : String(error); + triggerErrors.push(`${resolved.name}: ${errorMessage}`); + if (!executionRecorded) { + skippedTriggers.push({ skillName: resolved.skill, triggerId: resolved.id, triggerName: resolved.name, reason: 'error' }); + } + console.error(`::warning::Trigger ${resolved.name} failed: ${error}`); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .logGroupEnd */ .TN)(); + writeLiveSnapshot(triggerIndex); + } + } + // Set outputs + const highCount = (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_5__/* .countSeverity */ .jC)(allReports, 'high'); + workflowSpan.setAttribute('warden.finding.count', totalFindings); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('findings-count', totalFindings); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('high-count', highCount); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setOutput */ .uH)('summary', allReports.map((r) => r.summary).join('\n') || 'Scheduled analysis complete'); + // Write structured findings to file for external export (GCS, S3, etc.) + // before any all-failed/shouldFail error can propagate — this is the run's + // one true final write (`.done` marker + `findings-file` output), and it + // must land even when every trigger failed, or a terminated run is left + // looking permanently in-progress to a follower of the live snapshots. + const findingsOptions = { + ...(0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_9__/* .buildBaseOutputOptions */ .vM)(inputs, skippedTriggers), + skillExecutions, + recalledMemories: memoryRecall?.memories.map(({ id, version }) => ({ id, version })), + memoryRecallId: memoryRecall?.clientRecallId, + }; + try { + const findingsPath = (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .writeFindingsOutput */ .JR)(allReports, scheduleContext, [], findingsOptions); + console.log(`Findings written to ${findingsPath}`); + } + catch (error) { + console.error(`::warning::Failed to write findings output: ${error}`); + } + await (0,_service_js__WEBPACK_IMPORTED_MODULE_10__/* .publishActionRunFailOpen */ .pp)(service, () => (0,_reporting_output_js__WEBPACK_IMPORTED_MODULE_9__/* .buildFindingsOutput */ .Cs)(allReports, scheduleContext, [], findingsOptions)); + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .handleTriggerErrors */ .a3)(triggerErrors, scheduleTriggers.length); + if (shouldFailAction) { + (0,_base_js__WEBPACK_IMPORTED_MODULE_11__/* .setFailed */ .C1)(failureReasons.join('; ')); + } + console.log(`\nScheduled analysis complete: ${totalFindings} total findings`); +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 4257: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* unused harmony exports buildLocalEventContext, buildFileEventContext */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _output_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1978); +/* harmony import */ var _files_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20453); +/* harmony import */ var _git_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20190); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_output_index_js__WEBPACK_IMPORTED_MODULE_2__]); +_output_index_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; + + + + + +/** + * Convert git file change to EventContext FileChange format. + */ +function toFileChange(file) { + return { + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch, + chunks: file.chunks, + }; +} +/** + * Build an EventContext from local git repository state. + * Creates a synthetic pull_request event from git diff. + * + * When analyzing a specific commit (head is set), uses the actual commit + * message as title/body to provide intent context to the LLM. + */ +function buildLocalEventContext(options = {}) { + const cwd = options.cwd ?? process.cwd(); + const repoPath = getRepoRoot(cwd); + const { owner, name } = getRepoName(cwd); + const defaultBranch = options.defaultBranch ?? getDefaultBranch(cwd); + // When staged, always diff against HEAD (index vs HEAD) + const staged = options.staged ?? false; + const base = staged ? 'HEAD' : (options.base ?? defaultBranch); + const head = options.head; // undefined means working tree + const currentBranch = getCurrentBranch(cwd); + const headSha = head ? resolveRef(head, cwd) : getHeadSha(cwd); + const changedFiles = getChangedFilesWithPatches(base, head, cwd, { staged }); + const files = changedFiles.map(toFileChange); + // Use actual commit message when analyzing a specific commit + let title; + let body; + if (head) { + const commitMsg = getCommitMessage(head, cwd); + title = commitMsg.subject || `Commit ${head}`; + body = commitMsg.body || `Analyzing changes in ${head}`; + } + else if (staged) { + title = `Staged changes: ${currentBranch}`; + body = `Analyzing staged changes`; + } + else { + title = `Local changes: ${currentBranch}`; + body = `Analyzing local changes from ${base} to working tree`; + } + const diffContextSource = staged + ? { type: 'git-index' } + : head + ? { type: 'git-ref', ref: headSha } + : { type: 'working-tree' }; + return { + eventType: 'pull_request', + action: 'opened', + repository: { + owner, + name, + fullName: `${owner}/${name}`, + defaultBranch, + }, + pullRequest: { + number: 0, // Local run, no real PR number + title, + body, + author: 'local', + baseBranch: base, + headBranch: currentBranch, + headSha, + baseSha: resolveRef(base, cwd), + files, + }, + diffContextSource, + repoPath, + }; +} +/** + * Build an EventContext from a list of files or glob patterns. + * Creates a synthetic pull_request event treating files as newly added. + * This allows analysis without requiring git or a warden.toml config. + */ +async function buildFileEventContext(options) { + const requestedCwd = resolve(options.cwd ?? process.cwd()); + let cwd = requestedCwd; + try { + cwd = realpathSync(requestedCwd); + } + catch { + // File expansion reports missing or inaccessible invocation directories. + } + let repoPath = cwd; + try { + repoPath = getRepoRoot(cwd); + } + catch { + // Explicit file analysis also works outside a Git checkout. + } + const dirName = basename(repoPath); + const files = await expandAndCreateFileChanges(options.patterns, cwd, { + ignore: options.ignore, + scan: options.scan, + basePath: repoPath, + }); + return { + eventType: 'pull_request', + action: 'opened', + repository: { + owner: 'local', + name: dirName, + fullName: `local/${dirName}`, + defaultBranch: 'main', + }, + pullRequest: { + number: 0, + title: 'File analysis', + body: `Analyzing ${files.length} ${pluralize(files.length, 'file')}`, + author: 'local', + baseBranch: 'main', + headBranch: 'file-analysis', + headSha: 'file-analysis', + baseSha: 'file-analysis', + files, + }, + diffContextSource: { type: 'working-tree' }, + explicitFileTargets: true, + repoPath, + }; +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 20453: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Rq: () => (/* binding */ expandAndCreateFileChanges) +/* harmony export */ }); +/* unused harmony exports expandFileGlobs, createPatchFromContent, createSyntheticFileChange, createSyntheticFileChanges */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var brace_expansion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(94006); +/* harmony import */ var tinyglobby__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(7122); +/* harmony import */ var ignore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(22881); +/* harmony import */ var ignore__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(ignore__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(78481); +/* harmony import */ var _sdk_scan_policy_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(47394); +/* harmony import */ var _utils_exec_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(82224); +/* harmony import */ var _utils_path_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(60702); + + + + + + + + + +function hasGlobCharacters(pattern) { + return pattern.includes('*') || pattern.includes('?'); +} +function expandDirectoryPattern(pattern, cwd) { + if (hasGlobCharacters(pattern)) { + return pattern; + } + try { + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync)((0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(cwd, pattern)).isDirectory()) { + return pattern; + } + } + catch { + return pattern; + } + const normalized = (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)(pattern).replace(/\/+$/, ''); + if (normalized === '' || normalized === '.') { + return '**'; + } + return `${normalized}/**`; +} +/** + * Find the git root directory by walking up from the given path. + * Returns the git root path, or null if not in a git repository. + */ +function findGitRoot(startPath) { + try { + const root = (0,_utils_exec_js__WEBPACK_IMPORTED_MODULE_6__/* .execGitNonInteractive */ .rd)(['rev-parse', '--show-toplevel'], { + cwd: (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(startPath), + }); + return root ? (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(root) : null; + } + catch { + return null; + } +} +/** + * Prefix gitignore patterns with a directory path. + * Handles negation patterns, leading slashes, and preserves comments/empty lines. + * + * Note: Patterns without slashes (like *.log) are intentionally NOT prefixed + * with **\/ because the ignore package handles them correctly - they match + * at any depth relative to the .gitignore location when the path being tested + * is relative to the git root with the subdir prefix included. + */ +function prefixGitignorePatterns(content, prefix) { + return content + .split('\n') + .map((line) => { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + return line; + } + // Handle negation patterns + const isNegation = trimmed.startsWith('!'); + const pattern = isNegation ? trimmed.slice(1) : trimmed; + // Handle patterns with leading slash (anchored to .gitignore location) + // Remove leading slash to avoid double slashes: /build -> subdir/build + const cleanPattern = pattern.startsWith('/') ? pattern.slice(1) : pattern; + const prefixedPattern = `${prefix}/${cleanPattern}`; + return isNegation ? `!${prefixedPattern}` : prefixedPattern; + }) + .join('\n'); +} +/** + * Load all .gitignore files in the repository. + * Returns an ignore instance that can check if a file path should be ignored. + * + * The ignore package handles the complexity of gitignore semantics: + * - Patterns are applied relative to their .gitignore location + * - Negation patterns (!) work correctly + * - Directory patterns with trailing / work correctly + */ +function loadGitignoreRules(gitRoot) { + const ig = ignore__WEBPACK_IMPORTED_MODULE_3___default()(); + // Always ignore .git directory + ig.add('.git'); + // Use git to discover .gitignore files. This naturally skips ignored + // directories (node_modules, .venv, vendor, etc.) without maintaining + // a hardcoded exclusion list. + let gitignoreFiles; + try { + const output = (0,_utils_exec_js__WEBPACK_IMPORTED_MODULE_6__/* .execGitNonInteractive */ .rd)(['ls-files', '--cached', '--others', '--exclude-standard', '.gitignore', '**/.gitignore'], { cwd: gitRoot }); + gitignoreFiles = output + ? output.split('\n').map((f) => (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(gitRoot, f)) + : []; + } + catch { + // Not a real git repo or git not available. Walk directories manually, + // skipping common large directories that would never contain relevant + // .gitignore files. + gitignoreFiles = (0,tinyglobby__WEBPACK_IMPORTED_MODULE_8__/* .globSync */ .AZ)('**/.gitignore', { + cwd: gitRoot, + absolute: true, + dot: true, + expandDirectories: false, + ignore: ['**/.git/**', '**/node_modules/**'], + }); + } + // Sort by path depth (root first, then nested). + // Normalize to forward slashes so depth counting works on Windows too. + gitignoreFiles.sort((a, b) => (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)(a).split('/').length - (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)(b).split('/').length); + // Process gitignore files from root down (parent rules apply first) + for (const gitignorePath of gitignoreFiles) { + try { + const content = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(gitignorePath, 'utf-8'); + // Use normalized paths for relative calculation + const relativeDir = (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)((0,node_path__WEBPACK_IMPORTED_MODULE_1__.relative)(gitRoot, (0,node_path__WEBPACK_IMPORTED_MODULE_1__.dirname)(gitignorePath))); + if (relativeDir) { + ig.add(prefixGitignorePatterns(content, relativeDir)); + } + else { + ig.add(content); + } + } + catch { + // Ignore read errors (e.g., permission issues) + } + } + return ig; +} +/** + * Expand glob patterns to a list of file paths. + * + * By default, respects .gitignore files to automatically exclude ignored + * directories like node_modules/. This can be disabled by setting + * gitignore: false. + */ +async function expandFileGlobs(patterns, cwdOrOptions = process.cwd()) { + const options = typeof cwdOrOptions === 'string' ? { cwd: cwdOrOptions } : cwdOrOptions; + // Resolve to absolute path to handle relative paths like '.' or 'src' + const cwd = (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(options.cwd ?? process.cwd()); + const useGitignore = options.gitignore ?? true; + // Expand ranges before matching so multi-digit and padded values keep their width. + const expandedPatterns = patterns.flatMap((pattern) => (0,brace_expansion__WEBPACK_IMPORTED_MODULE_2__/* .expand */ .fT)(expandDirectoryPattern(pattern, cwd))); + // Get all matching files first + const files = await (0,tinyglobby__WEBPACK_IMPORTED_MODULE_8__/* .glob */ .TI)(expandedPatterns, { + cwd, + onlyFiles: true, + absolute: true, + dot: false, + expandDirectories: false, + braceExpansion: false, + // Always exclude .git directory + ignore: ['**/.git/**'], + }); + // If gitignore is disabled, return files as-is + if (!useGitignore) { + return files.sort(); + } + // Find git root - if not in a git repo, don't apply gitignore rules + const gitRoot = findGitRoot(cwd); + if (!gitRoot) { + return files.sort(); + } + // Load and apply gitignore rules + const ig = loadGitignoreRules(gitRoot); + const cwdRelativeToGitRoot = (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)((0,node_path__WEBPACK_IMPORTED_MODULE_1__.relative)(gitRoot, (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.realpathSync)(cwd))); + // Filter files using gitignore rules + // Normalize paths to forward slashes for consistent matching + const filteredFiles = files.filter((file) => { + const fileRelativeToCwd = (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)((0,node_path__WEBPACK_IMPORTED_MODULE_1__.relative)(cwd, file)); + const relativePath = cwdRelativeToGitRoot + ? (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)(`${cwdRelativeToGitRoot}/${fileRelativeToCwd}`) + : fileRelativeToCwd; + if (!(0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .isRepoRelativePath */ .Ms)(relativePath)) { + return true; + } + return !ig.ignores(relativePath); + }); + return filteredFiles.sort(); +} +/** + * Create a unified diff patch for a file, treating entire content as added. + */ +function createPatchFromContent(content) { + const lines = content.split('\n'); + const lineCount = lines.length; + // Handle empty files + if (lineCount === 0 || (lineCount === 1 && lines[0] === '')) { + return '@@ -0,0 +0,0 @@\n'; + } + // Create patch header showing all lines as additions + const patchLines = [`@@ -0,0 +1,${lineCount} @@`]; + for (const line of lines) { + patchLines.push(`+${line}`); + } + return patchLines.join('\n'); +} +/** + * Read a file and create a synthetic FileChange treating it as newly added. + * Scan limits can return a patchless placeholder without reading file content. + */ +function createSyntheticFileChange(absolutePath, basePath, options = {}) { + const relativePath = (0,_utils_path_js__WEBPACK_IMPORTED_MODULE_7__/* .normalizePath */ .Fd)((0,node_path__WEBPACK_IMPORTED_MODULE_1__.relative)(basePath, absolutePath)); + const prePatchSkip = (0,_sdk_scan_policy_js__WEBPACK_IMPORTED_MODULE_5__/* .getPrePatchFileSkip */ .vC)(relativePath, { + repoPath: basePath, + ignore: options.ignore, + scan: options.scan, + }); + if (prePatchSkip) { + return { + filename: relativePath, + status: 'added', + additions: 0, + deletions: 0, + chunks: 0, + }; + } + const content = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(absolutePath, 'utf-8'); + const lines = content.split('\n'); + const lineCount = lines.length; + const patch = createPatchFromContent(content); + return { + filename: relativePath, + status: 'added', + additions: lineCount, + deletions: 0, + patch, + chunks: (0,_types_index_js__WEBPACK_IMPORTED_MODULE_4__/* .countPatchChunks */ .kV)(patch), + }; +} +/** + * Process a list of file paths into FileChange objects. + */ +function createSyntheticFileChanges(absolutePaths, basePath, options = {}) { + return absolutePaths.map((filePath) => createSyntheticFileChange(filePath, basePath, options)); +} +/** + * Expand glob patterns and create FileChange objects for all matching files. + */ +async function expandAndCreateFileChanges(patterns, cwd = process.cwd(), options = {}) { + const resolvedCwd = (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(cwd); + const files = await expandFileGlobs(patterns, resolvedCwd); + const basePath = (0,node_path__WEBPACK_IMPORTED_MODULE_1__.resolve)(options.basePath ?? resolvedCwd); + return createSyntheticFileChanges(files, basePath, { + ignore: options.ignore, + scan: options.scan, + }); +} + + +/***/ }), + +/***/ 20190: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* unused harmony exports getCurrentBranch, getHeadSha, resolveRef, getDefaultBranch, getRepoRoot, getRepoName, getGitHubRepoUrl, getChangedFiles, getFilePatch, getChangedFilesWithPatches, hasUncommittedChanges, refExists, getCommitMessage */ +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78481); +/* harmony import */ var _utils_exec_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82224); + + +/** + * Execute a git command and return stdout. + * Uses array-based arguments to avoid shell injection. + */ +function git(args, cwd = process.cwd()) { + try { + return execGitNonInteractive(args, { cwd }); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Git command failed: git ${args.join(' ')}\n${message}`, { cause: error }); + } +} +/** + * Get the current branch name. + */ +function getCurrentBranch(cwd = process.cwd()) { + return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd); +} +/** + * Get the HEAD commit SHA. + */ +function getHeadSha(cwd = process.cwd()) { + return resolveRef('HEAD', cwd); +} +/** + * Resolve a ref (branch name, tag, SHA) to a full commit SHA. + */ +function resolveRef(ref, cwd = process.cwd()) { + return git(['rev-parse', ref], cwd); +} +/** + * Detect the default branch by checking common branch names locally. + * Also checks remote tracking refs (origin/*) for shallow clones + * where local branches may not exist (e.g. GitHub Actions). + * Does not perform any remote operations to avoid SSH prompts. + */ +function getDefaultBranch(cwd = process.cwd()) { + // Check common default branches locally (no remote operations) + for (const branch of ['main', 'master', 'develop']) { + try { + git(['rev-parse', '--verify', branch], cwd); + return branch; + } + catch { + // Try next branch + } + } + // Check remote tracking refs (common in shallow clones / CI) + for (const branch of ['main', 'master', 'develop']) { + try { + git(['rev-parse', '--verify', `origin/${branch}`], cwd); + return `origin/${branch}`; + } + catch { + // Try next branch + } + } + // Check remote HEAD symbolic ref (set by clone, no network needed) + try { + const remoteHead = git(['symbolic-ref', 'refs/remotes/origin/HEAD'], cwd); + if (remoteHead) { + // Returns e.g. "refs/remotes/origin/main" → extract "origin/main" + const match = remoteHead.match(/refs\/remotes\/(.*)/); + if (match?.[1]) { + return match[1]; + } + } + } + catch { + // No remote HEAD configured + } + // Check git config for user-configured default branch + try { + const configuredDefault = git(['config', 'init.defaultBranch'], cwd); + if (configuredDefault) { + return configuredDefault; + } + } + catch { + // Config not set + } + return 'main'; // Default fallback +} +/** + * Get the repository root path. + */ +function getRepoRoot(cwd = process.cwd()) { + return git(['rev-parse', '--show-toplevel'], cwd); +} +/** + * Get the repository name from the git remote or directory name. + */ +function getRepoName(cwd = process.cwd()) { + try { + const remoteUrl = git(['config', '--get', 'remote.origin.url'], cwd); + // Handle SSH: git@github.com:owner/repo.git + // Handle HTTPS: https://github.com/owner/repo.git + const match = remoteUrl.match(/[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/); + if (match && match[1] && match[2]) { + return { owner: match[1], name: match[2] }; + } + } + catch { + // No remote configured + } + // Fall back to directory name + const repoRoot = getRepoRoot(cwd); + const dirName = repoRoot.split('/').pop() ?? 'unknown'; + return { owner: 'local', name: dirName }; +} +/** + * Get the GitHub repository URL if the remote is on GitHub. + * Returns null if the remote is not GitHub or not configured. + */ +function getGitHubRepoUrl(cwd = process.cwd()) { + try { + const remoteUrl = git(['config', '--get', 'remote.origin.url'], cwd); + // Handle SSH: git@github.com:owner/repo.git + const sshMatch = remoteUrl.match(/git@github\.com:([\w.-]+)\/([\w.-]+?)(?:\.git)?$/); + if (sshMatch && sshMatch[1] && sshMatch[2]) { + return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`; + } + // Handle HTTPS: https://github.com/owner/repo.git + const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?$/); + if (httpsMatch && httpsMatch[1] && httpsMatch[2]) { + return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`; + } + } + catch { + // No remote configured + } + return null; +} +/** + * Map git status letter to FileChange status. + */ +function mapStatus(status) { + switch (status[0]) { + case 'A': + return 'added'; + case 'D': + return 'removed'; + case 'M': + return 'modified'; + case 'R': + return 'renamed'; + case 'C': + return 'copied'; + default: + return 'modified'; + } +} +/** + * Build the git diff arguments for a given base/head/staged configuration. + * Extra flags (e.g. '--name-status') are placed before the ref, matching + * the documented git-diff synopsis: git diff [] [] ... + */ +function buildDiffArgs(base, head, options, extraFlags) { + const flags = extraFlags ?? []; + if (options?.staged) { + return ['diff', ...flags, '--cached']; + } + const diffRef = head ? `${base}...${head}` : base; + return ['diff', ...flags, diffRef]; +} +/** + * Get list of changed files between two refs. + * If head is undefined, compares against the working tree. + * If options.staged is true, compares only staged changes against HEAD. + */ +function getChangedFiles(base, head, cwd = process.cwd(), options) { + // Get file statuses + const nameStatusOutput = git(buildDiffArgs(base, head, options, ['--name-status']), cwd); + if (!nameStatusOutput) { + return []; + } + const files = []; + for (const line of nameStatusOutput.split('\n')) { + if (!line.trim()) + continue; + const parts = line.split('\t'); + const status = parts[0] ?? ''; + // For renames, format is "R100\told-name\tnew-name" + const filename = parts.length > 2 ? (parts[2] ?? '') : (parts[1] ?? ''); + if (!filename) + continue; + files.push({ + filename, + status: mapStatus(status), + additions: 0, + deletions: 0, + }); + } + // Get numstat for additions/deletions + const numstatOutput = git(buildDiffArgs(base, head, options, ['--numstat']), cwd); + if (numstatOutput) { + for (const line of numstatOutput.split('\n')) { + if (!line.trim()) + continue; + const parts = line.split('\t'); + const additions = parts[0] ?? '0'; + const deletions = parts[1] ?? '0'; + const filename = parts[2] ?? ''; + const file = files.find((f) => f.filename === filename); + if (file) { + file.additions = additions === '-' ? 0 : parseInt(additions, 10); + file.deletions = deletions === '-' ? 0 : parseInt(deletions, 10); + } + } + } + return files; +} +/** + * Get the patch for a specific file. + */ +function getFilePatch(base, head, filename, cwd = process.cwd(), options) { + try { + return git([...buildDiffArgs(base, head, options), '--', filename], cwd); + } + catch { + return undefined; + } +} +/** + * Parse a combined diff output into individual file patches. + */ +function parseCombinedDiff(diffOutput) { + const patches = new Map(); + if (!diffOutput) + return patches; + // Split by "diff --git" but keep the delimiter + const parts = diffOutput.split(/(?=^diff --git )/m); + for (const part of parts) { + if (!part.trim()) + continue; + // Extract filename from "diff --git a/path b/path" line + const match = part.match(/^diff --git a\/(.+?) b\/(.+?)\n/); + if (match) { + // Use the "b" path (destination) as the filename + const filename = match[2]; + if (filename) { + patches.set(filename, part); + } + } + } + return patches; +} +/** + * Get patches for all changed files in a single git command. + */ +function getChangedFilesWithPatches(base, head, cwd = process.cwd(), options) { + const files = getChangedFiles(base, head, cwd, options); + if (files.length === 0) { + return files; + } + // Get all patches in a single git diff command + try { + const combinedDiff = git(buildDiffArgs(base, head, options), cwd); + const patches = parseCombinedDiff(combinedDiff); + for (const file of files) { + file.patch = patches.get(file.filename); + file.chunks = countPatchChunks(file.patch); + } + } + catch { + // Fall back to per-file patches if combined diff fails + for (const file of files) { + file.patch = getFilePatch(base, head, file.filename, cwd, options); + file.chunks = countPatchChunks(file.patch); + } + } + return files; +} +/** + * Check if there are uncommitted changes in the working tree. + */ +function hasUncommittedChanges(cwd = process.cwd()) { + const status = git(['status', '--porcelain'], cwd); + return status.length > 0; +} +/** + * Check if a ref exists. + */ +function refExists(ref, cwd = process.cwd()) { + try { + git(['rev-parse', '--verify', ref], cwd); + return true; + } + catch { + return false; + } +} +/** + * Get the commit message for a specific ref. + * Returns subject (first line) and body (remaining lines) separately. + */ +function getCommitMessage(ref, cwd = process.cwd()) { + // %s = subject, %b = body + const subject = git(['log', '-1', `--format=%s`, ref], cwd); + const body = git(['log', '-1', `--format=%b`, ref], cwd); + return { subject, body }; +} + + +/***/ }), + +/***/ 8899: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* unused harmony export BoxRenderer */ + +/** + * Unicode box-drawing characters for TTY mode. + */ +const BOX = { + topLeft: '┌', + topRight: '┐', + bottomLeft: '└', + bottomRight: '┘', + horizontal: '─', + vertical: '│', + leftT: '├', + rightT: '┤', +}; +/** + * Renders box-style containers for terminal output. + * Supports TTY mode with Unicode box characters and CI mode with plain text. + */ +class BoxRenderer { + title; + badge; + mode; + width; + lines = []; + constructor(options) { + this.title = options.title; + this.badge = options.badge; + this.mode = options.mode; + // Calculate width based on terminal columns, with min/max constraints + const minWidth = options.minWidth ?? 50; + const maxWidth = Math.min(options.mode.columns - 2, 100); + this.width = Math.max(minWidth, maxWidth); + } + /** + * Render the top border with title and optional badge. + * TTY: ┌─ title ─────────────────────── badge ─┐ + * CI: === title (badge) === + */ + header() { + if (this.mode.isTTY) { + const titlePart = `${BOX.horizontal} ${this.title} `; + const badgePart = this.badge ? ` ${this.badge} ${BOX.horizontal}` : BOX.horizontal; + const titleLen = this.stripAnsi(titlePart).length; + const badgeLen = this.stripAnsi(badgePart).length; + const fillLen = Math.max(0, this.width - titleLen - badgeLen - 2); + const fill = BOX.horizontal.repeat(fillLen); + this.lines.push(chalk.dim(BOX.topLeft) + + chalk.dim(BOX.horizontal) + ' ' + + chalk.bold(this.title) + + ' ' + chalk.dim(fill) + + (this.badge ? chalk.dim(` ${this.badge} `) : '') + + chalk.dim(BOX.horizontal + BOX.topRight)); + } + else { + const badgePart = this.badge ? ` (${this.badge})` : ''; + this.lines.push(`=== ${this.title}${badgePart} ===`); + } + return this; + } + /** + * Get the available content width (excluding borders and padding). + */ + get contentWidth() { + return this.width - 4; // 2 for borders + 2 for padding spaces + } + /** + * Add content lines with side borders (TTY) or plain (CI). + * Long lines are automatically wrapped to fit within the box. + */ + content(contentLines) { + const lines = Array.isArray(contentLines) ? contentLines : [contentLines]; + for (const line of lines) { + // Wrap long lines to fit within the box + const wrappedLines = this.wrapLine(line); + for (const wrappedLine of wrappedLines) { + if (this.mode.isTTY) { + const strippedLen = this.stripAnsi(wrappedLine).length; + const padding = Math.max(0, this.width - strippedLen - 4); + this.lines.push(chalk.dim(BOX.vertical) + ' ' + wrappedLine + ' '.repeat(padding) + ' ' + chalk.dim(BOX.vertical)); + } + else { + this.lines.push(wrappedLine); + } + } + } + return this; + } + /** + * Wrap a line to fit within the content width. + * Preserves leading indentation on wrapped lines. + */ + wrapLine(line) { + const maxWidth = this.contentWidth; + const stripped = this.stripAnsi(line); + // If it fits, return as-is + if (stripped.length <= maxWidth) { + return [line]; + } + // For lines with ANSI codes, we need to be careful. + // For simplicity, if the line has ANSI codes and is too long, + // we'll wrap the stripped version and lose formatting on continuation lines. + const hasAnsi = line !== stripped; + // Detect leading indentation + const indentMatch = stripped.match(/^(\s*)/); + const indent = indentMatch?.[1] ?? ''; + const textToWrap = hasAnsi ? stripped : line; + const result = []; + let remaining = textToWrap; + let isFirstLine = true; + while (remaining.length > 0) { + const currentIndent = isFirstLine ? '' : indent; + const availableWidth = maxWidth - currentIndent.length; + if (this.stripAnsi(remaining).length <= availableWidth) { + result.push(currentIndent + remaining); + break; + } + // Find a good break point (prefer word boundaries) + let breakPoint = availableWidth; + const searchStart = Math.max(0, availableWidth - 20); + for (let i = availableWidth; i >= searchStart; i--) { + if (remaining[i] === ' ') { + breakPoint = i; + break; + } + } + // If no space found, hard break at max width + if (breakPoint === availableWidth && remaining[availableWidth] !== ' ') { + breakPoint = availableWidth; + } + const chunk = remaining.slice(0, breakPoint); + result.push(currentIndent + chunk); + // Skip the space at the break point if there is one + remaining = remaining.slice(breakPoint).trimStart(); + isFirstLine = false; + } + return result; + } + /** + * Add an empty content line. + */ + blank() { + return this.content(''); + } + /** + * Render a horizontal divider. + * TTY: ├─────────────────────────────────────────────┤ + * CI: --- + */ + divider() { + if (this.mode.isTTY) { + const fill = BOX.horizontal.repeat(this.width - 2); + this.lines.push(chalk.dim(BOX.leftT + fill + BOX.rightT)); + } + else { + this.lines.push('---'); + } + return this; + } + /** + * Render the bottom border. + * TTY: └─────────────────────────────────────────────┘ + * CI: (nothing in CI mode - just ends) + */ + footer() { + if (this.mode.isTTY) { + const fill = BOX.horizontal.repeat(this.width - 2); + this.lines.push(chalk.dim(BOX.bottomLeft + fill + BOX.bottomRight)); + } + return this; + } + /** + * Get all rendered lines. + */ + render() { + return [...this.lines]; + } + /** + * Get the rendered output as a single string. + */ + toString() { + return this.lines.join('\n'); + } + /** + * Strip ANSI escape codes from a string for length calculation. + */ + stripAnsi(str) { + // oxlint-disable-next-line no-control-regex + return str.replace(/\x1b\[[0-9;]*m/g, ''); + } +} + + +/***/ }), + +/***/ 43171: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ac: () => (/* binding */ formatStatsCompact), +/* harmony export */ BD: () => (/* binding */ formatCost), +/* harmony export */ Dc: () => (/* binding */ totalUsageStats), +/* harmony export */ Ot: () => (/* binding */ countBySeverity), +/* harmony export */ Xr: () => (/* binding */ formatFindingCountsPlain), +/* harmony export */ ZH: () => (/* binding */ capitalize), +/* harmony export */ _y: () => (/* binding */ formatTokens), +/* harmony export */ a3: () => (/* binding */ formatDuration), +/* harmony export */ j$: () => (/* binding */ formatLocation), +/* harmony export */ lg: () => (/* binding */ totalUsageCost), +/* harmony export */ td: () => (/* binding */ pluralize), +/* harmony export */ xz: () => (/* binding */ formatSeverityPlain) +/* harmony export */ }); +/* unused harmony exports formatElapsed, formatBytes, formatSeverityDot, formatSeverityBadge, formatConfidenceBadge, formatFindingCompact, formatFindingCounts, formatProgress, formatFileStats, truncate, padRight, formatUsage, formatUsagePlain, totalAuxiliaryCost */ +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(39559); +/* harmony import */ var figures__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58653); + + +/** + * Capitalize the first letter of a string. + * @example capitalize('critical') // 'Critical' + */ +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} +/** + * Pluralize a word based on count. + * @example pluralize(1, 'file') // 'file' + * @example pluralize(2, 'file') // 'files' + * @example pluralize(1, 'fix', 'fixes') // 'fix' + * @example pluralize(2, 'fix', 'fixes') // 'fixes' + */ +function pluralize(count, singular, plural) { + if (count === 1) + return singular; + return plural ?? `${singular}s`; +} +/** + * Format a duration in milliseconds to a human-readable string. + * Under 1s: "50ms". Under 60s: "3.2s". Over 60s: "5m 3s". + */ +function formatDuration(ms) { + if (ms < 1000) { + return `${Math.round(ms)}ms`; + } + const totalSeconds = ms / 1000; + if (totalSeconds < 60) { + const formatted = totalSeconds.toFixed(1); + // toFixed(1) can round 59.95 to "60.0" — fall through to minutes format + if (formatted !== '60.0') { + return `${formatted}s`; + } + } + let minutes = Math.floor(totalSeconds / 60); + let seconds = Math.round(totalSeconds % 60); + if (seconds === 60) { + minutes += 1; + seconds = 0; + } + if (seconds === 0) { + return `${minutes}m`; + } + return `${minutes}m ${seconds}s`; +} +/** + * Format an elapsed time for display (e.g., "+0.8s", "+2m 3s"). + */ +function formatElapsed(ms) { + return `+${formatDuration(ms)}`; +} +/** + * Format bytes into a compact human-readable size. + */ +function formatBytes(bytes) { + if (bytes < 1024) { + return `${bytes.toLocaleString()} B`; + } + const kb = bytes / 1024; + if (kb < 1024) { + return `${kb.toFixed(kb < 10 ? 1 : 0)} KB`; + } + const mb = kb / 1024; + return `${mb.toFixed(mb < 10 ? 1 : 0)} MB`; +} +/** + * Severity configuration for display. + */ +const SEVERITY_CONFIG = { + high: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.red, symbol: figures__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Ay.bullet }, + medium: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.yellow, symbol: figures__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Ay.bullet }, + low: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.green, symbol: figures__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Ay.bullet }, +}; +/** + * Format a severity dot for terminal output. + */ +function formatSeverityDot(severity) { + const config = SEVERITY_CONFIG[severity]; + return config.color(config.symbol); +} +/** + * Format a severity badge for terminal output (colored dot + severity text). + */ +function formatSeverityBadge(severity) { + const config = SEVERITY_CONFIG[severity]; + return `${config.color(config.symbol)} ${config.color(`(${severity})`)}`; +} +/** + * Format a severity for plain text (CI mode). + */ +function formatSeverityPlain(severity) { + return `[${severity}]`; +} +/** + * Confidence configuration for display. + */ +const CONFIDENCE_CONFIG = { + high: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.green }, + medium: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.yellow }, + low: { color: chalk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay.red }, +}; +/** + * Format a confidence badge for terminal output. + * Returns empty string if confidence is undefined. + */ +function formatConfidenceBadge(confidence) { + if (!confidence) + return ''; + const config = CONFIDENCE_CONFIG[confidence]; + return config.color(`[${confidence} confidence]`); +} +/** + * Format a file location string. + */ +function formatLocation(path, startLine, endLine) { + if (!startLine) { + return path; + } + if (endLine && endLine !== startLine) { + return `${path}:${startLine}-${endLine}`; + } + return `${path}:${startLine}`; +} +/** + * Format a finding for terminal display. + */ +function formatFindingCompact(finding) { + const badge = formatSeverityBadge(finding.severity); + const id = chalk.dim(`[${finding.id}]`); + const location = finding.location + ? chalk.dim(formatLocation(finding.location.path, finding.location.startLine, finding.location.endLine)) + : ''; + return `${badge} ${id} ${finding.title}${location ? ` ${location}` : ''}`; +} +/** + * Format finding counts for display (with colored dots). + */ +function formatFindingCounts(counts) { + const total = Object.values(counts).reduce((a, b) => a + b, 0); + if (total === 0) { + return chalk.green('No findings'); + } + const parts = []; + if (counts.high > 0) + parts.push(`${formatSeverityDot('high')} ${counts.high} high`); + if (counts.medium > 0) + parts.push(`${formatSeverityDot('medium')} ${counts.medium} medium`); + if (counts.low > 0) + parts.push(`${formatSeverityDot('low')} ${counts.low} low`); + return `${total} finding${total === 1 ? '' : 's'}: ${parts.join(' ')}`; +} +/** + * Format finding counts for plain text. + */ +function formatFindingCountsPlain(counts) { + const total = Object.values(counts).reduce((a, b) => a + b, 0); + if (total === 0) { + return 'No findings'; + } + const parts = []; + if (counts.high > 0) + parts.push(`${counts.high} high`); + if (counts.medium > 0) + parts.push(`${counts.medium} medium`); + if (counts.low > 0) + parts.push(`${counts.low} low`); + return `${total} finding${total === 1 ? '' : 's'} (${parts.join(', ')})`; +} +/** + * Format a progress indicator like [1/3]. + */ +function formatProgress(current, total) { + return chalk.dim(`[${current}/${total}]`); +} +/** + * Format file change summary. + */ +function formatFileStats(files) { + const added = files.filter((f) => f.status === 'added').length; + const modified = files.filter((f) => f.status === 'modified').length; + const removed = files.filter((f) => f.status === 'removed').length; + const parts = []; + if (added > 0) + parts.push(chalk.green(`+${added}`)); + if (modified > 0) + parts.push(chalk.yellow(`~${modified}`)); + if (removed > 0) + parts.push(chalk.red(`-${removed}`)); + return parts.length > 0 ? parts.join(' ') : ''; +} +/** + * Truncate a string to fit within a width, adding ellipsis if needed. + */ +function truncate(str, maxWidth) { + if (str.length <= maxWidth) { + return str; + } + if (maxWidth <= 3) { + return str.slice(0, maxWidth); + } + return str.slice(0, maxWidth - 1) + figures.ellipsis; +} +/** + * Pad a string on the right to reach a certain width. + */ +function padRight(str, width) { + if (str.length >= width) { + return str; + } + return str + ' '.repeat(width - str.length); +} +/** + * Count findings by severity. + */ +function countBySeverity(findings) { + const counts = { + high: 0, + medium: 0, + low: 0, + }; + for (const finding of findings) { + counts[finding.severity]++; + } + return counts; +} +/** + * Format a USD cost for display. + */ +function formatCost(costUSD) { + return `$${costUSD.toFixed(2)}`; +} +/** + * Calculate total usage across primary and auxiliary calls. + */ +function totalUsageStats(usage, auxiliaryUsage) { + const hasAuxiliaryUsage = auxiliaryUsage !== undefined && Object.keys(auxiliaryUsage).length > 0; + if (!usage && !hasAuxiliaryUsage) + return undefined; + const total = { + inputTokens: usage?.inputTokens ?? 0, + outputTokens: usage?.outputTokens ?? 0, + costUSD: usage?.costUSD ?? 0, + }; + const addOptional = (key, value) => { + if (value === undefined && total[key] === undefined) + return; + total[key] = (total[key] ?? 0) + (value ?? 0); + }; + if (usage) { + addOptional('cacheReadInputTokens', usage.cacheReadInputTokens); + addOptional('cacheCreationInputTokens', usage.cacheCreationInputTokens); + addOptional('cacheCreation5mInputTokens', usage.cacheCreation5mInputTokens); + addOptional('cacheCreation1hInputTokens', usage.cacheCreation1hInputTokens); + addOptional('webSearchRequests', usage.webSearchRequests); + } + for (const auxiliary of Object.values(auxiliaryUsage ?? {})) { + total.inputTokens += auxiliary.inputTokens; + total.outputTokens += auxiliary.outputTokens; + total.costUSD += auxiliary.costUSD; + addOptional('cacheReadInputTokens', auxiliary.cacheReadInputTokens); + addOptional('cacheCreationInputTokens', auxiliary.cacheCreationInputTokens); + addOptional('cacheCreation5mInputTokens', auxiliary.cacheCreation5mInputTokens); + addOptional('cacheCreation1hInputTokens', auxiliary.cacheCreation1hInputTokens); + addOptional('webSearchRequests', auxiliary.webSearchRequests); + } + return total; +} +/** + * Calculate total cost across primary and auxiliary usage. + */ +function totalUsageCost(usage, auxiliaryUsage) { + return totalUsageStats(usage, auxiliaryUsage)?.costUSD; +} +/** + * Format token counts for display. + */ +function formatTokens(tokens) { + if (tokens >= 1_000_000) { + return `${(tokens / 1_000_000).toFixed(1)}M`; + } + if (tokens >= 1_000) { + return `${(tokens / 1_000).toFixed(1)}k`; + } + return String(tokens); +} +/** + * Format usage stats for terminal display. + */ +function formatUsage(usage, auxiliaryUsage) { + const total = totalUsageStats(usage, auxiliaryUsage) ?? usage; + const inputStr = formatTokens(total.inputTokens); + const outputStr = formatTokens(total.outputTokens); + const costStr = formatCost(total.costUSD); + return `${inputStr} in / ${outputStr} out · ${costStr}`; +} +/** + * Format usage stats for plain text display. + */ +function formatUsagePlain(usage, auxiliaryUsage) { + const total = totalUsageStats(usage, auxiliaryUsage) ?? usage; + const inputStr = formatTokens(total.inputTokens); + const outputStr = formatTokens(total.outputTokens); + const costStr = formatCost(total.costUSD); + return `${inputStr} input, ${outputStr} output, ${costStr}`; +} +/** + * Calculate total auxiliary cost from an AuxiliaryUsageMap. + */ +function totalAuxiliaryCost(auxiliaryUsage) { + return Object.values(auxiliaryUsage).reduce((sum, u) => sum + u.costUSD, 0); +} +/** + * Format stats (duration, tokens, cost) into a compact single-line format. + * Used for markdown footers in PR comments and check annotations. + * + * When auxiliaryUsage is provided, tokens and cost are primary + auxiliary totals. + * + * @example formatStatsCompact(15800, { inputTokens: 3000, outputTokens: 680, costUSD: 0.0048 }) + * // Returns: "⏱ 15.8s · 3.0k in / 680 out · $0.00" + * + * @example formatStatsCompact(15800, usage, { extraction: { inputTokens: 100, outputTokens: 50, costUSD: 0.001 } }) + * // Returns: "⏱ 15.8s · 3.1k in / 730 out · $0.01" + */ +function formatStatsCompact(durationMs, usage, auxiliaryUsage) { + const parts = []; + const total = totalUsageStats(usage, auxiliaryUsage); + if (durationMs !== undefined) { + parts.push(`⏱ ${formatDuration(durationMs)}`); + } + if (total) { + parts.push(`${formatTokens(total.inputTokens)} in / ${formatTokens(total.outputTokens)} out`); + parts.push(formatCost(total.costUSD)); + } + return parts.join(' · '); +} + + +/***/ }), + +/***/ 5832: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ hP: () => (/* binding */ ICON_CHECK), +/* harmony export */ xj: () => (/* binding */ ICON_SKIPPED) +/* harmony export */ }); +/* unused harmony exports SPINNER_FRAMES, ICON_PENDING, ICON_ERROR */ +/** + * Unicode icons for CLI output. + * Uses CHECK MARK (U+2713) instead of HEAVY CHECK MARK (U+2714) to avoid emoji rendering. + */ +/** Check mark for completed/success states */ +const ICON_CHECK = '✓'; // U+2713 CHECK MARK +/** Down arrow for skipped states */ +const ICON_SKIPPED = '↓'; // U+2193 DOWNWARDS ARROW +/** Braille spinner frames for loading animation */ +const SPINNER_FRAMES = (/* unused pure expression or super */ null && (['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F'])); +/** Circle for pending states */ +const ICON_PENDING = '\u25CB'; // ○ WHITE CIRCLE +/** X mark for error states */ +const ICON_ERROR = '\u2717'; // ✗ BALLOT X + + +/***/ }), + +/***/ 1978: +/***/ ((module, __unused_webpack___webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony import */ var _verbosity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21307); +/* harmony import */ var _reporter_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34593); +/* harmony import */ var _formatters_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43171); +/* harmony import */ var _tasks_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5836); +/* harmony import */ var _ink_runner_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(10483); +/* harmony import */ var _box_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8899); +/* harmony import */ var _jsonl_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6743); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_tasks_js__WEBPACK_IMPORTED_MODULE_3__, _ink_runner_js__WEBPACK_IMPORTED_MODULE_4__]); +([_tasks_js__WEBPACK_IMPORTED_MODULE_3__, _ink_runner_js__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__); + + + + + + + + + + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 10483: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* unused harmony exports getSkillCostUSD, runSkillTasksWithInk */ +/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(43663); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(54583); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var ink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22687); +/* harmony import */ var _tasks_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5836); +/* harmony import */ var _formatters_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(43171); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(82272); +/* harmony import */ var _verbosity_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(21307); +/* harmony import */ var _sdk_circuit_breaker_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(71794); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([ink__WEBPACK_IMPORTED_MODULE_2__, _tasks_js__WEBPACK_IMPORTED_MODULE_3__]); +([ink__WEBPACK_IMPORTED_MODULE_2__, _tasks_js__WEBPACK_IMPORTED_MODULE_3__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__); + +/** + * Ink-based skill runner with real-time progress display. + * + * While skills run, the dynamic Ink area shows running skills and active files. + * After Ink unmounts, the full per-skill + per-file breakdown is printed to + * stderr, followed by the normal findings report. + * + * UI updates are batched via setImmediate() to prevent rapid consecutive + * rerender() calls from producing duplicate output lines. + * + * Reporter spec: specs/reporters.md + * Terminal output design guide: specs/terminal-output.md + */ + + + + + + + + + + + +function Spinner() { + const [frame, setFrame] = useState(0); + useEffect(() => { + const timer = setInterval(() => { + setFrame((f) => (f + 1) % SPINNER_FRAMES.length); + }, 80); + return () => clearInterval(timer); + }, []); + return _jsx(Text, { color: "yellow", children: SPINNER_FRAMES[frame] }); +} +function FileProgress({ file }) { + const filename = truncate(file.filename, 50); + return (_jsxs(Box, { children: [_jsx(Spinner, {}), _jsxs(Text, { children: [" ", filename, " [", file.currentHunk, "/", file.totalHunks, "]"] })] })); +} +function getSkillCostUSD(skill) { + const hasFileUsage = skill.files.some((file) => file.usage !== undefined); + const primaryCost = skill.usage?.costUSD + ?? (hasFileUsage ? skill.files.reduce((sum, file) => sum + (file.usage?.costUSD ?? 0), 0) : undefined); + const auxiliaryCost = skill.auxiliaryUsage ? totalAuxiliaryCost(skill.auxiliaryUsage) : 0; + if (primaryCost === undefined && auxiliaryCost === 0) { + return undefined; + } + return (primaryCost ?? 0) + auxiliaryCost; +} +function RunningSkill({ skill }) { + const activeFiles = skill.files.filter((f) => f.status === 'running'); + const doneCount = skill.files.filter((f) => f.status === 'done' || f.status === 'skipped').length; + const totalCount = skill.files.length; + const findingCount = skill.files.reduce((sum, f) => sum + f.findings.length, 0); + const cost = getSkillCostUSD(skill); + return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Spinner, {}), _jsxs(Text, { children: [" ", skill.displayName] }), totalCount > 0 && _jsxs(Text, { dimColor: true, children: [" [", doneCount, "/", totalCount, " files]"] }), findingCount > 0 && _jsxs(Text, { children: [" ", findingCount, " ", findingCount === 1 ? 'finding' : 'findings'] }), cost !== undefined && cost > 0 && _jsxs(Text, { dimColor: true, children: [" ", formatCost(cost)] })] }), activeFiles.map((file) => (_jsx(Box, { marginLeft: 2, children: _jsx(FileProgress, { file: file }) }, file.filename)))] })); +} +function CompletedSkill({ skill }) { + if (skill.status === 'skipped') { + return (_jsxs(Text, { children: [_jsx(Text, { color: "yellow", children: ICON_SKIPPED }), " ", skill.displayName, " ", _jsx(Text, { dimColor: true, children: "[skipped]" })] })); + } + const findingCount = skill.findings.length; + const cost = getSkillCostUSD(skill); + const duration = skill.durationMs ? formatDuration(skill.durationMs) : undefined; + if (skill.status === 'error') { + return (_jsxs(Text, { children: [_jsx(Text, { color: "red", children: ICON_ERROR }), " ", skill.displayName, duration && _jsxs(Text, { dimColor: true, children: [" [", duration, "]"] })] })); + } + return (_jsxs(Text, { children: [_jsx(Text, { color: "green", children: ICON_CHECK }), " ", skill.displayName, duration && _jsxs(Text, { dimColor: true, children: [" [", duration, "]"] }), findingCount > 0 && _jsxs(Text, { children: [" ", findingCount, " ", findingCount === 1 ? 'finding' : 'findings'] }), cost !== undefined && cost > 0 && _jsxs(Text, { dimColor: true, children: [" ", formatCost(cost)] })] })); +} +function SkillRunner({ skills, warnings, interrupted, failFastTriggered }) { + const completed = skills.filter((s) => s.status === 'done' || s.status === 'skipped' || s.status === 'error'); + const running = skills.filter((s) => s.status === 'running'); + const pending = skills.filter((s) => s.status === 'pending'); + return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: warnings, children: (warning, index) => (_jsx(Text, { children: warning }, index)) }), completed.map((skill) => (_jsx(CompletedSkill, { skill: skill }, skill.name))), running.map((skill) => (_jsx(RunningSkill, { skill: skill }, skill.name))), pending.map((skill) => (_jsxs(Text, { dimColor: true, children: [ICON_PENDING, " ", skill.displayName] }, skill.name))), failFastTriggered && (_jsxs(Text, { color: "yellow", dimColor: true, children: [figures.warning, " Stopping ", '\u2014', " finding detected (--fail-fast)"] })), interrupted && !failFastTriggered && (_jsxs(Text, { color: "yellow", dimColor: true, children: [figures.warning, " Interrupted, finishing up... (press Ctrl+C again to force exit)"] }))] })); +} +/** Create a terminal skill state for skills that were skipped or errored before starting. */ +function makeTerminalSkillState(tasks, name, overrides) { + const task = tasks.find((t) => t.name === name); + return { + name, + displayName: task?.displayName ?? name, + status: 'pending', + files: [], + findings: [], + ...overrides, + }; +} +/** No-op callbacks for quiet mode. */ +const noop = () => { + return; +}; +const noopCallbacks = { + onSkillStart: noop, + onSkillUpdate: noop, + onFileUpdate: noop, + onChunkComplete: noop, + onSkillComplete: noop, + onSkillSkipped: noop, + onSkillError: noop, +}; +function syncFileFindingsWithFinalReport(files, findings) { + return files.map((file) => ({ + ...file, + findings: findings.filter((finding) => findingAppliesToFile(finding, file.filename)), + })); +} +/** Severity levels in display order. */ +const SEVERITY_LEVELS = (/* unused pure expression or super */ null && (['high', 'medium', 'low'])); +/** Print the per-file line within a skill summary. */ +function printFileSummary(file) { + if (file.status === 'done') { + const filename = truncate(file.filename, 50); + const counts = countBySeverity(file.findings); + let line = ` ${chalk.green(ICON_CHECK)} ${filename} ${chalk.dim(`[${file.totalHunks}/${file.totalHunks}]`)}`; + const severityParts = SEVERITY_LEVELS + .filter((s) => counts[s] > 0) + .map((s) => `${formatSeverityDot(s)} ${counts[s]}`); + if (severityParts.length > 0) + line += ` ${severityParts.join(' ')}`; + if (file.durationMs !== undefined) + line += chalk.dim(` ${formatDuration(file.durationMs)}`); + if (file.usage !== undefined) + line += chalk.dim(` ${formatCost(file.usage.costUSD)}`); + process.stderr.write(`${line}\n`); + } +} +/** Print the full skill + file breakdown to stderr after Ink unmounts. */ +function printSkillSummary(skillStates) { + for (const skill of skillStates) { + const duration = skill.durationMs ? chalk.dim(` [${formatDuration(skill.durationMs)}]`) : ''; + const cost = getSkillCostUSD(skill); + const costText = cost !== undefined && cost > 0 ? chalk.dim(` ${formatCost(cost)}`) : ''; + if (skill.status === 'done') { + process.stderr.write(`${chalk.green(ICON_CHECK)} ${skill.displayName}${duration}${costText}\n`); + } + else if (skill.status === 'skipped') { + process.stderr.write(`${chalk.yellow(ICON_SKIPPED)} ${skill.displayName} ${chalk.dim('[skipped]')}\n`); + } + else if (skill.status === 'error') { + process.stderr.write(`${chalk.red(ICON_ERROR)} ${skill.displayName}${duration}\n`); + if (skill.error) { + process.stderr.write(`${chalk.red(` Error: ${skill.error}`)}\n`); + } + } + if (skill.status === 'done' || skill.status === 'error') { + for (const file of skill.files) { + printFileSummary(file); + } + const skippedCount = skill.files.filter((f) => f.status === 'skipped').length; + if (skippedCount > 0) { + process.stderr.write(` ${chalk.dim(`${skippedCount} ${pluralize(skippedCount, 'file')} skipped`)}\n`); + } + } + } +} +/** + * Run skill tasks with Ink-based real-time progress display. + */ +async function runSkillTasksWithInk(tasks, options) { + const { verbosity, concurrency, failFastController, onSkillComplete: streamHook, onChunkComplete } = options; + const fireStreamHook = streamHook + ? (report) => { + try { + streamHook(report); + } + catch { /* streaming hook must not break the run */ } + } + : undefined; + if (tasks.length === 0 || verbosity === Verbosity.Quiet) { + // No tasks or quiet mode - run without UI using the global analysis queue. + const analysisQueue = new AsyncWorkQueue(concurrency); + const circuitAbortController = new AbortController(); + const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController: circuitAbortController }); + const composedTasks = composeTasksWithFailFast(tasks, failFastController, circuitBreaker, circuitAbortController); + const callbacks = { + ...noopCallbacks, + ...(fireStreamHook || failFastController + ? { + onSkillComplete: (name, report) => { + noopCallbacks.onSkillComplete(name, report); + fireStreamHook?.(report); + if (failFastController && report.findings.length > 0) { + failFastController.abort(); + } + }, + } + : {}), + ...(onChunkComplete + ? { + onChunkComplete: (name, chunk) => { + noopCallbacks.onChunkComplete?.(name, chunk); + try { + onChunkComplete(name, chunk); + } + catch { /* streaming hook must not break the run */ } + }, + } + : {}), + }; + return runComposedSkillTasks(composedTasks, callbacks, analysisQueue); + } + // Track skill states + const skillStates = []; + // Warnings are rendered via Ink's Static component so they appear above the + // dynamic spinner area without corrupting it. + const warnings = []; + // Track interrupt state for rendering in the Ink component + let interrupted = false; + let failFastTriggered = false; + process.stderr.write(`${chalk.bold('SKILLS')}\n`); + // Create Ink instance + const { rerender, unmount, clear } = render(_jsx(SkillRunner, { skills: skillStates, warnings: [], interrupted: false, failFastTriggered: false }), { stdout: process.stderr }); + // Batch UI updates to prevent rapid consecutive rerenders that cause duplicate lines. + // Without batching, multiple callbacks firing in quick succession (e.g., 5 files + // starting simultaneously) trigger 5 immediate rerenders, which Ink cannot + // process correctly, resulting in the same line appearing multiple times. + let updatePending = false; + let unmounted = false; + const updateUI = () => { + if (updatePending || unmounted) + return; + updatePending = true; + setImmediate(() => { + updatePending = false; + if (unmounted) + return; + rerender(_jsx(SkillRunner, { skills: [...skillStates], warnings: [...warnings], interrupted: interrupted, failFastTriggered: failFastTriggered })); + }); + }; + // Listen for abort signal to show interrupt message in the Ink UI + const abortSignal = tasks[0]?.runnerOptions?.abortController?.signal; + if (abortSignal && !abortSignal.aborted) { + abortSignal.addEventListener('abort', () => { + // Only show interrupt message for user SIGINT, not fail-fast + if (!failFastController?.signal.aborted) { + interrupted = true; + updateUI(); + } + }, { once: true }); + } + // Show fail-fast message when triggered + if (failFastController) { + failFastController.signal.addEventListener('abort', () => { + failFastTriggered = true; + updateUI(); + }, { once: true }); + } + // Callbacks to update state + const callbacks = { + onSkillStart: (skill) => { + skillStates.push(skill); + updateUI(); + }, + onSkillUpdate: (name, updates) => { + const idx = skillStates.findIndex((s) => s.name === name); + const existing = skillStates[idx]; + if (idx >= 0 && existing) { + const next = { ...existing, ...updates }; + if (updates.findings !== undefined) { + next.files = syncFileFindingsWithFinalReport(next.files, updates.findings); + } + skillStates[idx] = next; + updateUI(); + } + }, + onFileUpdate: (skillName, filename, updates) => { + const skill = skillStates.find((s) => s.name === skillName); + if (skill) { + const file = skill.files.find((f) => f.filename === filename); + if (file) { + Object.assign(file, updates); + updateUI(); + } + } + }, + onSkillComplete: (name, report) => { + fireStreamHook?.(report); + const idx = skillStates.findIndex((s) => s.name === name); + const existing = skillStates[idx]; + if (idx >= 0 && existing) { + skillStates[idx] = { + ...existing, + status: existing.status === 'error' || existing.status === 'skipped' ? existing.status : 'done', + durationMs: report.durationMs, + findings: report.findings, + usage: report.usage, + auxiliaryUsage: report.auxiliaryUsage, + files: syncFileFindingsWithFinalReport(existing.files, report.findings), + }; + } + if (failFastController && report.findings.length > 0) { + failFastController.abort(); + } + updateUI(); + }, + onChunkComplete: (name, chunk) => { + try { + onChunkComplete?.(name, chunk); + } + catch { /* streaming hook must not break the run */ } + }, + onSkillSkipped: (name) => { + skillStates.push(makeTerminalSkillState(tasks, name, { status: 'skipped' })); + updateUI(); + }, + onSkillError: (name, error) => { + const idx = skillStates.findIndex((s) => s.name === name); + const existing = skillStates[idx]; + if (idx >= 0 && existing) { + skillStates[idx] = { ...existing, status: 'error', error }; + } + else { + skillStates.push(makeTerminalSkillState(tasks, name, { status: 'error', error })); + } + updateUI(); + }, + onLargePrompt: (_skillName, filename, lineRange, chars, estimatedTokens) => { + const location = `${filename}:${lineRange}`; + const size = `${Math.round(chars / 1000)}k chars (~${Math.round(estimatedTokens / 1000)}k tokens)`; + warnings.push(`${chalk.yellow(figures.warning)} Large prompt for ${location}: ${size}`); + updateUI(); + }, + onPromptSize: verbosity >= Verbosity.Debug + ? (_skillName, filename, lineRange, systemChars, userChars, totalChars, estimatedTokens) => { + const location = `${filename}:${lineRange}`; + warnings.push(chalk.dim(`[debug] Prompt for ${location}: system=${systemChars}, user=${userChars}, total=${totalChars} chars (~${estimatedTokens} tokens)`)); + updateUI(); + } + : undefined, + onHunkFailed: verbosity >= Verbosity.Verbose + ? (_skillName, filename, lineRange, error) => { + const location = `${filename}:${lineRange}`; + warnings.push(`${chalk.yellow(figures.warning)} Chunk failed: ${location} ${chalk.dim(`\u2014 ${error}`)}`); + updateUI(); + } + : undefined, + onExtractionFailure: verbosity >= Verbosity.Verbose + ? (_skillName, filename, lineRange, error, preview) => { + const location = `${filename}:${lineRange}`; + warnings.push(`${chalk.yellow(figures.warning)} Extraction failed: ${location} ${chalk.dim(`\u2014 ${error}`)}`); + if (verbosity >= Verbosity.Debug && preview) { + warnings.push(chalk.dim(`[debug] Output preview: ${preview.slice(0, 200)}`)); + } + updateUI(); + } + : undefined, + onRetry: verbosity >= Verbosity.Verbose + ? (_skillName, filename, lineRange, attempt, maxRetries, error, delayMs) => { + const location = `${filename}:${lineRange}`; + const retryInfo = `attempt ${attempt}/${maxRetries}`; + const delay = delayMs > 0 ? `, retrying in ${Math.round(delayMs / 1000)}s` : ''; + warnings.push(chalk.dim(`[debug] Retry ${location} (${retryInfo}${delay}): ${error}`)); + updateUI(); + } + : undefined, + }; + const analysisQueue = new AsyncWorkQueue(concurrency); + // Compose per-task abort controllers: fire on SIGINT, fail-fast, or provider circuit breaker. + const circuitAbortController = new AbortController(); + const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController: circuitAbortController }); + const composedTasks = composeTasksWithFailFast(tasks, failFastController, circuitBreaker, circuitAbortController); + // Launch all skills in parallel; the queue is the sole concurrency gate. + const results = await runComposedSkillTasks(composedTasks, callbacks, analysisQueue); + // Flush any pending setImmediate from updateUI so last-tick warnings are + // rendered before we tear down. setImmediate is FIFO, so our callback runs + // after the queued rerender. + await new Promise((resolve) => setImmediate(resolve)); + unmounted = true; + clear(); + unmount(); + printSkillSummary(skillStates); + return results; +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 6743: +/***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => { + + +// UNUSED EXPORTS: JsonlChunkRecordSchema, JsonlFileRecordSchema, JsonlFixEvalDetailSchema, JsonlFixEvaluationRecordSchema, JsonlRecordSchema, JsonlRunMetadataSchema, JsonlSummaryRecordSchema, JsonlUsageBreakdownEntrySchema, JsonlUsageBreakdownSchema, MODEL_DEFAULT_SENTINEL, appendJsonlLine, auxiliaryUsageFromBreakdown, buildJsonlUsageBreakdown, buildRunMetadata, buildSkillJsonlRecord, buildSummaryJsonlRecord, generateRunId, getRepoLogPath, initJsonlFile, parseJsonlChunkRecord, parseJsonlReports, parseJsonlSummaryRecord, parseLogMetadata, readJsonlLog, renderJsonlChunkLine, renderJsonlChunkRecords, renderJsonlSkillLine, renderJsonlString, renderJsonlSummaryLine, scanUsageFromBreakdown, shortRunId, usageStatsHaveValue, writeJsonlContent, writeJsonlReport + +// EXTERNAL MODULE: external "node:fs" +var external_node_fs_ = __webpack_require__(73024); +// EXTERNAL MODULE: external "node:crypto" +var external_node_crypto_ = __webpack_require__(77598); +// EXTERNAL MODULE: external "node:path" +var external_node_path_ = __webpack_require__(76760); +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js + 7 modules +var schemas = __webpack_require__(51737); +// EXTERNAL MODULE: ./src/types/index.ts +var types = __webpack_require__(78481); +// EXTERNAL MODULE: ./src/sentry.ts +var sentry = __webpack_require__(30340); +// EXTERNAL MODULE: ./src/cli/output/formatters.ts +var formatters = __webpack_require__(43171); +;// CONCATENATED MODULE: ./src/cli/output/usage-breakdown.ts + + + +/** Usage plus model/runtime attribution for one billable JSONL component. */ +const JsonlUsageBreakdownEntrySchema = types/* UsageAttributionSchema */.o2.extend({ + usage: types/* UsageStatsSchema */.Ur, +}); +/** Detailed usage accounting for one durable JSONL record. */ +const JsonlUsageBreakdownSchema = schemas/* object */.Ikc({ + /** Primary hunk/scan usage for this record. */ + scan: JsonlUsageBreakdownEntrySchema.optional(), + /** Auxiliary agent usage, keyed by stage/agent name. */ + auxiliary: schemas/* record */.g1P(schemas/* string */.YjP(), JsonlUsageBreakdownEntrySchema).optional(), + /** Total usage for this record: scan plus all auxiliary agents. */ + total: JsonlUsageBreakdownEntrySchema, +}).superRefine((breakdown, ctx) => { + const hasScan = usageStatsHaveValue(breakdown.scan?.usage); + const hasAuxiliary = usageBreakdownEntriesHaveValue(breakdown.auxiliary); + if (!hasScan && !hasAuxiliary) { + ctx.addIssue({ + code: 'custom', + message: 'usageBreakdown requires scan or auxiliary usage', + }); + return; + } + const auxiliaryTotal = aggregateUsageBreakdownEntries(breakdown.auxiliary); + const expected = usage_breakdown_aggregateUsageStatsPreservingOptional([breakdown.scan?.usage, auxiliaryTotal].filter((usage) => usage !== undefined)); + if (!usageStatsMatch(breakdown.total.usage, expected)) { + ctx.addIssue({ + code: 'custom', + path: ['total', 'usage'], + message: 'usageBreakdown.total must equal scan plus auxiliary usage', + }); + } +}); +/** Return true when usage contains non-zero token, tool, or cost data. */ +function usageStatsHaveValue(usage) { + if (!usage) + return false; + return usage.inputTokens > 0 + || usage.outputTokens > 0 + || (usage.cacheReadInputTokens ?? 0) > 0 + || (usage.cacheCreationInputTokens ?? 0) > 0 + || (usage.cacheCreation5mInputTokens ?? 0) > 0 + || (usage.cacheCreation1hInputTokens ?? 0) > 0 + || (usage.webSearchRequests ?? 0) > 0 + || usage.costUSD > 0; +} +function auxiliaryUsageHasValue(auxiliaryUsage) { + if (!auxiliaryUsage) + return false; + return Object.values(auxiliaryUsage).some(usageStatsHaveValue); +} +function usageBreakdownEntriesHaveValue(entries) { + if (!entries) + return false; + return Object.values(entries).some((entry) => usageStatsHaveValue(entry.usage)); +} +function aggregateUsageBreakdownEntries(entries) { + if (!usageBreakdownEntriesHaveValue(entries)) + return undefined; + return usage_breakdown_aggregateUsageStatsPreservingOptional(Object.values(entries).map((entry) => entry.usage)); +} +/** Aggregate usage stats while avoiding optional zero fields unless inputs had them. */ +function usage_breakdown_aggregateUsageStatsPreservingOptional(usages) { + const total = { + inputTokens: 0, + outputTokens: 0, + costUSD: 0, + }; + for (const usage of usages) { + total.inputTokens += usage.inputTokens; + total.outputTokens += usage.outputTokens; + total.costUSD += usage.costUSD; + if (usage.cacheReadInputTokens !== undefined || total.cacheReadInputTokens !== undefined) { + total.cacheReadInputTokens = (total.cacheReadInputTokens ?? 0) + (usage.cacheReadInputTokens ?? 0); + } + if (usage.cacheCreationInputTokens !== undefined || total.cacheCreationInputTokens !== undefined) { + total.cacheCreationInputTokens = (total.cacheCreationInputTokens ?? 0) + (usage.cacheCreationInputTokens ?? 0); + } + if (usage.cacheCreation5mInputTokens !== undefined || total.cacheCreation5mInputTokens !== undefined) { + total.cacheCreation5mInputTokens = (total.cacheCreation5mInputTokens ?? 0) + (usage.cacheCreation5mInputTokens ?? 0); + } + if (usage.cacheCreation1hInputTokens !== undefined || total.cacheCreation1hInputTokens !== undefined) { + total.cacheCreation1hInputTokens = (total.cacheCreation1hInputTokens ?? 0) + (usage.cacheCreation1hInputTokens ?? 0); + } + if (usage.webSearchRequests !== undefined || total.webSearchRequests !== undefined) { + total.webSearchRequests = (total.webSearchRequests ?? 0) + (usage.webSearchRequests ?? 0); + } + } + return total; +} +function usageStatsMatch(actual, expected) { + return actual.inputTokens === expected.inputTokens + && actual.outputTokens === expected.outputTokens + && (actual.cacheReadInputTokens ?? 0) === (expected.cacheReadInputTokens ?? 0) + && (actual.cacheCreationInputTokens ?? 0) === (expected.cacheCreationInputTokens ?? 0) + && (actual.cacheCreation5mInputTokens ?? 0) === (expected.cacheCreation5mInputTokens ?? 0) + && (actual.cacheCreation1hInputTokens ?? 0) === (expected.cacheCreation1hInputTokens ?? 0) + && (actual.webSearchRequests ?? 0) === (expected.webSearchRequests ?? 0) + && Math.abs(actual.costUSD - expected.costUSD) < 0.000000001; +} +function uniqueSorted(values) { + const unique = [...new Set(values.filter((value) => Boolean(value)))].sort(); + return unique.length > 0 ? unique : undefined; +} +function attributionModels(attribution) { + return [ + ...(attribution?.model ? [attribution.model] : []), + ...(attribution?.models ?? []), + ]; +} +function attributionRuntimes(attribution) { + return [ + ...(attribution?.runtime ? [attribution.runtime] : []), + ...(attribution?.runtimes ?? []), + ]; +} +function buildUsageBreakdownEntry(usage, attribution) { + if (!usageStatsHaveValue(usage)) + return undefined; + return { + usage, + ...attribution, + }; +} +function buildAuxiliaryUsageBreakdownEntries(auxiliaryUsage, attribution) { + if (!auxiliaryUsageHasValue(auxiliaryUsage)) + return undefined; + const entries = {}; + for (const [agent, usage] of Object.entries(auxiliaryUsage)) { + const entry = buildUsageBreakdownEntry(usage, attribution?.[agent]); + if (entry) { + entries[agent] = entry; + } + } + return Object.keys(entries).length > 0 ? entries : undefined; +} +function buildTotalUsageBreakdownEntry(usage, scan, auxiliary) { + const componentAttributions = [ + scan, + ...Object.values(auxiliary ?? {}), + ]; + const models = uniqueSorted(componentAttributions.flatMap((entry) => attributionModels(entry))); + const runtimes = uniqueSorted(componentAttributions.flatMap((entry) => attributionRuntimes(entry))); + return { + usage, + model: models?.length === 1 ? models[0] : undefined, + models: models && models.length > 1 ? models : undefined, + runtime: runtimes?.length === 1 ? runtimes[0] : undefined, + runtimes: runtimes && runtimes.length > 1 ? runtimes : undefined, + }; +} +/** Build detailed usage accounting for a JSONL record. */ +function usage_breakdown_buildJsonlUsageBreakdown(usage, auxiliaryUsage, options = {}) { + const scan = buildUsageBreakdownEntry(usage, options.scan); + const auxiliary = buildAuxiliaryUsageBreakdownEntries(auxiliaryUsage, options.auxiliary); + if (!scan && !auxiliary) + return undefined; + const auxiliaryTotal = aggregateUsageBreakdownEntries(auxiliary); + const total = usage_breakdown_aggregateUsageStatsPreservingOptional([scan?.usage, auxiliaryTotal].filter((u) => u !== undefined)); + return { + scan, + auxiliary, + total: buildTotalUsageBreakdownEntry(total, scan, auxiliary), + }; +} +/** Return only the primary scan usage from a usage breakdown. */ +function usage_breakdown_scanUsageFromBreakdown(breakdown) { + return breakdown?.scan?.usage; +} +/** Return auxiliary usage from a usage breakdown in the legacy map shape. */ +function usage_breakdown_auxiliaryUsageFromBreakdown(breakdown) { + const auxiliary = breakdown?.auxiliary; + if (!auxiliary) + return undefined; + const usage = {}; + for (const [agent, entry] of Object.entries(auxiliary)) { + usage[agent] = entry.usage; + } + return Object.keys(usage).length > 0 ? usage : undefined; +} +/** Return auxiliary model/runtime attribution from a usage breakdown. */ +function usage_breakdown_auxiliaryUsageAttributionFromBreakdown(breakdown) { + const auxiliary = breakdown?.auxiliary; + if (!auxiliary) + return undefined; + const attribution = {}; + for (const [agent, entry] of Object.entries(auxiliary)) { + const { usage: _usage, ...entryAttribution } = entry; + if (Object.keys(entryAttribution).length > 0) { + attribution[agent] = entryAttribution; + } + } + return Object.keys(attribution).length > 0 ? attribution : undefined; +} +/** Aggregate model/runtime attribution across scan reports. */ +function usage_breakdown_usageAttributionFromReports(reports) { + const models = uniqueSorted(reports.map((report) => report.model)); + const runtimes = uniqueSorted(reports.map((report) => report.runtime)); + if (!models && !runtimes) + return undefined; + return { + model: models?.length === 1 ? models[0] : undefined, + models: models && models.length > 1 ? models : undefined, + runtime: runtimes?.length === 1 ? runtimes[0] : undefined, + runtimes: runtimes && runtimes.length > 1 ? runtimes : undefined, + }; +} +/** Aggregate auxiliary model/runtime attribution across reports. */ +function usage_breakdown_aggregateReportAuxiliaryUsageAttribution(reports) { + return reports.reduce((acc, report) => mergeAuxiliaryUsageAttribution(acc, report.auxiliaryUsageAttribution), undefined); +} + +;// CONCATENATED MODULE: ./src/cli/output/jsonl.ts + + + + + + + + + + +/** + * Sentinel value recorded in JSONL metadata when no model is explicitly configured. + */ +const MODEL_DEFAULT_SENTINEL = '(default)'; +/** + * Generate a unique run ID for this execution. + */ +function generateRunId() { + return randomUUID(); +} +/** + * Get the first 8 hex chars (no dashes) of a UUID for use in filenames. + */ +function shortRunId(runId) { + return runId.replace(/-/g, '').slice(0, 8); +} +/** + * Get the repo-local log file path. + * Returns: {repoRoot}/.warden/logs/{runId8}-{ISO-datetime}.jsonl + */ +function getRepoLogPath(repoRoot, runId, timestamp = new Date()) { + const ts = timestamp.toISOString().replace(/[:.]/g, '-'); + return join(repoRoot, '.warden', 'logs', `${shortRunId(runId)}-${ts}.jsonl`); +} +/** + * JSONL record schemas for Warden's structured run output. + * + * Formal JSON Schema: specs/jsonl-schema.json + * Example payloads: specs/jsonl-examples.jsonl + * Reporter spec: specs/reporters.md Section 3 "JSONL Specification" + * + * BACKWARD COMPATIBILITY: breaking on-disk JSONL log formats is NEVER + * ALLOWED. Users keep .warden/logs/*.jsonl across versions. The schema + * may evolve — new optional fields, additive enum values, normalization + * — but every historical shape must continue to parse cleanly. Field + * renames require a preprocess that maps the old name to the new one + * (see FileReportSchema's `findingCount → findings` preprocess in + * src/types/index.ts). Removing a field is fine; making it optional in + * the schema preserves old logs. If you can't reconcile an old shape + * with a preprocess, the change is wrong — find a different path. + */ +/** Metadata common to every JSONL record. */ +const JsonlRunMetadataSchema = schemas/* object */.Ikc({ + timestamp: schemas/* string */.YjP().datetime(), + durationMs: schemas/* number */.aig().nonnegative(), + cwd: schemas/* string */.YjP(), + runId: schemas/* string */.YjP(), + traceId: schemas/* string */.YjP().optional(), + model: schemas/* string */.YjP().optional(), + headSha: schemas/* string */.YjP().optional(), +}); +/** Per-file breakdown within a skill record (re-exported from shared types). */ +const JsonlFileRecordSchema = (/* unused pure expression or super */ null && (FileReportSchema)); +/** Unit of work scanned by Warden, emitted during streaming and finalization. */ +const JsonlChunkRecordSchema = schemas/* object */.Ikc({ + schemaVersion: schemas/* literal */.euz(1), + run: JsonlRunMetadataSchema, + skill: schemas/* string */.YjP(), + model: schemas/* string */.YjP().optional(), + chunk: schemas/* object */.Ikc({ + file: schemas/* string */.YjP(), + index: schemas/* number */.aig().int().positive(), + total: schemas/* number */.aig().int().positive(), + lineRange: schemas/* string */.YjP(), + }), + status: schemas/* enum */.k5n(['ok', 'error', 'skipped']), + findings: schemas/* array */.YOg(types/* FindingSchema */.p_), + usageBreakdown: JsonlUsageBreakdownSchema.optional(), + durationMs: schemas/* number */.aig().nonnegative(), + error: types/* SkillErrorSchema */.J1.optional(), + skippedFiles: schemas/* array */.YOg(types/* SkippedFileSchema */.AU).optional(), + trace: types/* HunkTraceSchema */.Ne.optional(), + verifierRejections: types/* VerifierRejectionsSchema */.IH.optional(), +}); +const JsonlLegacyChunkRecordSchema = JsonlChunkRecordSchema.extend({ + usage: types/* UsageStatsSchema */.Ur.optional(), + auxiliaryUsage: types/* AuxiliaryUsageMapSchema */.xb.optional(), +}); +function normalizeChunkRecord(record) { + const { usage, auxiliaryUsage, ...chunk } = record; + return { + ...chunk, + usageBreakdown: chunk.usageBreakdown ?? buildJsonlUsageBreakdown(usage, auxiliaryUsage, { + scan: { model: chunk.model }, + }), + }; +} +function parseJsonlChunkRecord(value) { + const result = JsonlLegacyChunkRecordSchema.safeParse(value); + return result.success ? normalizeChunkRecord(result.data) : undefined; +} +/** + * One skill's analysis results. This is the shared SkillReport plus a `run` + * block of run-wide metadata, so any new SkillReport field is automatically + * part of the JSONL contract without a parallel schema. + */ +const JsonlRecordSchema = types/* SkillReportSchema */.r6.extend({ + run: JsonlRunMetadataSchema, + usageBreakdown: JsonlUsageBreakdownSchema.optional(), +}); +/** Normalized output shape — what we emit. */ +const BySeverityOutputSchema = schemas/* object */.Ikc({ + high: schemas/* number */.aig().int().nonnegative(), + medium: schemas/* number */.aig().int().nonnegative(), + low: schemas/* number */.aig().int().nonnegative(), +}); +/** + * Severity breakdown in the summary record. + * + * Parse-time accepts any string keys (legacy logs may emit 5-level severities + * like 'critical'/'info'); a transform normalizes 'critical' → 'high' and + * 'info' → 'low' and drops unknown keys. The piped output shape is the + * strict `{ high, medium, low }` triple we emit going forward, so + * JSON-Schema derivation describes the output contract (not the lax input). + */ +const BySeveritySchema = schemas/* record */.g1P(schemas/* string */.YjP(), schemas/* number */.aig().int().nonnegative()) + .transform((obj) => { + const result = { high: 0, medium: 0, low: 0 }; + for (const [key, value] of Object.entries(obj)) { + const normalized = key === 'critical' ? 'high' : key === 'info' ? 'low' : key; + if (normalized === 'high' || normalized === 'medium' || normalized === 'low') { + result[normalized] += value; + } + } + return result; +}) + .pipe(BySeverityOutputSchema); +/** Aggregate summary across all skills (always the last JSONL line). */ +const JsonlSummaryRecordSchema = schemas/* object */.Ikc({ + run: JsonlRunMetadataSchema, + type: schemas/* literal */.euz('summary'), + totalFindings: schemas/* number */.aig().int().nonnegative(), + bySeverity: BySeveritySchema, + usageBreakdown: JsonlUsageBreakdownSchema.optional(), + totalSkippedFiles: schemas/* number */.aig().int().nonnegative().optional(), + failedSkills: schemas/* array */.YOg(schemas/* string */.YjP()).optional(), + totalFailedHunks: schemas/* number */.aig().int().nonnegative().optional(), + totalFailedExtractions: schemas/* number */.aig().int().nonnegative().optional(), + totalVerifierRejections: schemas/* number */.aig().int().nonnegative().optional(), + /** + * Top-level run error captured before any skill ran (e.g. auth failure, + * config load error). Skill-level errors live on the SkillRecord; this + * is for failures that prevent the per-skill loop from starting. + */ + error: types/* SkillErrorSchema */.J1.optional(), +}); +const JsonlLegacySummaryRecordSchema = JsonlSummaryRecordSchema.extend({ + usage: types/* UsageStatsSchema */.Ur.optional(), + auxiliaryUsage: types/* AuxiliaryUsageMapSchema */.xb.optional(), +}); +function normalizeSummaryRecord(record) { + const { usage, auxiliaryUsage, ...summary } = record; + return { + ...summary, + usageBreakdown: summary.usageBreakdown ?? buildJsonlUsageBreakdown(usage, auxiliaryUsage), + }; +} +function parseJsonlSummaryRecord(value) { + const result = JsonlLegacySummaryRecordSchema.safeParse(value); + return result.success ? normalizeSummaryRecord(result.data) : undefined; +} +/** Per-evaluation detail for fix evaluation records. */ +const JsonlFixEvalDetailSchema = schemas/* object */.Ikc({ + path: schemas/* string */.YjP(), + line: schemas/* number */.aig().int().positive(), + findingId: schemas/* string */.YjP().optional(), + verdict: schemas/* union */.KCZ([types/* FixStatusSchema */.$3, schemas/* literal */.euz('re_detected'), schemas/* literal */.euz('eval_error')]), + reasoning: schemas/* string */.YjP().optional(), + durationMs: schemas/* number */.aig().nonnegative(), + usage: types/* UsageStatsSchema */.Ur, + usedFallback: schemas/* boolean */.zMY().optional(), +}); +/** Fix evaluation results record. */ +const JsonlFixEvaluationRecordSchema = schemas/* object */.Ikc({ + run: JsonlRunMetadataSchema, + type: schemas/* literal */.euz('fix-evaluation'), + evaluated: schemas/* number */.aig().int().nonnegative(), + resolved: schemas/* number */.aig().int().nonnegative(), + needsAttention: schemas/* number */.aig().int().nonnegative(), + skipped: schemas/* number */.aig().int().nonnegative(), + failedEvaluations: schemas/* number */.aig().int().nonnegative(), + usage: types/* UsageStatsSchema */.Ur.optional(), + evaluations: schemas/* array */.YOg(JsonlFixEvalDetailSchema).optional(), +}); +/** + * Aggregate usage stats from reports. + */ +function aggregateUsage(reports) { + const usages = reports.map((r) => r.usage).filter((u) => u !== undefined); + if (usages.length === 0) + return undefined; + return aggregateUsageStatsPreservingOptional(usages); +} +/** + * Build a JSONL run metadata block. `durationMs` is a snapshot at write + * time for skill records, the run total on the trailing summary record. + */ +function buildRunMetadata(options) { + return { + timestamp: (options.timestamp ?? new Date()).toISOString(), + durationMs: options.durationMs, + cwd: options.cwd ?? process.cwd(), + runId: options.runId, + traceId: options.traceId, + model: options.model, + headSha: options.headSha, + }; +} +/** Build a skill JSONL record, dropping zero-valued optional fields. */ +function buildSkillJsonlRecord(report, run) { + const trimmed = { + ...report, + skippedFiles: report.skippedFiles?.length ? report.skippedFiles : undefined, + failedHunks: report.failedHunks || undefined, + failedExtractions: report.failedExtractions || undefined, + hunkFailures: report.hunkFailures?.length ? report.hunkFailures : undefined, + traces: report.traces?.length ? report.traces : undefined, + }; + return { + ...trimmed, + run, + usageBreakdown: buildJsonlUsageBreakdown(report.usage, report.auxiliaryUsage, { + scan: { model: report.model, runtime: report.runtime }, + auxiliary: report.auxiliaryUsageAttribution, + }), + }; +} +/** Build the aggregate summary JSONL record. */ +function buildSummaryJsonlRecord(reports, run, error) { + const allFindings = reports.flatMap((r) => r.findings); + const totalSkippedFiles = reports.reduce((n, r) => n + (r.skippedFiles?.length ?? 0), 0); + const totalAuxiliaryUsage = reports.reduce((acc, r) => mergeAuxiliaryUsage(acc, r.auxiliaryUsage), undefined); + const totalAuxiliaryUsageAttribution = aggregateReportAuxiliaryUsageAttribution(reports); + const usage = aggregateUsage(reports); + const failedSkills = reports.filter((r) => r.error).map((r) => r.skill); + const totalFailedHunks = reports.reduce((n, r) => n + (r.failedHunks ?? 0), 0); + const totalFailedExtractions = reports.reduce((n, r) => n + (r.failedExtractions ?? 0), 0); + const totalVerifierRejections = reports.reduce((n, r) => n + (r.verifierRejections?.count ?? 0), 0); + return { + run, + type: 'summary', + totalFindings: allFindings.length, + bySeverity: countBySeverity(allFindings), + usageBreakdown: buildJsonlUsageBreakdown(usage, totalAuxiliaryUsage, { + scan: usageAttributionFromReports(reports), + auxiliary: totalAuxiliaryUsageAttribution, + }), + totalSkippedFiles: totalSkippedFiles > 0 ? totalSkippedFiles : undefined, + failedSkills: failedSkills.length > 0 ? failedSkills : undefined, + totalFailedHunks: totalFailedHunks > 0 ? totalFailedHunks : undefined, + totalFailedExtractions: totalFailedExtractions > 0 ? totalFailedExtractions : undefined, + totalVerifierRejections: totalVerifierRejections > 0 ? totalVerifierRejections : undefined, + error, + }; +} +/** Render a single skill JSONL record as one line including trailing newline. */ +function renderJsonlSkillLine(report, run) { + return JSON.stringify(buildSkillJsonlRecord(report, run)) + '\n'; +} +/** Render the summary JSONL record as one line including trailing newline. */ +function renderJsonlSummaryLine(reports, run, error) { + return JSON.stringify(buildSummaryJsonlRecord(reports, run, error)) + '\n'; +} +/** Render one chunk result record as one JSONL line. */ +function renderJsonlChunkLine(record) { + return JSON.stringify(JsonlChunkRecordSchema.parse(record)) + '\n'; +} +function renderJsonlChunkRecords(records) { + return records.map((record) => renderJsonlChunkLine(record)).join(''); +} +/** Create parent dirs and truncate the file to empty. */ +function initJsonlFile(outputPath) { + const resolvedPath = resolve(process.cwd(), outputPath); + mkdirSync(dirname(resolvedPath), { recursive: true }); + writeFileSync(resolvedPath, ''); +} +/** + * Append a pre-rendered line (must include its trailing newline). + * This uses one synchronous append call so parallel skill callbacks in this + * process cannot interleave partial JSON records. + */ +function appendJsonlLine(outputPath, line) { + const resolvedPath = resolve(process.cwd(), outputPath); + mkdirSync(dirname(resolvedPath), { recursive: true }); + appendFileSync(resolvedPath, line); +} +/** + * Render skill reports as a JSONL string. + * Each line contains one skill report with run metadata. + * A final summary line is appended at the end. + */ +function renderJsonlString(reports, durationMs, options) { + const runMetadata = buildRunMetadata({ + runId: options?.runId ?? generateRunId(), + durationMs, + timestamp: options?.timestamp, + traceId: options?.traceId, + model: options?.model, + headSha: options?.headSha, + cwd: options?.cwd, + }); + const lines = []; + for (const report of reports) { + lines.push(JSON.stringify(buildSkillJsonlRecord(report, runMetadata))); + } + lines.push(JSON.stringify(buildSummaryJsonlRecord(reports, runMetadata, options?.error))); + return lines.join('\n') + '\n'; +} +/** + * Write skill reports to a JSONL file. + */ +function writeJsonlReport(outputPath, reports, durationMs, options) { + const resolvedPath = resolve(process.cwd(), outputPath); + const content = renderJsonlString(reports, durationMs, options); + mkdirSync(dirname(resolvedPath), { recursive: true }); + writeFileSync(resolvedPath, content); +} +/** + * Write pre-rendered JSONL content to a file path. + */ +function writeJsonlContent(outputPath, content) { + const resolvedPath = resolve(process.cwd(), outputPath); + mkdirSync(dirname(resolvedPath), { recursive: true }); + writeFileSync(resolvedPath, content); +} +/** + * Read a JSONL log file and return its contents. + */ +function readJsonlLog(logPath) { + return readFileSync(logPath, 'utf-8'); +} +function summarizeFindings(skill, findings) { + if (findings.length === 0) + return `${skill}: No issues found`; + const counts = countBySeverity(findings); + const parts = [ + counts.high ? `${counts.high} high` : undefined, + counts.medium ? `${counts.medium} medium` : undefined, + counts.low ? `${counts.low} low` : undefined, + ].filter(Boolean); + return `${skill}: Found ${findings.length} ${findings.length === 1 ? 'issue' : 'issues'} (${parts.join(', ')})`; +} +function addUsage(a, b) { + if (!a) + return b; + if (!b) + return a; + return { + inputTokens: a.inputTokens + b.inputTokens, + outputTokens: a.outputTokens + b.outputTokens, + cacheReadInputTokens: (a.cacheReadInputTokens ?? 0) + (b.cacheReadInputTokens ?? 0), + cacheCreationInputTokens: (a.cacheCreationInputTokens ?? 0) + (b.cacheCreationInputTokens ?? 0), + cacheCreation5mInputTokens: (a.cacheCreation5mInputTokens ?? 0) + (b.cacheCreation5mInputTokens ?? 0), + cacheCreation1hInputTokens: (a.cacheCreation1hInputTokens ?? 0) + (b.cacheCreation1hInputTokens ?? 0), + webSearchRequests: (a.webSearchRequests ?? 0) + (b.webSearchRequests ?? 0), + costUSD: a.costUSD + b.costUSD, + }; +} +function reportsFromChunks(chunks) { + const bySkill = new Map(); + for (const chunk of chunks) { + const records = bySkill.get(chunk.skill) ?? []; + records.push(chunk); + bySkill.set(chunk.skill, records); + } + const reports = []; + for (const [skill, records] of bySkill) { + const reportLevelError = records.find(isReportLevelErrorRecord)?.error; + const chunkRecords = records.filter((record) => !isReportLevelErrorRecord(record)); + const analysisChunkRecords = chunkRecords.filter(isAnalysisChunkRecord); + const aggregateRecords = chunkRecords.length > 0 ? chunkRecords : records; + const findings = aggregateRecords.flatMap((r) => r.findings); + const usage = aggregateRecords.reduce((acc, r) => addUsage(acc, scanUsageFromBreakdown(r.usageBreakdown)), undefined); + const auxiliaryUsage = aggregateRecords.reduce((acc, r) => mergeAuxiliaryUsage(acc, auxiliaryUsageFromBreakdown(r.usageBreakdown)), undefined); + const auxiliaryUsageAttribution = aggregateRecords.reduce((acc, r) => mergeAuxiliaryUsageAttribution(acc, auxiliaryUsageAttributionFromBreakdown(r.usageBreakdown)), undefined); + const traces = aggregateRecords.flatMap((r) => r.trace ? [r.trace] : []); + const filesByName = new Map(); + const hunkFailures = []; + const skippedFiles = records.flatMap((r) => r.skippedFiles ?? []); + for (const record of aggregateRecords) { + const existing = filesByName.get(record.chunk.file); + if (record.chunk.file) { + filesByName.set(record.chunk.file, { + filename: record.chunk.file, + findings: (existing?.findings ?? 0) + record.findings.length, + durationMs: (existing?.durationMs ?? 0) + record.durationMs, + usage: addUsage(existing?.usage, scanUsageFromBreakdown(record.usageBreakdown)), + }); + } + if (record.status === 'error' && record.error && !isReportLevelErrorRecord(record)) { + hunkFailures.push({ + type: isExtractionErrorCode(record.error.code) ? 'extraction' : 'analysis', + filename: record.chunk.file, + lineRange: record.chunk.lineRange, + code: record.error.code, + message: record.error.message, + }); + } + } + const failedHunks = analysisChunkRecords.filter((r) => r.status === 'error' && r.error && !isExtractionErrorCode(r.error.code)).length; + const failedExtractions = analysisChunkRecords.filter((r) => r.status === 'error' && r.error && isExtractionErrorCode(r.error.code)).length; + const verifierRejections = aggregateRecords.find((r) => r.verifierRejections)?.verifierRejections; + const allChunksFailed = analysisChunkRecords.length > 0 && + findings.length === 0 && + analysisChunkRecords.every((record) => record.status === 'error'); + const report = { + skill, + summary: summarizeFindings(skill, findings), + findings, + durationMs: aggregateRecords.reduce((sum, r) => sum + r.durationMs, 0), + usage, + files: [...filesByName.values()], + model: aggregateRecords.find((r) => r.model)?.model, + }; + if (reportLevelError) { + report.error = reportLevelError; + } + else if (allChunksFailed) { + report.error = { + code: 'all_hunks_failed', + message: `All ${analysisChunkRecords.length} ${analysisChunkRecords.length === 1 ? 'chunk' : 'chunks'} failed to analyze.`, + }; + } + if (auxiliaryUsage) + report.auxiliaryUsage = auxiliaryUsage; + if (auxiliaryUsageAttribution) + report.auxiliaryUsageAttribution = auxiliaryUsageAttribution; + if (failedHunks > 0) + report.failedHunks = failedHunks; + if (failedExtractions > 0) + report.failedExtractions = failedExtractions; + if (verifierRejections) + report.verifierRejections = verifierRejections; + if (hunkFailures.length > 0) + report.hunkFailures = hunkFailures; + if (traces.length > 0) + report.traces = traces; + if (skippedFiles.length > 0) + report.skippedFiles = skippedFiles; + reports.push(report); + } + return reports; +} +function isReportLevelErrorRecord(record) { + return record.status === 'error' && record.chunk.file === '' && Boolean(record.error); +} +function isUsageOnlyPostProcessingRecord(record) { + return record.chunk.file === '' && record.chunk.lineRange === 'post-processing'; +} +function isSkippedFilesMetadataRecord(record) { + return record.status === 'skipped' && record.chunk.lineRange === '' && (record.skippedFiles?.length ?? 0) > 0; +} +function isAnalysisChunkRecord(record) { + return !isUsageOnlyPostProcessingRecord(record) && !isSkippedFilesMetadataRecord(record); +} +function parseJsonlReports(content) { + const lines = content.trim().split('\n').filter((line) => line.trim()); + const reports = []; + const chunks = []; + let runMetadata; + let totalDurationMs = 0; + for (const line of lines) { + try { + const parsed = JSON.parse(line); + const chunk = parseJsonlChunkRecord(parsed); + if (chunk) { + chunks.push(chunk); + if (!runMetadata) + runMetadata = chunk.run; + totalDurationMs = Math.max(totalDurationMs, chunk.run.durationMs); + continue; + } + // Skip summary record (but capture metadata from it) + if (parsed.type === 'summary') { + const summary = parseJsonlSummaryRecord(parsed); + if (!summary) + throw new Error('Invalid summary record'); + runMetadata = summary.run; + totalDurationMs = summary.run.durationMs; + continue; + } + // Fix-evaluation records are valid JSONL but not SkillReports; let + // them pass through silently so we don't warn on every line of a log + // that contains them. + if (parsed.type === 'fix-evaluation') + continue; + // A JsonlRecord is a SkillReport + { run }. Strip `run` to get the + // SkillReport without rebuilding it field-by-field. + const { run, usageBreakdown: _usageBreakdown, ...report } = JsonlRecordSchema.parse(parsed); + reports.push(report); + // Capture run metadata from first record if no summary yet + if (!runMetadata) { + runMetadata = run; + totalDurationMs = run.durationMs; + } + } + catch (err) { + logger.warn('Skipping malformed JSONL line', { + error: err instanceof Error ? err.message : String(err), + }); + } + } + return { reports: [...reports, ...reportsFromChunks(chunks)], runMetadata, totalDurationMs }; +} +/** + * Parse a JSONL log file's summary, skill names, and high-level metadata. + * Returns undefined when the file can't be read or contains no parseable + * records; in-progress files (valid records but no summary yet) return + * metadata with `inProgress: true`. + */ +function parseLogMetadata(filePath) { + let content; + try { + content = readFileSync(filePath, 'utf-8'); + } + catch { + return undefined; + } + const lines = content.trim().split('\n').filter((l) => l.trim()); + let summary; + let firstRun; + const skills = []; + let model; + let headSha; + const uniqueFiles = new Set(); + const chunks = []; + let recognizedRecords = 0; + for (const line of lines) { + try { + const parsed = JSON.parse(line); + const chunk = parseJsonlChunkRecord(parsed); + if (chunk) { + chunks.push(chunk); + recognizedRecords++; + if (!skills.includes(chunk.skill)) { + skills.push(chunk.skill); + } + if (!model && chunk.model) { + model = chunk.model; + } + if (!model && chunk.run.model) { + model = chunk.run.model; + } + if (!headSha && chunk.run.headSha) { + headSha = chunk.run.headSha; + } + if (!firstRun) + firstRun = chunk.run; + if (chunk.chunk.file) { + uniqueFiles.add(chunk.chunk.file); + } + } + else if (parsed.type === 'summary') { + const parsedSummary = parseJsonlSummaryRecord(parsed); + if (!parsedSummary) + throw new Error('Invalid summary record'); + summary = parsedSummary; + recognizedRecords++; + if (!model && parsed.run?.model && typeof parsed.run.model === 'string') { + model = parsed.run.model; + } + if (!headSha && parsed.run?.headSha && typeof parsed.run.headSha === 'string') { + headSha = parsed.run.headSha; + } + if (!firstRun) + firstRun = summary.run; + } + else if (parsed.skill && typeof parsed.skill === 'string') { + recognizedRecords++; + if (!skills.includes(parsed.skill)) { + skills.push(parsed.skill); + } + if (!model && parsed.run?.model && typeof parsed.run.model === 'string') { + model = parsed.run.model; + } + if (!headSha && parsed.run?.headSha && typeof parsed.run.headSha === 'string') { + headSha = parsed.run.headSha; + } + if (!firstRun && parsed.run) { + const runResult = JsonlRunMetadataSchema.safeParse(parsed.run); + if (runResult.success) + firstRun = runResult.data; + } + if (Array.isArray(parsed.files)) { + for (const f of parsed.files) { + if (f && typeof f.filename === 'string') { + uniqueFiles.add(f.filename); + } + } + } + } + } + catch (err) { + logger.warn('Skipping malformed JSONL line', { + error: err instanceof Error ? err.message : String(err), + }); + } + } + // Empty or fully corrupt files (no parseable records) surface as + // "parse error" in the list, not as in-progress runs. + if (recognizedRecords === 0 && lines.length > 0) + return undefined; + if (!summary && chunks.length > 0) { + const reports = reportsFromChunks(chunks); + const lastDuration = chunks.reduce((max, chunk) => Math.max(max, chunk.run.durationMs), 0); + const firstChunk = chunks[0]; + if (!firstChunk) + return undefined; + const run = { ...(firstRun ?? firstChunk.run), durationMs: lastDuration }; + summary = buildSummaryJsonlRecord(reports, run); + } + return { + summary, + inProgress: chunks.length > 0 ? !existsSync(`${filePath}.done`) : !summary && !existsSync(`${filePath}.done`), + runMetadata: summary?.run ?? firstRun, + skills, + model, + headSha, + totalFiles: uniqueFiles.size, + }; +} + + +/***/ }), + +/***/ 34593: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* unused harmony export Reporter */ +/* harmony import */ var _verbosity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21307); +/* harmony import */ var _formatters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(43171); +/* harmony import */ var _box_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8899); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82272); + + + + + + + + + +/** + * Map a file change status to its single-character symbol. + */ +function statusSymbol(status) { + if (status === 'added') + return '+'; + if (status === 'removed') + return '-'; + return '~'; +} +/** + * Map a file change status to a colored symbol for TTY output. + */ +function coloredStatusSymbol(status) { + const sym = statusSymbol(status); + if (status === 'added') + return chalk.green(sym); + if (status === 'removed') + return chalk.red(sym); + return chalk.yellow(sym); +} +/** + * ASCII art logo for TTY header. + */ +const LOGO = ` + __ __ _ +/ / /\\ \\ \\__ _ _ __ __| | ___ _ __ +\\ \\/ \\/ / _\` | '__/ _\` |/ _ \\ '_ \\ + \\ /\\ / (_| | | | (_| | __/ | | | + \\/ \\/ \\__,_|_| \\__,_|\\___|_| |_| +`.replace(/^\n/, ''); +/** + * Main reporter class for CLI output. + * Handles different verbosity levels and TTY/non-TTY modes. + * + * Reporter spec: specs/reporters.md + */ +class Reporter { + mode; + verbosity; + constructor(mode, verbosity) { + this.mode = mode; + this.verbosity = verbosity; + } + /** + * Output to stderr (status messages). + */ + log(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + console.error(message); + } + /** + * Output to stderr with timestamp (plain/log mode). + */ + logPlain(message) { + console.error(`[${timestamp()}] warden: ${message}`); + } + /** + * Print the header with logo and version. + */ + header() { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(''); + for (const line of LOGO.split('\n')) { + this.log(chalk.dim(line)); + } + this.log(chalk.dim(`v${getVersion()}`)); + this.log(''); + } + else { + this.logPlain(`Warden v${getVersion()}`); + } + } + /** + * Start the context section (e.g., "Analyzing changes from HEAD~3...") + */ + startContext(description) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.dim(description)); + this.log(''); + } + else { + this.logPlain(description); + } + } + /** + * Display the list of files being analyzed. + */ + contextFiles(files) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + const totalChunks = files.reduce((sum, f) => sum + (f.chunks ?? 0), 0); + const displayFiles = files.slice(0, 10); + if (this.mode.isTTY) { + this.log(chalk.bold('FILES') + + chalk.cyan(` ${files.length} files`) + + chalk.dim(` · ${totalChunks} chunks`)); + for (const file of displayFiles) { + const chunkInfo = file.chunks ? chalk.dim(` (${file.chunks} ${pluralize(file.chunks, 'chunk')})`) : ''; + this.log(` ${coloredStatusSymbol(file.status)} ${file.filename}${chunkInfo}`); + } + if (files.length > 10) { + this.log(chalk.dim(` ... and ${files.length - 10} more`)); + } + this.log(''); + } + else { + this.logPlain(`Found ${files.length} changed files with ${totalChunks} chunks`); + for (const file of displayFiles) { + const chunkInfo = file.chunks ? ` (${file.chunks} ${pluralize(file.chunks, 'chunk')})` : ''; + this.logPlain(` ${statusSymbol(file.status)} ${file.filename}${chunkInfo}`); + } + if (files.length > 10) { + this.logPlain(` ... and ${files.length - 10} more`); + } + } + } + /** + * Aggregate usage stats from multiple reports. + */ + aggregateUsage(reports) { + const usages = reports.map((r) => r.usage).filter((u) => u !== undefined); + if (usages.length === 0) + return undefined; + return usages.reduce((acc, u) => ({ + inputTokens: acc.inputTokens + u.inputTokens, + outputTokens: acc.outputTokens + u.outputTokens, + cacheReadInputTokens: (acc.cacheReadInputTokens ?? 0) + (u.cacheReadInputTokens ?? 0), + cacheCreationInputTokens: (acc.cacheCreationInputTokens ?? 0) + (u.cacheCreationInputTokens ?? 0), + cacheCreation5mInputTokens: (acc.cacheCreation5mInputTokens ?? 0) + (u.cacheCreation5mInputTokens ?? 0), + cacheCreation1hInputTokens: (acc.cacheCreation1hInputTokens ?? 0) + (u.cacheCreation1hInputTokens ?? 0), + webSearchRequests: (acc.webSearchRequests ?? 0) + (u.webSearchRequests ?? 0), + costUSD: acc.costUSD + u.costUSD, + })); + } + /** + * Aggregate auxiliary usage stats from multiple reports. + */ + aggregateAuxiliaryUsage(reports) { + let totalAuxiliaryUsage; + for (const report of reports) { + if (report.auxiliaryUsage) { + totalAuxiliaryUsage = mergeAuxiliaryUsage(totalAuxiliaryUsage, report.auxiliaryUsage); + } + } + return totalAuxiliaryUsage; + } + /** + * Render the summary section. + */ + renderSummary(reports, totalDuration, options) { + const allFindings = []; + let totalFailedHunks = 0; + let totalFailedExtractions = 0; + let totalSkippedFiles = 0; + let totalVerifierRejections = 0; + for (const report of reports) { + allFindings.push(...report.findings); + totalFailedHunks += report.failedHunks ?? 0; + totalFailedExtractions += report.failedExtractions ?? 0; + totalSkippedFiles += report.skippedFiles?.length ?? 0; + totalVerifierRejections += report.verifierRejections?.count ?? 0; + } + const counts = countBySeverity(allFindings); + const totalUsage = this.aggregateUsage(reports); + const totalAuxiliaryUsage = this.aggregateAuxiliaryUsage(reports); + if (this.verbosity === Verbosity.Quiet) { + // Quiet mode: just output the summary line + const countStr = formatFindingCountsPlain(counts); + console.log(countStr); + return; + } + if (this.mode.isTTY) { + this.log(chalk.bold('SUMMARY')); + this.log(formatFindingCounts(counts)); + if (totalFailedHunks > 0) { + this.log(chalk.yellow(`${figures.warning} ${totalFailedHunks} ${pluralize(totalFailedHunks, 'chunk')} failed to analyze`)); + } + if (totalFailedExtractions > 0) { + this.log(chalk.yellow(`${figures.warning} ${totalFailedExtractions} finding ${pluralize(totalFailedExtractions, 'extraction')} failed`)); + } + if (totalVerifierRejections > 0) { + this.log(chalk.yellow(`${figures.warning} ${totalVerifierRejections} ${pluralize(totalVerifierRejections, 'finding')} rejected by verification`)); + } + if ((totalFailedHunks > 0 || totalFailedExtractions > 0) && this.verbosity < Verbosity.Verbose) { + this.log(chalk.dim(' Use -v for failure details')); + } + if (totalSkippedFiles > 0) { + this.log(chalk.dim(`${totalSkippedFiles} ${pluralize(totalSkippedFiles, 'file')} skipped`)); + } + const durationLine = `Analysis completed in ${formatDuration(totalDuration)}`; + if (totalUsage) { + this.log(chalk.dim(`${durationLine} · ${formatUsage(totalUsage, totalAuxiliaryUsage)}`)); + } + else { + this.log(chalk.dim(durationLine)); + } + if (options?.traceId && this.verbosity >= Verbosity.Verbose) { + this.log(chalk.dim(`Trace: ${options.traceId}`)); + } + } + else { + this.logPlain(`Summary: ${formatFindingCountsPlain(counts)}`); + if (totalFailedHunks > 0) { + this.logPlain(`WARN: ${totalFailedHunks} ${pluralize(totalFailedHunks, 'chunk')} failed to analyze`); + } + if (totalFailedExtractions > 0) { + this.logPlain(`WARN: ${totalFailedExtractions} finding ${pluralize(totalFailedExtractions, 'extraction')} failed`); + } + if (totalVerifierRejections > 0) { + this.logPlain(`WARN: ${totalVerifierRejections} ${pluralize(totalVerifierRejections, 'finding')} rejected by verification`); + } + if ((totalFailedHunks > 0 || totalFailedExtractions > 0) && this.verbosity < Verbosity.Verbose) { + this.logPlain('Use -v for failure details'); + } + if (totalSkippedFiles > 0) { + this.logPlain(`${totalSkippedFiles} ${pluralize(totalSkippedFiles, 'file')} skipped`); + } + if (totalUsage) { + this.logPlain(`Usage: ${formatUsagePlain(totalUsage, totalAuxiliaryUsage)}`); + } + this.logPlain(`Total time: ${formatDuration(totalDuration)}`); + if (options?.traceId && this.verbosity >= Verbosity.Verbose) { + this.logPlain(`Trace: ${options.traceId}`); + } + } + } + /** + * Display the configuration section with triggers. + */ + configTriggers(loaded, matched, triggers) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.bold('CONFIG') + + chalk.cyan(` ${loaded} triggers`) + + chalk.dim(` · ${matched} matched`)); + // Show matched triggers + for (const trigger of triggers) { + this.log(` ${chalk.green(ICON_CHECK)} ${trigger.name} ${chalk.dim(`(${trigger.skill})`)}`); + } + this.log(''); + } + else { + this.logPlain(`Config: ${loaded} triggers, ${matched} matched`); + for (const trigger of triggers) { + this.logPlain(` ${trigger.name} (${trigger.skill})`); + } + } + } + /** + * Log a step message. + */ + step(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(`${chalk.cyan(figures.arrowRight)} ${message}`); + } + else { + this.logPlain(message); + } + } + /** + * Log a success message. + */ + success(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(`${chalk.green(ICON_CHECK)} ${message}`); + } + else { + this.logPlain(message); + } + } + /** + * Log a file creation message (green "Created" prefix, no icon). + */ + created(filename) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(`${chalk.green('Created')} ${filename}`); + } + else { + this.logPlain(`Created ${filename}`); + } + } + /** + * Log a skipped file message (yellow "Skipped" prefix with reason). + */ + skipped(filename, reason) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + const suffix = reason ? chalk.dim(` (${reason})`) : ''; + if (this.mode.isTTY) { + this.log(`${chalk.yellow('Skipped')} ${filename}${suffix}`); + } + else { + this.logPlain(`Skipped ${filename}${reason ? ` (${reason})` : ''}`); + } + } + /** + * Log a warning message. + */ + warning(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(`${chalk.yellow(figures.warning)} ${message}`); + } + else { + this.logPlain(`WARN: ${message}`); + } + } + /** + * Log an error message. + * Errors are always shown, even in quiet mode. + */ + error(message) { + if (this.mode.isTTY) { + console.error(`${chalk.red(figures.cross)} ${message}`); + } + else { + console.error(`[${timestamp()}] warden: ERROR: ${message}`); + } + } + /** + * Log a debug message. + */ + debug(message) { + if (this.verbosity < Verbosity.Debug) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.dim(`[debug] ${message}`)); + } + else { + this.logPlain(`DEBUG: ${message}`); + } + } + /** + * Log a hint/tip message. + */ + tip(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.dim(`Tip: ${message}`)); + } + // No tips in CI mode + } + /** + * Log dim/subtle text (visible at normal verbosity, hidden in quiet mode). + */ + dim(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.dim(message)); + } + else { + this.logPlain(message); + } + } + /** + * Log plain text (no prefix). + */ + text(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(message); + } + else { + this.logPlain(message); + } + } + /** + * Log bold text. + */ + bold(message) { + if (this.verbosity === Verbosity.Quiet) { + return; + } + if (this.mode.isTTY) { + this.log(chalk.bold(message)); + } + else { + this.logPlain(message); + } + } + /** + * Output a blank line. + */ + blank() { + if (this.verbosity === Verbosity.Quiet) { + return; + } + this.log(''); + } + /** + * Render an empty state box (e.g., "No changes found"). + */ + renderEmptyState(message, tip) { + if (this.verbosity === Verbosity.Quiet) { + console.log(message); + return; + } + if (this.mode.isTTY) { + const box = new BoxRenderer({ + title: 'warden', + mode: this.mode, + }); + box.header(); + box.blank(); + box.content(`${chalk.yellow(figures.warning)} ${message}`); + if (tip) { + box.blank(); + box.content(chalk.dim(`Tip: ${tip}`)); + } + box.blank(); + box.footer(); + for (const line of box.render()) { + this.log(line); + } + } + else { + this.logPlain(`WARN: ${message}`); + if (tip) { + this.logPlain(`Tip: ${tip}`); + } + } + } +} + + +/***/ }), + +/***/ 5836: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ O7: () => (/* binding */ createDefaultCallbacks), +/* harmony export */ UG: () => (/* binding */ runSkillTask) +/* harmony export */ }); +/* unused harmony exports composeTasksWithFailFast, runComposedSkillTasks, runSkillTasks */ +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78481); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30340); +/* harmony import */ var _sdk_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(98229); +/* harmony import */ var _sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(45452); +/* harmony import */ var _sdk_circuit_breaker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71794); +/* harmony import */ var _sdk_types_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(88973); +/* harmony import */ var _sdk_report_files_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(79418); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(39559); +/* harmony import */ var figures__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(58653); +/* harmony import */ var _verbosity_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(21307); +/* harmony import */ var _icons_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(5832); +/* harmony import */ var _tty_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(80029); +/* harmony import */ var _formatters_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(43171); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(82272); +var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__]); +_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; +/** + * Task execution for skills. + * Callback-based state updates for CLI and Ink rendering. + * + * Reporter spec: specs/reporters.md + */ + + + + + + + + + + + + + + +function allAnalysisFailuresHaveCode(hunkFailures, code) { + const analysisFailures = hunkFailures.filter((failure) => failure.type === 'analysis'); + return (analysisFailures.length > 0 + && analysisFailures.every((failure) => failure.code === code)); +} +function firstAnalysisFailureMessage(hunkFailures, code) { + return hunkFailures.find((failure) => failure.type === 'analysis' && failure.code === code)?.message; +} +function extractionFailureCodes(hunkFailures) { + if (hunkFailures.length === 0 + || !hunkFailures.every((failure) => failure.type === 'extraction' && (0,_types_index_js__WEBPACK_IMPORTED_MODULE_0__/* .isExtractionErrorCode */ .nE)(failure.code))) { + return undefined; + } + return [...new Set(hunkFailures.map((failure) => failure.code))]; +} +function summarizeRunFailure(args) { + const { totalHunks, hunkFailures, circuitBreaker, runtime } = args; + const circuitReason = circuitBreaker?.reason; + if (circuitReason) { + const providerContext = circuitBreaker.providerContextFor(args.scope); + return { code: circuitReason.code, message: circuitReason.message, providerContext }; + } + if (allAnalysisFailuresHaveCode(hunkFailures, 'auth_failed')) { + return { + code: 'auth_failed', + message: 'Authentication failed. Warden stopped early.', + }; + } + if (allAnalysisFailuresHaveCode(hunkFailures, 'invalid_model_selector')) { + return { + code: 'invalid_model_selector', + message: firstAnalysisFailureMessage(hunkFailures, 'invalid_model_selector') ?? 'Invalid Pi model selector.', + }; + } + if (allAnalysisFailuresHaveCode(hunkFailures, 'provider_unavailable')) { + return { + code: 'provider_unavailable', + message: `Provider unavailable: all ${totalHunks} chunk${totalHunks === 1 ? '' : 's'} failed to analyze. Warden stopped early.`, + }; + } + const extractionCodes = extractionFailureCodes(hunkFailures); + const primaryExtractionCode = extractionCodes?.[0]; + if (primaryExtractionCode) { + return { + code: primaryExtractionCode, + message: `Findings extraction failed for all ${totalHunks} chunk${totalHunks === 1 ? '' : 's'} (${extractionCodes.join(', ')}).`, + }; + } + return { + code: 'all_hunks_failed', + message: `All ${totalHunks} chunk${totalHunks === 1 ? '' : 's'} failed to analyze. ` + + `This usually indicates an authentication problem. ` + + ((runtime ?? 'pi') === 'claude' + ? `Verify WARDEN_ANTHROPIC_API_KEY is set correctly, or run 'claude login' when using the Claude runtime without an API key.` + : `Verify WARDEN_MODEL and the WARDEN-prefixed provider API key for that model are set correctly.`), + }; +} +/** + * Write a log-mode message to stderr with timestamp prefix. + * Used for non-TTY / plain output. + */ +function logPlain(message) { + console.error(`[${(0,_tty_js__WEBPACK_IMPORTED_MODULE_8__/* .timestamp */ .vE)()}] warden: ${message}`); +} +/** + * Write a debug-level message to stderr. + * Uses chalk.dim formatting in TTY mode, timestamped "DEBUG:" prefix otherwise. + */ +function debugLog(mode, message) { + if (mode.isTTY) { + console.error(chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim(`[debug] ${message}`)); + } + else { + logPlain(`DEBUG: ${message}`); + } +} +/** + * Format a finding's location as a compact string, falling back to 'unknown'. + */ +function findingLocation(finding) { + if (!finding.location) + return 'unknown'; + return (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatLocation */ .j$)(finding.location.path, finding.location.startLine, finding.location.endLine); +} +function findingSummary(finding) { + return `${findingLocation(finding)}: ${finding.title}`; +} +function formatFindingProcessingEvent(event) { + const reason = event.reason ? ` (${event.reason})` : ''; + const replacement = event.replacement ? ` -> ${findingSummary(event.replacement)}` : ''; + return `${event.stage}:${event.action} ${findingSummary(event.finding)}${replacement}${reason}`; +} +/** + * Run a single skill task. + */ +async function runSkillTask(options, callbacks, sharedAnalysisQueue) { + const { name, displayName = name, triggerName, failOn, minConfidence, resolveSkill, context, runnerOptions: configuredRunnerOptions = {}, } = options; + // This clone's identity scopes circuit-breaker provider diagnostics to this skill run. + const runnerOptions = { ...configuredRunnerOptions }; + const taskConcurrency = runnerOptions.parallel === false + ? 1 + : runnerOptions.concurrency ?? _sdk_types_js__WEBPACK_IMPORTED_MODULE_10__/* .DEFAULT_ANALYSIS_CONCURRENCY */ .R; + const analysisQueue = sharedAnalysisQueue ?? new _utils_index_js__WEBPACK_IMPORTED_MODULE_7__/* .AsyncWorkQueue */ .Z_(taskConcurrency); + return _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'skill.run', name: `run ${displayName}` }, async (span) => { + span.setAttribute('gen_ai.agent.name', displayName); + if (triggerName) { + span.setAttribute('warden.trigger.name', triggerName); + } + const files = context.pullRequest?.files ?? []; + span.setAttribute('warden.file.count', files.length); + _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .logger */ .vF.info(_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .logger */ .vF.fmt `Skill execution started: ${displayName}`, { + 'warden.file.count': files.length, + }); + const startTime = Date.now(); + const runtime = runnerOptions.runtime ?? 'pi'; + // Mirror of the inner-scope `skill` so the outer catch can use + // report.skill when resolveSkill succeeded but a later step threw. + // Stays undefined only if resolveSkill itself failed. + let resolvedSkillName; + let resolvedModel; + try { + let skill; + try { + skill = await resolveSkill(); + resolvedSkillName = skill.name; + span.setAttribute('gen_ai.agent.name', skill.name); + } + catch (err) { + if (err instanceof _sdk_errors_js__WEBPACK_IMPORTED_MODULE_2__/* .WardenAuthenticationError */ .Aq) + throw err; + const message = err instanceof Error ? err.message : String(err); + throw new _sdk_errors_js__WEBPACK_IMPORTED_MODULE_2__/* .SkillRunnerError */ .cy(message, { cause: err, code: 'skill_resolution_failed' }); + } + // Prepare files (parse patches into hunks) + const { files: preparedFiles, skippedFiles, hunkGate } = (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .prepareSkillFiles */ .kV)(skill, context, { + contextLines: runnerOptions.contextLines, + ignore: runnerOptions.ignore, + scan: runnerOptions.scan, + chunking: runnerOptions.chunking, + skipHunks: runnerOptions.skipHunks, + }); + if (preparedFiles.length === 0) { + // No files to analyze - skip + const skippedReport = { + skill: skill.name, + summary: (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .emptyRunSummary */ .xc)(hunkGate), + findings: [], + usage: { inputTokens: 0, outputTokens: 0, costUSD: 0 }, + durationMs: Date.now() - startTime, + model: runnerOptions?.model, + runtime, + skippedFiles: skippedFiles.length > 0 ? skippedFiles : undefined, + hunkGate, + }; + span.setAttribute('warden.finding.count', 0); + callbacks.onSkillSkipped(name); + // Also fire onSkillComplete so the incremental JSONL writer records the skipped skill. + callbacks.onSkillComplete(name, skippedReport); + return { + name, + report: skippedReport, + failOn, + minConfidence, + }; + } + // Initialize file states + const fileStates = preparedFiles.map((file) => ({ + filename: file.filename, + status: 'pending', + currentHunk: 0, + totalHunks: file.hunks.length, + findings: [], + })); + // Notify skill start + callbacks.onSkillStart({ + name, + displayName, + status: 'running', + startTime, + files: fileStates, + findings: [], + }); + // Build PR context for inclusion in prompts (if available) + // For non-PR contexts (CLI file/diff mode), skip the "Other Files" list to avoid + // bloating every hunk prompt with thousands of filenames. + const isPullRequest = context.pullRequest ? context.pullRequest.number !== 0 : false; + const prContext = context.pullRequest + ? { + changedFiles: isPullRequest ? context.pullRequest.files.map((f) => f.filename) : [], + title: context.pullRequest.title, + body: context.pullRequest.body, + maxContextFiles: runnerOptions.maxContextFiles, + } + : undefined; + // Files aggregate hunk results; the shared queue owns concurrency. + const processFile = async (prepared, index) => { + const filename = prepared.filename; + const localState = fileStates[index]; + let fileStartTime; + const fileCallbacks = { + skillStartTime: startTime, + onHunkStart: (hunkNum, totalHunks, lineRange) => { + if (fileStartTime === undefined) { + fileStartTime = Date.now(); + if (localState) + localState.status = 'running'; + callbacks.onFileUpdate(name, filename, { + status: 'running', + totalHunks, + }); + } + callbacks.onHunkStart?.(name, filename, hunkNum, totalHunks, lineRange); + }, + onHunkComplete: (_hunkNum, findings, usage) => { + // Accumulate findings and usage for this file + const current = fileStates[index]; + if (current) { + current.currentHunk++; + current.findings.push(...findings); + if (current.usage) { + current.usage.inputTokens += usage.inputTokens; + current.usage.outputTokens += usage.outputTokens; + current.usage.costUSD += usage.costUSD; + if (usage.cacheReadInputTokens) { + current.usage.cacheReadInputTokens = (current.usage.cacheReadInputTokens ?? 0) + usage.cacheReadInputTokens; + } + if (usage.cacheCreationInputTokens) { + current.usage.cacheCreationInputTokens = (current.usage.cacheCreationInputTokens ?? 0) + usage.cacheCreationInputTokens; + } + if (usage.cacheCreation5mInputTokens) { + current.usage.cacheCreation5mInputTokens = (current.usage.cacheCreation5mInputTokens ?? 0) + usage.cacheCreation5mInputTokens; + } + if (usage.cacheCreation1hInputTokens) { + current.usage.cacheCreation1hInputTokens = (current.usage.cacheCreation1hInputTokens ?? 0) + usage.cacheCreation1hInputTokens; + } + if (usage.webSearchRequests) { + current.usage.webSearchRequests = (current.usage.webSearchRequests ?? 0) + usage.webSearchRequests; + } + } + else { + current.usage = { ...usage }; + } + callbacks.onFileUpdate(name, filename, { + currentHunk: current.currentHunk, + usage: current.usage, + }); + } + }, + onLargePrompt: callbacks.onLargePrompt + ? (lineRange, chars, estimatedTokens) => { + callbacks.onLargePrompt?.(name, filename, lineRange, chars, estimatedTokens); + } + : undefined, + onPromptSize: callbacks.onPromptSize + ? (lineRange, systemChars, userChars, totalChars, estimatedTokens) => { + callbacks.onPromptSize?.(name, filename, lineRange, systemChars, userChars, totalChars, estimatedTokens); + } + : undefined, + onExtractionResult: callbacks.onExtractionResult + ? (lineRange, findingsCount, method) => { + callbacks.onExtractionResult?.(name, filename, lineRange, findingsCount, method); + } + : undefined, + onChunkComplete: callbacks.onChunkComplete + ? (chunk) => { + callbacks.onChunkComplete?.(skill.name, chunk); + } + : undefined, + onHunkFailed: callbacks.onHunkFailed + ? (lineRange, error) => { + callbacks.onHunkFailed?.(name, filename, lineRange, error); + } + : undefined, + onExtractionFailure: callbacks.onExtractionFailure + ? (lineRange, error, preview) => { + callbacks.onExtractionFailure?.(name, filename, lineRange, error, preview); + } + : undefined, + onRetry: callbacks.onRetry + ? (lineRange, attempt, maxRetries, error, delayMs) => { + callbacks.onRetry?.(name, filename, lineRange, attempt, maxRetries, error, delayMs); + } + : undefined, + }; + const result = await (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .analyzeFile */ .xy)(skill, prepared, context.repoPath, runnerOptions, fileCallbacks, prContext, analysisQueue); + // Detect if this file was aborted before any real work happened + const fileDurationMs = fileStartTime === undefined ? 0 : Date.now() - fileStartTime; + const aborted = runnerOptions.abortController?.signal.aborted ?? false; + const noWork = !result.usage || (result.usage.inputTokens === 0 && result.usage.outputTokens === 0); + const fileStatus = (aborted && noWork) ? 'skipped' : 'done'; + if (localState) + localState.status = fileStatus; + callbacks.onFileUpdate(name, filename, { + status: fileStatus, + findings: result.findings, + usage: result.usage, + durationMs: fileDurationMs, + }); + return { + findings: result.findings, + usage: result.usage, + durationMs: fileDurationMs, + failedHunks: result.failedHunks, + failedExtractions: result.failedExtractions, + hunkFailures: result.hunkFailures, + auxiliaryUsage: result.auxiliaryUsage, + traces: result.traces, + responseModels: result.responseModels, + }; + }; + // Files only group results and progress. The shared queue schedules every hunk. + const allResults = await Promise.all(preparedFiles.map((file, index) => processFile(file, index))); + // Mark never-dispatched files as skipped + for (const fileState of fileStates) { + if (fileState.status === 'pending') { + callbacks.onFileUpdate(name, fileState.filename, { status: 'skipped' }); + } + } + // Build report + const duration = Date.now() - startTime; + const allFindings = allResults.flatMap((r) => r.findings); + const allUsage = allResults.map((r) => r.usage).filter((u) => u !== undefined); + const allAuxEntries = allResults.flatMap((r) => r.auxiliaryUsage ?? []); + const allTraces = allResults.flatMap((r) => r.traces ?? []); + const allResponseModels = allResults.flatMap((r) => r.responseModels ?? []); + resolvedModel = (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveResponseModel */ .X5)(allResponseModels, runnerOptions?.model); + const totalFailedHunks = allResults.reduce((sum, r) => sum + r.failedHunks, 0); + const totalFailedExtractions = allResults.reduce((sum, r) => sum + r.failedExtractions, 0); + const allHunkFailures = allResults.flatMap((r) => r.hunkFailures); + const totalHunks = preparedFiles.reduce((sum, f) => sum + f.hunks.length, 0); + // Each hunk contributes to at most one of failedHunks / failedExtractions + // (mutually exclusive in analyzeFile), so summing them gives the total + // failed-hunk count. Counting only analysis failures would miss the + // scenario where every hunk's SDK call succeeded but every extraction + // failed — a silent zero-findings run otherwise. + const totalAttemptFailures = totalFailedHunks + totalFailedExtractions; + const circuitReason = runnerOptions.circuitBreaker?.reason; + if (totalHunks > 0 + && allFindings.length === 0 + && totalAttemptFailures > 0 + && (circuitReason + || (totalAttemptFailures === totalHunks + && !(runnerOptions.abortController?.signal.aborted ?? false)))) { + const auxUsage = (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .aggregateAuxiliaryUsage */ .RL)(allAuxEntries); + const error = summarizeRunFailure({ + totalHunks, + hunkFailures: allHunkFailures, + circuitBreaker: runnerOptions.circuitBreaker, + runtime: runnerOptions.runtime, + scope: runnerOptions, + }); + const errorReport = { + skill: skill.name, + summary: `${skill.name}: failed (${error.code})`, + findings: [], + usage: (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .aggregateUsage */ .Z$)(allUsage), + durationMs: duration, + model: resolvedModel, + runtime, + // Preserve per-file metadata (timing, partial usage, attempted + // filenames) on failure runs too — `warden runs` and JSONL + // consumers iterate this array to count attempted files. Without + // it, a failed run shows totalFiles: 0. + files: preparedFiles.map((file, i) => { + const r = allResults[i]; + return { + filename: file.filename, + findings: r?.findings.length ?? 0, + durationMs: r?.durationMs, + usage: r?.usage, + }; + }), + failedHunks: totalFailedHunks, + hunkFailures: allHunkFailures, + error: { + code: error.code, + message: error.message, + timestamp: new Date().toISOString(), + }, + }; + if (totalFailedExtractions > 0) + errorReport.failedExtractions = totalFailedExtractions; + if (skippedFiles.length > 0) + errorReport.skippedFiles = skippedFiles; + if (auxUsage) + errorReport.auxiliaryUsage = auxUsage; + if (runnerOptions.captureTraces && allTraces.length > 0) + errorReport.traces = allTraces; + span.setAttribute('warden.finding.count', 0); + callbacks.onSkillError(name, error.message); + // Mirror the success path: emit a final completion event with the + // (errored) report so terminal renderers print the per-skill + // summary line. Without this, console mode shows the error string + // alone with no breakdown of timing, cost, or attempted files. + callbacks.onSkillUpdate(name, { + status: 'error', + durationMs: duration, + findings: [], + usage: errorReport.usage, + auxiliaryUsage: errorReport.auxiliaryUsage, + }); + callbacks.onSkillComplete(name, errorReport); + // Carry a typed error alongside the report so consumers that re-throw + // (action executor, Sentry.captureException) preserve the ErrorCode. + const runnerError = new _sdk_errors_js__WEBPACK_IMPORTED_MODULE_2__/* .SkillRunnerError */ .cy(error.message, { + code: error.code, + providerContext: error.providerContext, + hunkFailures: allHunkFailures, + }); + return { name, report: errorReport, error: runnerError, failOn, minConfidence }; + } + const processed = await (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .postProcessFindings */ .yp)(allFindings, { + skill, + repoPath: context.repoPath, + apiKey: runnerOptions.apiKey, + runtime: runnerOptions.runtime, + auxiliaryModel: runnerOptions.auxiliaryModel, + auxiliaryEffort: runnerOptions.auxiliaryEffort, + synthesisModel: runnerOptions.synthesisModel, + auxiliaryMaxRetries: runnerOptions.auxiliaryMaxRetries, + verifyFindings: runnerOptions.verifyFindings, + maxTurns: runnerOptions.maxTurns, + abortController: runnerOptions.abortController, + pathToClaudeCodeExecutable: runnerOptions.pathToClaudeCodeExecutable, + prContext, + onFindingProcessing: (event) => { + callbacks.onFindingProcessing?.(name, event); + }, + }); + const finalFindings = processed.findings; + allAuxEntries.push(...processed.auxiliaryUsage); + const report = { + skill: skill.name, + summary: (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .generateSummary */ .ur)(skill.name, finalFindings), + findings: finalFindings, + usage: (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .aggregateUsage */ .Z$)(allUsage), + durationMs: duration, + model: resolvedModel, + runtime, + files: (0,_sdk_report_files_js__WEBPACK_IMPORTED_MODULE_11__/* .buildFileReports */ .K)(preparedFiles.map((file, i) => { + const r = allResults[i]; + return { + filename: file.filename, + durationMs: r?.durationMs, + usage: r?.usage, + }; + }), finalFindings), + }; + if (skippedFiles.length > 0) { + report.skippedFiles = skippedFiles; + } + if (hunkGate) { + report.hunkGate = hunkGate; + } + if (totalFailedHunks > 0) { + report.failedHunks = totalFailedHunks; + } + if (totalFailedExtractions > 0) { + report.failedExtractions = totalFailedExtractions; + } + if (allHunkFailures.length > 0) { + report.hunkFailures = allHunkFailures; + } + if (runnerOptions.captureTraces && allTraces.length > 0) { + report.traces = allTraces; + } + const auxUsage = (0,_sdk_runner_js__WEBPACK_IMPORTED_MODULE_3__/* .aggregateAuxiliaryUsage */ .RL)(allAuxEntries); + if (auxUsage) { + report.auxiliaryUsage = auxUsage; + } + if (processed.verifierRejections) { + report.verifierRejections = processed.verifierRejections; + } + span.setAttribute('warden.finding.count', report.findings.length); + // Emit metrics and log completion + (0,_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .emitSkillMetrics */ .s7)(report); + _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .logger */ .vF.info(_sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .logger */ .vF.fmt `Skill execution complete: ${displayName}`, { + 'warden.finding.count': report.findings.length, + 'duration_ms': report.durationMs, + }); + // Notify skill complete + callbacks.onSkillUpdate(name, { + status: 'done', + durationMs: duration, + findings: finalFindings, + usage: report.usage, + auxiliaryUsage: report.auxiliaryUsage, + }); + callbacks.onSkillComplete(name, report); + return { name, report, failOn, minConfidence }; + } + catch (err) { + const { code, message } = (0,_sdk_errors_js__WEBPACK_IMPORTED_MODULE_2__/* .classifyError */ .fe)(err); + callbacks.onSkillError(name, message); + // Use the resolved skill name when available so JSONL output matches + // the success path's identifier. Falls back to the trigger name only + // when resolveSkill itself threw. + const skillName = resolvedSkillName ?? name; + const errorReport = { + skill: skillName, + summary: `${skillName}: failed (${code})`, + findings: [], + durationMs: Date.now() - startTime, + model: resolvedModel ?? runnerOptions?.model, + runtime, + error: { code, message, timestamp: new Date().toISOString() }, + }; + span.setAttribute('warden.finding.count', 0); + // Mirror the success / all-hunks-fail paths: emit a final completion + // event so non-TTY (log-mode) renderers print a per-skill summary + // line for the failure. Without this, log mode shows only the + // bare error string with no timing or duration. + callbacks.onSkillUpdate(name, { + status: 'error', + durationMs: errorReport.durationMs, + findings: [], + }); + callbacks.onSkillComplete(name, errorReport); + return { name, report: errorReport, error: err, failOn, minConfidence }; + } + }); +} +/** + * Create default progress callbacks for console output. + * In TTY mode: colored icons, chalk formatting. + * In non-TTY/log mode: timestamped lines with finding details. + */ +function createDefaultCallbacks(tasks, mode, verbosity) { + /** Resolve the display name for a skill, falling back to the raw name. */ + function displayNameFor(name) { + return tasks.find((t) => t.name === name)?.displayName ?? name; + } + /** Track per-skill skipped file counts for collapsed summary in non-TTY mode. */ + const skippedCounts = new Map(); + // Skipped skills also fire onSkillComplete (for the JSONL writer). + // Suppress the duplicate "completed" line for those names. + const skippedSkills = new Set(); + return { + onSkillStart: (skill) => { + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet) + return; + if (!mode.isTTY) { + const fileCount = skill.files.length; + logPlain(`Running ${displayNameFor(skill.name)} (${fileCount} ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .pluralize */ .td)(fileCount, 'file')})...`); + } + }, + onSkillUpdate: () => { }, + onFileUpdate: (_skillName, filename, updates) => { + if (updates.status === 'skipped') { + skippedCounts.set(_skillName, (skippedCounts.get(_skillName) ?? 0) + 1); + return; + } + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet || mode.isTTY) + return; + if (updates.status !== 'done') + return; + const duration = updates.durationMs !== undefined ? (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatDuration */ .a3)(updates.durationMs) : '?'; + const cost = updates.usage ? ` ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatCost */ .BD)(updates.usage.costUSD)}` : ''; + const n = updates.findings?.length ?? 0; + const suffix = n > 0 ? ` ${n} ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .pluralize */ .td)(n, 'finding')}` : ''; + logPlain(` ${displayNameFor(_skillName)} > ${filename} done ${duration}${cost}${suffix}`); + }, + onHunkStart: (skillName, filename, hunkNum, totalHunks, lineRange) => { + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet || mode.isTTY) + return; + logPlain(` ${displayNameFor(skillName)} > ${filename} [${hunkNum}/${totalHunks}] ${lineRange}`); + }, + onSkillComplete: (name, report) => { + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet) + return; + if (skippedSkills.has(name)) + return; + const displayName = displayNameFor(name); + // Errored runs render as failures, not as misleading "completed - + // 0 findings" lines with a green checkmark. onSkillError already + // printed the error message; this line carries timing only. + if (report.error) { + if (mode.isTTY) { + const duration = report.durationMs !== undefined ? ` ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim(`[${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatDuration */ .a3)(report.durationMs)}]`)}` : ''; + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.red('✗')} ${displayName}${duration} ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.red(`(${report.error.code})`)}`); + } + else { + const duration = report.durationMs !== undefined ? (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatDuration */ .a3)(report.durationMs) : '?'; + logPlain(`${displayName} failed in ${duration} (${report.error.code})`); + } + return; + } + if (mode.isTTY) { + const duration = report.durationMs !== undefined ? ` ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim(`[${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatDuration */ .a3)(report.durationMs)}]`)}` : ''; + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.green(_icons_js__WEBPACK_IMPORTED_MODULE_12__/* .ICON_CHECK */ .hP)} ${displayName}${duration}`); + // Debug: log finding details + if (verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug && report.findings.length > 0) { + for (const finding of report.findings) { + debugLog(mode, `${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatSeverityPlain */ .xz)(finding.severity)} ${findingLocation(finding)}: ${finding.title}`); + } + } + } + else { + // Log mode: timestamped completion with duration and finding summary + const duration = report.durationMs !== undefined ? (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatDuration */ .a3)(report.durationMs) : '?'; + const counts = (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .countBySeverity */ .Ot)(report.findings); + const summary = (0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatFindingCountsPlain */ .Xr)(counts); + logPlain(`${displayName} completed in ${duration} - ${summary}`); + // Show per-finding lines at Verbose+ verbosity in log mode + // (the final report already shows findings with full detail) + if (verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Verbose) { + for (const finding of report.findings) { + logPlain(` ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .formatSeverityPlain */ .xz)(finding.severity)} ${findingLocation(finding)}: ${finding.title}`); + } + } + const skipped = skippedCounts.get(name) ?? 0; + if (skipped > 0) { + logPlain(` ${skipped} ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .pluralize */ .td)(skipped, 'file')} skipped`); + } + } + }, + onSkillSkipped: (name) => { + skippedSkills.add(name); + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet) + return; + const displayName = displayNameFor(name); + if (mode.isTTY) { + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.yellow(_icons_js__WEBPACK_IMPORTED_MODULE_12__/* .ICON_SKIPPED */ .xj)} ${displayName} ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim('[skipped]')}`); + } + else { + logPlain(`${displayName} skipped`); + } + }, + onSkillError: (name, error) => { + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet) + return; + const displayName = displayNameFor(name); + if (mode.isTTY) { + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.red('\u2717')} ${displayName} - ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.red(error)}`); + } + else { + logPlain(`ERROR: ${displayName} - ${error}`); + const skipped = skippedCounts.get(name) ?? 0; + if (skipped > 0) { + logPlain(` ${skipped} ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .pluralize */ .td)(skipped, 'file')} skipped`); + } + } + }, + // Warn about large prompts (always shown unless quiet) + onLargePrompt: (_skillName, filename, lineRange, chars, estimatedTokens) => { + if (verbosity === _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Quiet) + return; + const location = `${filename}:${lineRange}`; + const size = `${Math.round(chars / 1000)}k chars (~${Math.round(estimatedTokens / 1000)}k tokens)`; + if (mode.isTTY) { + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.yellow(figures__WEBPACK_IMPORTED_MODULE_13__/* ["default"] */ .Ay.warning)} Large prompt for ${location}: ${size}`); + } + else { + logPlain(`WARN: Large prompt for ${location}: ${size}`); + } + }, + // Debug mode: show prompt sizes + onPromptSize: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug + ? (_skillName, filename, lineRange, systemChars, userChars, totalChars, estimatedTokens) => { + const location = `${filename}:${lineRange}`; + debugLog(mode, `Prompt for ${location}: system=${systemChars}, user=${userChars}, total=${totalChars} chars (~${estimatedTokens} tokens)`); + } + : undefined, + // Debug mode: show extraction results + onExtractionResult: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug + ? (_skillName, filename, lineRange, findingsCount, method) => { + debugLog(mode, `Extracted ${findingsCount} ${(0,_formatters_js__WEBPACK_IMPORTED_MODULE_6__/* .pluralize */ .td)(findingsCount, 'finding')} from ${filename}:${lineRange} via ${method}`); + } + : undefined, + onFindingProcessing: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug + ? (_skillName, event) => { + debugLog(mode, formatFindingProcessingEvent(event)); + } + : undefined, + // Verbose mode: show per-hunk analysis failures (spec: event #16 hunk_failed) + onHunkFailed: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Verbose + ? (_skillName, filename, lineRange, error) => { + const location = `${filename}:${lineRange}`; + if (mode.isTTY) { + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.yellow(figures__WEBPACK_IMPORTED_MODULE_13__/* ["default"] */ .Ay.warning)} Chunk failed: ${location} ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim(`\u2014 ${error}`)}`); + } + else { + logPlain(`WARN: Chunk failed: ${location} \u2014 ${error}`); + } + } + : undefined, + // Verbose mode: show per-hunk extraction failures (spec: event #17 extraction_failure) + onExtractionFailure: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Verbose + ? (_skillName, filename, lineRange, error, preview) => { + const location = `${filename}:${lineRange}`; + if (mode.isTTY) { + console.error(`${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.yellow(figures__WEBPACK_IMPORTED_MODULE_13__/* ["default"] */ .Ay.warning)} Extraction failed: ${location} ${chalk__WEBPACK_IMPORTED_MODULE_9__/* ["default"] */ .Ay.dim(`\u2014 ${error}`)}`); + if (verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug && preview) { + debugLog(mode, ` Output preview: ${preview.slice(0, 200)}`); + } + } + else { + logPlain(`WARN: Extraction failed: ${location} \u2014 ${error}`); + if (verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Debug && preview) { + logPlain(`DEBUG: Output preview: ${preview.slice(0, 200)}`); + } + } + } + : undefined, + // Verbose mode: show retry attempts (spec: event #18 retry) + onRetry: verbosity >= _verbosity_js__WEBPACK_IMPORTED_MODULE_5__/* .Verbosity */ .W.Verbose + ? (_skillName, filename, lineRange, attempt, maxRetries, error, delayMs) => { + const location = `${filename}:${lineRange}`; + const retryInfo = `attempt ${attempt}/${maxRetries}`; + const delay = delayMs > 0 ? `, retrying in ${Math.round(delayMs / 1000)}s` : ''; + if (mode.isTTY) { + debugLog(mode, `Retry ${location} (${retryInfo}${delay}): ${error}`); + } + else { + logPlain(`WARN: Retry ${location} (${retryInfo}${delay}): ${error}`); + } + } + : undefined, + }; +} +/** + * Share abort/circuit state across task runner options. + */ +function composeTasksWithFailFast(tasks, failFastController, circuitBreaker, circuitAbortController) { + if (!failFastController && !circuitBreaker && !circuitAbortController) + return tasks; + const sharedAbortController = new AbortController(); + const taskControllers = new Set(); + const composedTaskControllers = new WeakMap(); + const abortAll = () => { + sharedAbortController.abort(); + for (const controller of taskControllers) { + controller.abort(); + } + }; + for (const source of [failFastController, circuitAbortController]) { + if (!source) + continue; + if (source.signal.aborted) { + abortAll(); + } + else { + source.signal.addEventListener('abort', abortAll, { once: true }); + } + } + const composeAbortController = (taskController) => { + if (!taskController) + return sharedAbortController; + const cached = composedTaskControllers.get(taskController); + if (cached) + return cached; + const composed = new AbortController(); + composedTaskControllers.set(taskController, composed); + taskControllers.add(composed); + const abortTask = () => composed.abort(); + if (sharedAbortController.signal.aborted || taskController.signal.aborted) { + abortTask(); + } + else { + taskController.signal.addEventListener('abort', abortTask, { once: true }); + } + return composed; + }; + return tasks.map((task) => ({ + ...task, + runnerOptions: { + ...task.runnerOptions, + abortController: composeAbortController(task.runnerOptions?.abortController), + circuitBreaker: task.runnerOptions?.circuitBreaker ?? circuitBreaker, + }, + })); +} +/** + * Launch all skill tasks in parallel using a shared hunk queue. + */ +async function runComposedSkillTasks(tasks, callbacks, analysisQueue) { + const results = await runPool(tasks, tasks.length, (task) => runSkillTask(task, callbacks, analysisQueue), { shouldAbort: () => tasks[0]?.runnerOptions?.abortController?.signal.aborted ?? false }); + return results; +} +/** + * Run multiple skill tasks with optional concurrency. + * Uses callbacks to report progress for Ink rendering. + */ +async function runSkillTasks(tasks, options, callbacks) { + const { mode, verbosity, concurrency, failFastController, onSkillComplete, onChunkComplete } = options; + const analysisQueue = new AsyncWorkQueue(concurrency); + const effectiveCallbacks = callbacks ?? createDefaultCallbacks(tasks, mode, verbosity); + const wrappedCallbacks = { + ...effectiveCallbacks, + ...(onSkillComplete || failFastController + ? { + onSkillComplete: (name, report) => { + effectiveCallbacks.onSkillComplete(name, report); + try { + onSkillComplete?.(report); + } + catch { /* streaming hook must not break the run */ } + if (failFastController && report.findings.length > 0) { + failFastController.abort(); + } + }, + } + : {}), + ...(onChunkComplete + ? { + onChunkComplete: (name, chunk) => { + effectiveCallbacks.onChunkComplete?.(name, chunk); + try { + onChunkComplete(name, chunk); + } + catch { /* streaming hook must not break the run */ } + }, + } + : {}), + }; + // Output SKILLS header (TTY only - in log mode, "Running..." lines are sufficient) + if (verbosity !== Verbosity.Quiet && tasks.length > 0 && mode.isTTY) { + console.error(chalk.bold('SKILLS')); + } + const circuitAbortController = new AbortController(); + const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController: circuitAbortController }); + const composedTasks = composeTasksWithFailFast(tasks, failFastController, circuitBreaker, circuitAbortController); + // Listen for abort signal to show interrupt message (non-TTY only; Ink handles TTY) + const abortSignal = composedTasks[0]?.runnerOptions?.abortController?.signal; + if (abortSignal && !abortSignal.aborted && !mode.isTTY && verbosity !== Verbosity.Quiet) { + abortSignal.addEventListener('abort', () => { + // Only show interrupt message for user SIGINT, not fail-fast + if (!failFastController?.signal.aborted && !circuitAbortController.signal.aborted) { + logPlain('Interrupted, finishing up... (press Ctrl+C again to force exit)'); + } + }, { once: true }); + } + // Show fail-fast message when triggered (non-TTY only) + if (failFastController && !mode.isTTY && verbosity !== Verbosity.Quiet) { + failFastController.signal.addEventListener('abort', () => { + logPlain('Stopping \u2014 finding detected (--fail-fast)'); + }, { once: true }); + } + // Launch all skills in parallel; the queue is the sole concurrency gate. + return runComposedSkillTasks(composedTasks, wrappedCallbacks, analysisQueue); +} + +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }); + +/***/ }), + +/***/ 80029: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T6: () => (/* binding */ warnAction), +/* harmony export */ d5: () => (/* binding */ logAction), +/* harmony export */ vE: () => (/* binding */ timestamp) +/* harmony export */ }); +/* unused harmony export detectOutputMode */ + +/** + * Detect terminal capabilities. + * @param colorOverride - Optional override for color support (--color / --no-color) + */ +function detectOutputMode(colorOverride) { + // Check both stderr and stdout for TTY - some environments have TTY on one but not the other + const streamIsTTY = (process.stderr.isTTY || process.stdout.isTTY) ?? false; + // Treat dumb terminals as non-TTY (e.g., TERM=dumb used by some editors/agents) + const term = process.env['TERM'] ?? ''; + const isDumbTerminal = term === 'dumb' || term === ''; + const isTTY = streamIsTTY && !isDumbTerminal; + // Determine color support + let supportsColor; + if (colorOverride !== undefined) { + supportsColor = colorOverride; + } + else if (process.env['NO_COLOR']) { + supportsColor = false; + } + else if (process.env['FORCE_COLOR']) { + supportsColor = true; + } + else { + supportsColor = isTTY && chalk.level > 0; + } + // Configure chalk based on color support + if (!supportsColor) { + chalk.level = 0; + } + const columns = process.stderr.columns ?? process.stdout.columns ?? 80; + return { + isTTY, + supportsColor, + columns, + }; +} +/** + * Get a timestamp for CI/non-TTY output. + */ +function timestamp() { + return new Date().toISOString(); +} +/** + * Log a timestamped action message to stderr. + * Used by action workflow steps (dedup, fix eval, stale resolution) for consistent output. + */ +function logAction(message) { + console.error(`[${timestamp()}] warden: ${message}`); +} +/** + * Log a timestamped warning to stderr. + */ +function warnAction(message) { + console.error(`[${timestamp()}] warden: WARN: ${message}`); +} + + +/***/ }), + +/***/ 21307: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ W: () => (/* binding */ Verbosity) +/* harmony export */ }); +/* unused harmony export parseVerbosity */ +/** + * Verbosity levels for CLI output. + */ +var Verbosity; +(function (Verbosity) { + /** Errors + final summary only */ + Verbosity[Verbosity["Quiet"] = 0] = "Quiet"; + /** Normal output with progress */ + Verbosity[Verbosity["Normal"] = 1] = "Normal"; + /** Real-time findings, hunk details */ + Verbosity[Verbosity["Verbose"] = 2] = "Verbose"; + /** Token counts, latencies, debug info */ + Verbosity[Verbosity["Debug"] = 3] = "Debug"; +})(Verbosity || (Verbosity = {})); +/** + * Parse verbosity from CLI flags. + * @param quiet - If true, return Quiet + * @param verboseCount - Number of -v flags (0, 1, or 2+) + * @param debug - If true, return Debug (overrides verbose count) + */ +function parseVerbosity(quiet, verboseCount, debug) { + if (quiet) { + return Verbosity.Quiet; + } + if (debug || verboseCount >= 2) { + return Verbosity.Debug; + } + if (verboseCount === 1) { + return Verbosity.Verbose; + } + return Verbosity.Normal; +} + + +/***/ }), + +/***/ 77695: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ln: () => (/* binding */ resolveLayeredSkillConfigs), +/* harmony export */ M3: () => (/* binding */ loadLayeredWardenConfig), +/* harmony export */ Zu: () => (/* binding */ emptyToUndefined), +/* harmony export */ hd: () => (/* binding */ buildSkillRootsByName), +/* harmony export */ tx: () => (/* binding */ ConfigLoadError) +/* harmony export */ }); +/* unused harmony exports loadWardenConfigFile, loadWardenConfig, mergeWardenConfigs, resolveSkillConfigs */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77598); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_crypto__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var smol_toml__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(90785); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30340); +/* harmony import */ var _skills_loader_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(34691); +/* harmony import */ var _schema_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(96120); + + + + + + + +class ConfigLoadError extends Error { + constructor(message, options) { + super(message, options); + this.name = 'ConfigLoadError'; + } +} +function parseConfigContent(content) { + let rawConfig; + try { + rawConfig = (0,smol_toml__WEBPACK_IMPORTED_MODULE_3__/* .parse */ .qg)(content); + } + catch (error) { + throw new ConfigLoadError('Failed to parse TOML configuration', { cause: error }); + } + // Detect legacy [[triggers]] format and provide migration guidance + if (rawConfig && typeof rawConfig === 'object' && 'triggers' in rawConfig) { + throw new ConfigLoadError('Legacy [[triggers]] format detected. Migrate to [[skills]] format:\n\n' + + ' [[triggers]] → [[skills]]\n' + + ' name = "my-skill" name = "my-skill"\n' + + ' event = "pull_request" → [[skills.triggers]]\n' + + ' skill = "my-skill" type = "pull_request"\n' + + ' actions = [...] actions = [...]\n\n' + + 'See the migration guide for details.'); + } + const result = _schema_js__WEBPACK_IMPORTED_MODULE_6__/* .WardenConfigSchema */ .kV.safeParse(rawConfig); + if (!result.success) { + const issues = result.error.issues.map(i => ` - ${i.path.join('.')}: ${i.message}`).join('\n'); + throw new ConfigLoadError(`Invalid configuration:\n${issues}`); + } + return result.data; +} +function loadWardenConfigFile(configPath) { + return _sentry_js__WEBPACK_IMPORTED_MODULE_4__/* .Sentry.startSpan */ .sQ.startSpan({ op: 'config.load', name: 'load config' }, () => { + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(configPath)) { + throw new ConfigLoadError(`Configuration file not found: ${configPath}`); + } + let content; + try { + content = (0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(configPath, 'utf-8'); + } + catch (error) { + throw new ConfigLoadError(`Failed to read configuration file: ${configPath}`, { cause: error }); + } + return parseConfigContent(content); + }); +} +function loadWardenConfig(configDir) { + return loadWardenConfigFile(join(configDir, 'warden.toml')); +} +function mergeArray(base, overlay) { + const merged = [...(base ?? []), ...(overlay ?? [])]; + return merged.length > 0 ? merged : undefined; +} +function mergeCoalesceConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { ...base, ...overlay }; +} +function mergeChunkingConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { + ...base, + ...overlay, + filePatterns: mergeArray(base.filePatterns, overlay.filePatterns), + coalesce: mergeCoalesceConfig(base.coalesce, overlay.coalesce), + }; +} +function mergeIgnoreConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + // Preserve order: overlay negations must be able to re-include base ignores. + const paths = mergeArray(base.paths, overlay.paths); + return paths ? { paths } : undefined; +} +function mergeScanConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { ...base, ...overlay }; +} +function mergeNestedConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { ...base, ...overlay }; +} +function mergeDefaults(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { + ...base, + ...overlay, + agent: mergeNestedConfig(base.agent, overlay.agent), + auxiliary: mergeNestedConfig(base.auxiliary, overlay.auxiliary), + synthesis: mergeNestedConfig(base.synthesis, overlay.synthesis), + verification: mergeNestedConfig(base.verification, overlay.verification), + ignorePaths: mergeArray(base.ignorePaths, overlay.ignorePaths), + chunking: mergeChunkingConfig(base.chunking, overlay.chunking), + ignore: mergeIgnoreConfig(base.ignore, overlay.ignore), + scan: mergeScanConfig(base.scan, overlay.scan), + }; +} +function mergeRunnerConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { ...base, ...overlay }; +} +function mergeLogsConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + return { ...base, ...overlay }; +} +function mergeServiceConfig(base, overlay) { + if (!base) + return overlay; + if (!overlay) + return base; + const merged = { ...base, ...overlay }; + if (overlay.data === 'metrics' && overlay.memory === undefined) { + delete merged.memory; + } + return merged; +} +function effectiveAgentDefaults(defaults) { + const model = emptyToUndefined(defaults?.agent?.model) ?? emptyToUndefined(defaults?.model); + const maxTurns = defaults?.agent?.maxTurns ?? defaults?.maxTurns; + const effort = defaults?.agent?.effort; + const effective = {}; + if (model !== undefined) + effective.model = model; + if (maxTurns !== undefined) + effective.maxTurns = maxTurns; + if (effort !== undefined) + effective.effort = effort; + return Object.keys(effective).length > 0 ? effective : undefined; +} +function effectiveAuxiliaryDefaults(defaults) { + const model = emptyToUndefined(defaults?.auxiliary?.model); + const effort = defaults?.auxiliary?.effort; + const maxRetries = defaults?.auxiliary?.maxRetries ?? defaults?.auxiliaryMaxRetries; + const effective = {}; + if (model !== undefined) + effective.model = model; + if (effort !== undefined) + effective.effort = effort; + if (maxRetries !== undefined) + effective.maxRetries = maxRetries; + return Object.keys(effective).length > 0 ? effective : undefined; +} +function effectiveSynthesisDefaults(defaults) { + const model = emptyToUndefined(defaults?.synthesis?.model); + return model === undefined ? undefined : { model }; +} +function inheritRepoLayerDefaults(base, repo) { + const inherited = { ...(repo ?? {}) }; + // Normalize legacy and nested fields before merging so either repo syntax + // overrides the corresponding base execution default. + const agent = mergeNestedConfig(effectiveAgentDefaults(base), effectiveAgentDefaults(repo)); + if (agent) { + inherited.agent = agent; + } + const auxiliary = mergeNestedConfig(effectiveAuxiliaryDefaults(base), effectiveAuxiliaryDefaults(repo)); + if (auxiliary) { + inherited.auxiliary = auxiliary; + } + const synthesis = mergeNestedConfig(effectiveSynthesisDefaults(base), effectiveSynthesisDefaults(repo)); + if (synthesis) { + inherited.synthesis = synthesis; + } + if (base?.runtime !== undefined && inherited.runtime === undefined) { + inherited.runtime = base.runtime; + } + // The app that writes Warden's checks is a property of the workflow run, so + // repo skills trust the same app as org skills unless the repo names one. + if (base?.incrementalApp !== undefined && inherited.incrementalApp === undefined) { + inherited.incrementalApp = base.incrementalApp; + } + // Offline is sticky across layers: either layer can force offline for the run. + if (base?.offline === true || repo?.offline === true) { + inherited.offline = true; + } + const verification = mergeNestedConfig(base?.verification, repo?.verification); + if (verification) { + inherited.verification = verification; + } + return Object.keys(inherited).length > 0 ? inherited : undefined; +} +function withoutBaseDuplicateSkills(base, repo, options = {}) { + const baseSkillNames = new Set(base.skills.map((skill) => skill.name)); + const skipped = new Set(); + const skills = repo.skills.filter((skill) => { + if (!baseSkillNames.has(skill.name)) { + return true; + } + skipped.add(skill.name); + return false; + }); + for (const skillName of skipped) { + const basePath = options.baseConfigPath ?? 'base config'; + const repoPath = options.repoConfigPath ?? 'repo config'; + options.onWarning?.(`Skill "${skillName}" is defined in both ${basePath} and ${repoPath}. ` + + 'Using the base config skill and ignoring the repo config duplicate.'); + } + return skipped.size > 0 ? { ...repo, skills } : repo; +} +function mergeWardenConfigs(base, overlay, options = {}) { + const effectiveOverlay = withoutBaseDuplicateSkills(base, overlay, options); + const mergedConfig = { + version: 1, + defaults: mergeDefaults(base.defaults, effectiveOverlay.defaults), + skills: [...base.skills, ...effectiveOverlay.skills], + runner: mergeRunnerConfig(base.runner, effectiveOverlay.runner), + logs: mergeLogsConfig(base.logs, effectiveOverlay.logs), + service: mergeServiceConfig(base.service, effectiveOverlay.service), + }; + const result = _schema_js__WEBPACK_IMPORTED_MODULE_6__/* .WardenConfigSchema */ .kV.safeParse(mergedConfig); + if (!result.success) { + const issues = result.error.issues.map(i => ` - ${i.path.join('.')}: ${i.message}`).join('\n'); + throw new ConfigLoadError(`Invalid merged configuration:\n${issues}`); + } + return result.data; +} +function buildSkillRootsByName(repoPath, layered, baseSkillRoot) { + const baseRoots = {}; + const repoRoots = {}; + if (layered.baseConfig) { + const localBaseSkills = layered.baseConfig.skills.filter((skill) => !skill.remote); + const localBaseSkillsRequiringRoot = localBaseSkills.filter((skill) => !(0,_skills_loader_js__WEBPACK_IMPORTED_MODULE_5__/* .isBuiltinSkillName */ .OB)(skill.name)); + if (localBaseSkillsRequiringRoot.length > 0 && !baseSkillRoot) { + throw new ConfigLoadError('base-skill-root is required when the base config defines local skills'); + } + if (baseSkillRoot) { + const resolvedBaseSkillRoot = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(repoPath, baseSkillRoot); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(resolvedBaseSkillRoot)) { + throw new ConfigLoadError(`Skill root not found: ${resolvedBaseSkillRoot}`); + } + for (const skill of localBaseSkills) { + baseRoots[skill.name] = resolvedBaseSkillRoot; + } + } + else { + for (const skill of localBaseSkills) { + if ((0,_skills_loader_js__WEBPACK_IMPORTED_MODULE_5__/* .isBuiltinSkillName */ .OB)(skill.name)) { + baseRoots[skill.name] = undefined; + } + } + } + } + if (layered.repoConfig) { + for (const skill of layered.repoConfig.skills) { + if (!skill.remote) { + repoRoots[skill.name] = repoPath; + } + } + } + const result = {}; + if (Object.keys(baseRoots).length > 0) { + result.base = baseRoots; + } + if (Object.keys(repoRoots).length > 0) { + result.repo = repoRoots; + } + return result.base || result.repo ? result : undefined; +} +function loadLayeredWardenConfig(repoPath, options = {}) { + const repoConfigPath = (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(repoPath, options.configPath ?? 'warden.toml'); + const baseConfigPath = options.baseConfigPath + ? (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(repoPath, options.baseConfigPath) + : undefined; + if (baseConfigPath && !(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(baseConfigPath)) { + throw new ConfigLoadError(`Configuration file not found: ${baseConfigPath}`); + } + if (!baseConfigPath) { + const repoConfig = loadWardenConfigFile(repoConfigPath); + return { config: repoConfig, repoConfig }; + } + if ((0,node_path__WEBPACK_IMPORTED_MODULE_2__.normalize)(baseConfigPath) === (0,node_path__WEBPACK_IMPORTED_MODULE_2__.normalize)(repoConfigPath)) { + throw new ConfigLoadError('base-config-path and config-path must point to different files'); + } + const baseConfig = loadWardenConfigFile(baseConfigPath); + if (!(0,node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(repoConfigPath)) { + return { config: baseConfig, baseConfig }; + } + const repoConfig = withoutBaseDuplicateSkills(baseConfig, loadWardenConfigFile(repoConfigPath), { + baseConfigPath: options.baseConfigPath, + repoConfigPath: options.configPath ?? 'warden.toml', + onWarning: options.onWarning, + }); + return { + config: mergeWardenConfigs(baseConfig, repoConfig), + baseConfig, + repoConfig, + }; +} +/** `id` is a verbose JSON blob, too unwieldy for a repeated cross-artifact join key. */ +function deriveSkillExecutionId(identity) { + return (0,node_crypto__WEBPACK_IMPORTED_MODULE_1__.createHash)('sha256').update(identity).digest('hex').slice(0, 12); +} +function triggerIdentity(skill, trigger) { + return JSON.stringify({ + skill: skill.name, + remote: skill.remote, + paths: skill.paths, + ignorePaths: skill.ignorePaths, + failOn: trigger?.failOn ?? skill.failOn, + reportOn: trigger?.reportOn ?? skill.reportOn, + maxFindings: trigger?.maxFindings ?? skill.maxFindings, + reportOnSuccess: trigger?.reportOnSuccess ?? skill.reportOnSuccess, + requestChanges: trigger?.requestChanges ?? skill.requestChanges, + failCheck: trigger?.failCheck ?? skill.failCheck, + model: trigger?.model ?? skill.model, + maxTurns: trigger?.maxTurns ?? skill.maxTurns, + verification: trigger?.verification?.enabled ?? skill.verification?.enabled, + minConfidence: trigger?.minConfidence ?? skill.minConfidence, + type: trigger?.type ?? '*', + actions: trigger?.actions, + draft: trigger?.draft, + labels: trigger?.labels, + schedule: trigger?.schedule, + }); +} +function resolveVerifyFindings(defaults, skill, trigger) { + return trigger?.verification?.enabled + ?? skill.verification?.enabled + ?? defaults?.verification?.enabled + ?? true; +} +function resolveSkillSource(skill, skillRootsByName) { + if (!skillRootsByName || !Object.hasOwn(skillRootsByName, skill.name)) { + return {}; + } + const skillRoot = skillRootsByName[skill.name]; + return { + skillRoot, + useBuiltinSkill: !skill.remote && skillRoot === undefined, + }; +} +/** + * Convert empty strings to undefined. + * GitHub Actions substitutes unconfigured secrets with empty strings, + * so we need to treat '' as "not set" for optional config values. + */ +function emptyToUndefined(value) { + return value === '' ? undefined : value; +} +/** + * Resolve all skills in a config into a flat array of ResolvedTriggers. + * Each skill x trigger combination produces one entry. + * Skills with no triggers produce one wildcard entry (type: '*'). + * + * Model precedence (highest to lowest): + * 1. trigger-level model + * 2. skill-level model + * 3. defaults.agent.model + * 4. defaults.model (legacy warden.toml [defaults]) + * 5. cliModel (--model flag) + * 6. WARDEN_MODEL env var + * 7. SDK default (not set here) + */ +function resolveSkillConfigs(config, cliModel, skillRootsByName) { + const defaults = config.defaults; + const envModel = emptyToUndefined(process.env['WARDEN_MODEL']); + const result = []; + const runtime = defaults?.runtime ?? 'pi'; + const auxiliaryModel = emptyToUndefined(defaults?.auxiliary?.model); + const auxiliaryEffort = defaults?.auxiliary?.effort; + const synthesisModel = emptyToUndefined(defaults?.synthesis?.model) ?? + auxiliaryModel; + const auxiliaryMaxRetries = defaults?.auxiliary?.maxRetries ?? + defaults?.auxiliaryMaxRetries; + for (const skill of config.skills) { + const skillSource = resolveSkillSource(skill, skillRootsByName); + const baseModel = emptyToUndefined(skill.model) ?? + emptyToUndefined(defaults?.agent?.model) ?? + emptyToUndefined(defaults?.model) ?? + emptyToUndefined(cliModel) ?? + envModel; + const baseMaxTurns = skill.maxTurns ?? defaults?.agent?.maxTurns ?? defaults?.maxTurns; + const effort = defaults?.agent?.effort; + // Merge ignorePaths: skill-level + defaults (additive, not override) + const mergedIgnorePaths = [ + ...(defaults?.ignorePaths ?? []), + ...(skill.ignorePaths ?? []), + ]; + const filters = { + paths: skill.paths, + ignorePaths: mergedIgnorePaths.length > 0 ? mergedIgnorePaths : undefined, + }; + if (!skill.triggers || skill.triggers.length === 0) { + // Wildcard: no triggers means run everywhere + result.push({ + id: triggerIdentity(skill, undefined), + skillExecutionId: deriveSkillExecutionId(triggerIdentity(skill, undefined)), + name: skill.name, + skill: skill.name, + type: '*', + remote: skill.remote, + ...skillSource, + filters, + failOn: skill.failOn ?? defaults?.failOn, + reportOn: skill.reportOn ?? defaults?.reportOn, + maxFindings: skill.maxFindings ?? defaults?.maxFindings, + reportOnSuccess: skill.reportOnSuccess ?? defaults?.reportOnSuccess, + requestChanges: skill.requestChanges ?? defaults?.requestChanges, + failCheck: skill.failCheck ?? defaults?.failCheck, + incremental: skill.incremental ?? defaults?.incremental, + incrementalApp: defaults?.incrementalApp, + model: baseModel, + maxTurns: baseMaxTurns, + effort, + runtime, + auxiliaryModel, + auxiliaryEffort, + synthesisModel, + auxiliaryMaxRetries, + verifyFindings: resolveVerifyFindings(defaults, skill), + minConfidence: skill.minConfidence ?? defaults?.minConfidence, + batchDelayMs: defaults?.batchDelayMs, + maxContextFiles: defaults?.chunking?.maxContextFiles, + ignore: defaults?.ignore, + scan: defaults?.scan, + chunking: defaults?.chunking, + }); + } + else { + for (const trigger of skill.triggers) { + result.push({ + id: triggerIdentity(skill, trigger), + skillExecutionId: deriveSkillExecutionId(triggerIdentity(skill, trigger)), + name: skill.name, + skill: skill.name, + type: trigger.type, + actions: trigger.actions, + draft: trigger.draft, + labels: trigger.labels, + remote: skill.remote, + ...skillSource, + filters, + // 3-level merge: trigger > skill > defaults + failOn: trigger.failOn ?? skill.failOn ?? defaults?.failOn, + reportOn: trigger.reportOn ?? skill.reportOn ?? defaults?.reportOn, + maxFindings: trigger.maxFindings ?? skill.maxFindings ?? defaults?.maxFindings, + reportOnSuccess: trigger.reportOnSuccess ?? skill.reportOnSuccess ?? defaults?.reportOnSuccess, + requestChanges: trigger.requestChanges ?? skill.requestChanges ?? defaults?.requestChanges, + failCheck: trigger.failCheck ?? skill.failCheck ?? defaults?.failCheck, + incremental: trigger.incremental ?? skill.incremental ?? defaults?.incremental, + incrementalApp: defaults?.incrementalApp, + model: emptyToUndefined(trigger.model) ?? baseModel, + maxTurns: trigger.maxTurns ?? baseMaxTurns, + effort, + runtime, + auxiliaryModel, + auxiliaryEffort, + synthesisModel, + auxiliaryMaxRetries, + verifyFindings: resolveVerifyFindings(defaults, skill, trigger), + minConfidence: trigger.minConfidence ?? skill.minConfidence ?? defaults?.minConfidence, + batchDelayMs: defaults?.batchDelayMs, + maxContextFiles: defaults?.chunking?.maxContextFiles, + ignore: defaults?.ignore, + scan: defaults?.scan, + chunking: defaults?.chunking, + schedule: trigger.schedule, + }); + } + } + } + return result; +} +function resolveLayeredSkillConfigs(layered, cliModel, skillRootsByName) { + if (layered.baseConfig && layered.repoConfig) { + const repoConfig = withoutBaseDuplicateSkills(layered.baseConfig, layered.repoConfig); + const repoConfigWithInheritedDefaults = { + ...repoConfig, + defaults: inheritRepoLayerDefaults(layered.baseConfig.defaults, repoConfig.defaults), + }; + return [ + ...resolveSkillConfigs(layered.baseConfig, cliModel, skillRootsByName?.base), + ...resolveSkillConfigs(repoConfigWithInheritedDefaults, cliModel, skillRootsByName?.repo), + ]; + } + if (layered.baseConfig) { + return resolveSkillConfigs(layered.baseConfig, cliModel, skillRootsByName?.base); + } + if (layered.repoConfig) { + return resolveSkillConfigs(layered.repoConfig, cliModel, skillRootsByName?.repo); + } + return resolveSkillConfigs(layered.config, cliModel, skillRootsByName?.repo ?? skillRootsByName?.base); +} + + +/***/ }), + +/***/ 96120: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + H0: () => (/* binding */ DEFAULT_SCAN_LIMITS), + Tx: () => (/* binding */ ServiceConfigSchema), + kV: () => (/* binding */ WardenConfigSchema) +}); + +// UNUSED EXPORTS: AgentRuntimeConfigSchema, AuxiliaryRuntimeConfigSchema, ChunkingConfigSchema, CoalesceConfigSchema, DefaultsSchema, EffortSchema, FilePatternSchema, IgnoreConfigSchema, LogCleanupModeSchema, LogsConfigSchema, RunnerConfigSchema, RuntimeNameSchema, ScanConfigSchema, ScheduleConfigSchema, SkillConfigSchema, SkillDefinitionSchema, SkillTriggerSchema, SynthesisRuntimeConfigSchema, ToolConfigSchema, ToolNameSchema, TriggerTypeSchema, VerificationConfigSchema + +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js + 7 modules +var schemas = __webpack_require__(51737); +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js +var compat = __webpack_require__(40231); +// EXTERNAL MODULE: ../warden-service-api/dist/index.js + 5 modules +var dist = __webpack_require__(15747); +;// CONCATENATED MODULE: ./src/sdk/runtimes/types.ts +/** + * Runtime contract for model-backed providers. + * + * Warden's analysis pipeline builds prompts, handles retry policy, parses + * findings, and aggregates report data. Runtime interfaces are backend + * capabilities underneath that pipeline. Runtimes expose skill execution, + * auxiliary model tasks, and synthesis tasks. + * + * Runtime implementations are responsible for backend-specific execution + * details such as model identifiers, stream events, authentication side + * channels, stderr/diagnostics, telemetry attributes, tool loops, and usage + * normalization. Callers should be able to switch runtimes without changing + * hunk parsing, extraction repair, deduplication, fix gates, or reporting. + */ + +const RuntimeNameSchema = schemas/* enum */.k5n(['claude', 'pi']); + +// EXTERNAL MODULE: ./src/types/index.ts +var types = __webpack_require__(78481); +;// CONCATENATED MODULE: ./src/config/schema.ts + + + + +// Tool names that can be allowed/denied +const ToolNameSchema = schemas/* enum */.k5n([ + 'Read', + 'Write', + 'Edit', + 'Bash', + 'Glob', + 'Grep', + 'WebFetch', + 'WebSearch', +]); +// Tool configuration for skills +const ToolConfigSchema = schemas/* object */.Ikc({ + allowed: schemas/* array */.YOg(ToolNameSchema).optional(), + denied: schemas/* array */.YOg(ToolNameSchema).optional(), +}); +// Skill definition +const SkillDefinitionSchema = schemas/* object */.Ikc({ + name: schemas/* string */.YjP().min(1), + description: schemas/* string */.YjP(), + prompt: schemas/* string */.YjP(), + tools: ToolConfigSchema.optional(), + /** Directory where the skill was loaded from, for resolving resources (scripts/, references/, assets/) */ + rootDir: schemas/* string */.YjP().optional(), +}); +// Schedule-specific configuration +const ScheduleConfigSchema = schemas/* object */.Ikc({ + /** Title for the tracking issue (default: "Warden: {skillName}") */ + issueTitle: schemas/* string */.YjP().optional(), +}); +// Trigger type: where the trigger runs +const TriggerTypeSchema = schemas/* enum */.k5n(['pull_request', 'local', 'schedule']); + +const EffortSchema = schemas/* enum */.k5n(['off', 'low', 'medium', 'high', 'xhigh', 'max']); +const AgentRuntimeConfigSchema = schemas/* object */.Ikc({ + /** Model for repo-aware skill execution. Overrides legacy defaults.model. */ + model: schemas/* string */.YjP().optional(), + /** Maximum agentic turns for repo-aware skill execution. Overrides legacy defaults.maxTurns. */ + maxTurns: schemas/* number */.aig().int().positive().optional(), + /** Effort level to use for repo-aware skill execution. Uses runtime default when omitted. */ + effort: EffortSchema.optional(), +}).strict(); +const AuxiliaryRuntimeConfigSchema = schemas/* object */.Ikc({ + /** Model for auxiliary structured model calls. Uses runtime default if omitted. */ + model: schemas/* string */.YjP().optional(), + /** Reasoning effort for auxiliary structured model calls. Uses runtime default when omitted. */ + effort: EffortSchema.optional(), + /** Max retries for auxiliary structured model calls. Overrides legacy auxiliaryMaxRetries. */ + maxRetries: schemas/* number */.aig().int().positive().optional(), +}).strict(); +const SynthesisRuntimeConfigSchema = schemas/* object */.Ikc({ + /** Model for post-analysis synthesis/consolidation. Falls back to auxiliary.model if omitted. */ + model: schemas/* string */.YjP().optional(), +}).strict(); +const VerificationConfigSchema = schemas/* object */.Ikc({ + /** Verify candidate findings in a second read-only pass. Defaults to true. */ + enabled: schemas/* boolean */.zMY().optional(), +}).strict(); +// Skill trigger definition (nested under [[skills.triggers]]) +const SkillTriggerSchema = schemas/* object */.Ikc({ + /** Trigger type: pull_request (GitHub), local (CLI), or schedule (cron) */ + type: TriggerTypeSchema, + /** Actions to trigger on (only for pull_request type) */ + actions: schemas/* array */.YOg(schemas/* string */.YjP()).min(1).optional(), + /** Match pull_request triggers by draft state. Set false to run only on non-draft PRs. */ + draft: schemas/* boolean */.zMY().optional(), + /** Match pull_request triggers when any listed label is present. */ + labels: schemas/* array */.YOg(schemas/* string */.YjP()).min(1).optional(), + // Per-trigger overrides (flattened output fields) + failOn: types/* SeverityThresholdSchema */.q$.optional(), + reportOn: types/* SeverityThresholdSchema */.q$.optional(), + maxFindings: schemas/* number */.aig().int().positive().optional(), + reportOnSuccess: schemas/* boolean */.zMY().optional(), + /** Use REQUEST_CHANGES review event when findings exceed failOn */ + requestChanges: schemas/* boolean */.zMY().optional(), + /** Fail the check run when findings exceed failOn */ + failCheck: schemas/* boolean */.zMY().optional(), + /** Skip hunks an earlier clean run on this PR already reviewed. Overrides skill/defaults. */ + incremental: schemas/* boolean */.zMY().optional(), + model: schemas/* string */.YjP().optional(), + maxTurns: schemas/* number */.aig().int().positive().optional(), + /** Candidate finding verification. Overrides skill/defaults verification. */ + verification: VerificationConfigSchema.optional(), + /** Minimum confidence level for findings. Findings below this are filtered from output. */ + minConfidence: types/* ConfidenceThresholdSchema */.HA.optional(), + /** Schedule-specific configuration. Only used when type is 'schedule'. */ + schedule: ScheduleConfigSchema.optional(), +}).superRefine((data, ctx) => { + if (data.type === 'pull_request' && (!data.actions || data.actions.length === 0)) { + ctx.addIssue({ + code: compat/* ZodIssueCode */.eq.custom, + message: "actions is required for pull_request triggers", + path: ["actions"], + }); + } + if (data.type !== 'pull_request' && data.labels) { + ctx.addIssue({ + code: compat/* ZodIssueCode */.eq.custom, + message: "labels is only supported for pull_request triggers", + path: ["labels"], + }); + } +}); +// Skill configuration (top-level [[skills]]) +const SkillConfigSchema = schemas/* object */.Ikc({ + name: schemas/* string */.YjP().min(1), + /** Path patterns to include */ + paths: schemas/* array */.YOg(schemas/* string */.YjP()).optional(), + /** Path patterns to exclude */ + ignorePaths: schemas/* array */.YOg(schemas/* string */.YjP()).optional(), + /** Remote repository reference for the skill (e.g., "owner/repo" or "owner/repo@sha") */ + remote: schemas/* string */.YjP().optional(), + // Flattened output fields (skill-level defaults) + failOn: types/* SeverityThresholdSchema */.q$.optional(), + reportOn: types/* SeverityThresholdSchema */.q$.optional(), + maxFindings: schemas/* number */.aig().int().positive().optional(), + reportOnSuccess: schemas/* boolean */.zMY().optional(), + /** Use REQUEST_CHANGES review event when findings exceed failOn */ + requestChanges: schemas/* boolean */.zMY().optional(), + /** Fail the check run when findings exceed failOn */ + failCheck: schemas/* boolean */.zMY().optional(), + /** Skip hunks an earlier clean run on this PR already reviewed. Overrides defaults.incremental. */ + incremental: schemas/* boolean */.zMY().optional(), + /** Model to use for this skill (e.g., 'openai/gpt-5.5'). Uses SDK default if not specified. */ + model: schemas/* string */.YjP().optional(), + /** Maximum agentic turns (API round-trips) per hunk analysis. Overrides defaults.maxTurns. */ + maxTurns: schemas/* number */.aig().int().positive().optional(), + /** Candidate finding verification. Overrides defaults.verification. */ + verification: VerificationConfigSchema.optional(), + /** Minimum confidence level for findings. Findings below this are filtered from output. */ + minConfidence: types/* ConfidenceThresholdSchema */.HA.optional(), + /** Triggers defining when/where this skill runs. Omit to run everywhere (wildcard). */ + triggers: schemas/* array */.YOg(SkillTriggerSchema).optional(), +}); +// Runner configuration +const RunnerConfigSchema = schemas/* object */.Ikc({ + /** Max concurrent hunk analyses across all skills (default: 4) */ + concurrency: schemas/* number */.aig().int().positive().optional(), +}); +// File pattern for chunking configuration +const FilePatternSchema = schemas/* object */.Ikc({ + /** Glob pattern to match files (e.g., "**\/pnpm-lock.yaml") */ + pattern: schemas/* string */.YjP(), + /** How to handle matching files: 'per-hunk' (default), 'whole-file', or 'skip' */ + mode: schemas/* enum */.k5n(['per-hunk', 'whole-file', 'skip']).default('skip'), +}); +// Coalescing configuration for merging nearby hunks +const CoalesceConfigSchema = schemas/* object */.Ikc({ + /** Enable hunk coalescing (default: true) */ + enabled: schemas/* boolean */.zMY().default(true), + /** Max lines gap between hunks to merge (default: 30) */ + maxGapLines: schemas/* number */.aig().int().nonnegative().default(30), + /** Target max size per chunk in characters (default: 8000) */ + maxChunkSize: schemas/* number */.aig().int().positive().default(8000), +}); +// Chunking configuration for controlling how files are processed +const ChunkingConfigSchema = schemas/* object */.Ikc({ + /** Patterns to control file processing mode */ + filePatterns: schemas/* array */.YOg(FilePatternSchema).optional(), + /** Coalescing options for merging nearby hunks */ + coalesce: CoalesceConfigSchema.optional(), + /** Max number of "other files" to list in hunk prompts for PR context. 0 disables the section entirely. Default: 50 */ + maxContextFiles: schemas/* number */.aig().int().nonnegative().default(50), +}); +const IgnoreConfigSchema = schemas/* object */.Ikc({ + /** Gitignore-style path patterns to ignore. Prefix with ! to re-include. */ + paths: schemas/* array */.YOg(schemas/* string */.YjP()).optional(), +}).strict(); +const ScanConfigSchema = schemas/* object */.Ikc({ + /** Max files to analyze after ignores are applied. Default: 150 */ + maxFiles: schemas/* number */.aig().int().positive().optional(), + /** Max changed lines to analyze after ignores are applied. Default: 10000 */ + maxChangedLines: schemas/* number */.aig().int().positive().optional(), + /** Max file size in bytes for files whose contents may be read. Default: 1048576 */ + maxFileBytes: schemas/* number */.aig().int().positive().optional(), + /** Max file length in lines for files whose contents may be read. Default: 3000 */ + maxFileLines: schemas/* number */.aig().int().positive().optional(), +}).strict(); +const DEFAULT_SCAN_LIMITS = { + maxFiles: 150, + maxChangedLines: 10_000, + maxFileBytes: 1_048_576, + maxFileLines: 3_000, +}; +// Default configuration that skills inherit from +const DefaultsSchema = schemas/* object */.Ikc({ + /** Fail the build when findings meet this severity */ + failOn: types/* SeverityThresholdSchema */.q$.optional(), + /** Only report findings at or above this severity */ + reportOn: types/* SeverityThresholdSchema */.q$.optional(), + maxFindings: schemas/* number */.aig().int().positive().optional(), + /** Report even when there are no findings (default: false) */ + reportOnSuccess: schemas/* boolean */.zMY().optional(), + /** Use REQUEST_CHANGES review event when findings exceed failOn. Default: false */ + requestChanges: schemas/* boolean */.zMY().optional(), + /** Fail the check run when findings exceed failOn. Default: false */ + failCheck: schemas/* boolean */.zMY().optional(), + /** + * Skip hunks an earlier clean run on this PR already reviewed with the same + * skill config. Pull request runs in the GitHub Action only. Default: false + */ + incremental: schemas/* boolean */.zMY().optional(), + /** + * Slug of the GitHub App that writes Warden's check runs. Only its checks + * count as incremental baselines. Required for incremental review. + */ + incrementalApp: schemas/* string */.YjP().min(1).optional(), + /** Create/update GitHub Check runs (core + per-skill). Default: true */ + postChecks: schemas/* boolean */.zMY().optional(), + /** Default model for all skills (e.g., 'openai/gpt-5.5') */ + model: schemas/* string */.YjP().optional(), + /** Maximum agentic turns (API round-trips) per hunk analysis. Default: 50 */ + maxTurns: schemas/* number */.aig().int().positive().optional(), + /** Runtime backend for all model-backed execution. Default: pi */ + runtime: RuntimeNameSchema.optional(), + /** + * Block network access for remote skills and Pi model-catalog refresh. + * Prefer this durable setting for both. CLI `--offline` and `WARDEN_OFFLINE` + * enable the same for one run. + */ + offline: schemas/* boolean */.zMY().optional(), + /** Model defaults for repo-aware skill execution. */ + agent: AgentRuntimeConfigSchema.optional(), + /** Model defaults for auxiliary structured model calls. */ + auxiliary: AuxiliaryRuntimeConfigSchema.optional(), + /** Model defaults for post-analysis synthesis/consolidation. */ + synthesis: SynthesisRuntimeConfigSchema.optional(), + /** Candidate finding verification. Enabled by default; set enabled=false to opt out. */ + verification: VerificationConfigSchema.optional(), + /** Minimum confidence level for findings. Findings below this are filtered from output. Default: medium */ + minConfidence: types/* ConfidenceThresholdSchema */.HA.optional(), + /** Path patterns to exclude from all skills */ + ignorePaths: schemas/* array */.YOg(schemas/* string */.YjP()).optional(), + /** Default branch for the repository (e.g., 'main', 'master', 'develop'). Auto-detected if not specified. */ + defaultBranch: schemas/* string */.YjP().optional(), + /** Chunking configuration for controlling how files are processed */ + chunking: ChunkingConfigSchema.optional(), + /** Global file ignore policy applied before scan limits and chunking */ + ignore: IgnoreConfigSchema.optional(), + /** Global scan limits applied after ignore filtering */ + scan: ScanConfigSchema.optional(), + /** Delay applied before each analysis dispatched after the first concurrent wave. Default: 0 */ + batchDelayMs: schemas/* number */.aig().int().nonnegative().optional(), + /** Max retries for auxiliary structured model calls (extraction repair, merging, dedup, fix evaluation). Default: 5 */ + auxiliaryMaxRetries: schemas/* number */.aig().int().positive().optional(), +}); +// Log cleanup mode +const LogCleanupModeSchema = schemas/* enum */.k5n(['ask', 'auto', 'never']); +// Logs configuration +const LogsConfigSchema = schemas/* object */.Ikc({ + /** How to handle expired log files: 'ask' (default, prompt in TTY), 'auto' (silently delete), 'never' (keep all) */ + cleanup: LogCleanupModeSchema.default('ask'), + /** Number of days to retain log files before considering them expired. Default: 30 */ + retentionDays: schemas/* number */.aig().int().positive().default(30), +}); +const ServiceEndpointSchema = schemas/* string */.YjP().url().refine((value) => { + let endpoint; + try { + endpoint = new URL(value); + } + catch { + return false; + } + if (endpoint.username || endpoint.password) + return false; + if (endpoint.protocol === 'https:') + return true; + return endpoint.protocol === 'http:' + && ['localhost', '127.0.0.1', '[::1]'].includes(endpoint.hostname); +}, 'Service URL must use HTTPS, except for local development'); +const ServiceConfigSchema = schemas/* object */.Ikc({ + /** Optional endpoint. Environment credentials are never paired with a config-only URL. */ + url: ServiceEndpointSchema.optional(), + /** Maximum class of run data sent to the service. Default: findings. */ + data: dist/* DataProfileSchema */.ly.default('findings'), + /** Recall and learn repository memory. The final service resolver applies profile-aware defaults. */ + memory: schemas/* boolean */.zMY().optional(), + /** Total deadline for each optional service operation. */ + timeoutMs: schemas/* number */.aig().int().min(100).max(30_000).default(2_000), +}).superRefine((service, context) => { + if (service.memory && service.data === 'metrics') { + context.addIssue({ + code: compat/* ZodIssueCode */.eq.custom, + path: ['memory'], + message: 'service.memory requires service.data to be findings or code', + }); + } +}); +// Main warden.toml configuration +const WardenConfigSchema = schemas/* object */.Ikc({ + version: schemas/* literal */.euz(1), + defaults: DefaultsSchema.optional(), + skills: schemas/* array */.YOg(SkillConfigSchema).default([]), + runner: RunnerConfigSchema.optional(), + logs: LogsConfigSchema.optional(), + service: ServiceConfigSchema.optional(), +}) + .superRefine((config, ctx) => { + const names = config.skills.map((s) => s.name); + const duplicates = names.filter((name, i) => names.indexOf(name) !== i); + if (duplicates.length > 0) { + ctx.addIssue({ + code: compat/* ZodIssueCode */.eq.custom, + message: `Duplicate skill names: ${[...new Set(duplicates)].join(', ')}`, + path: ['skills'], + }); + } + // Validate schedule skills have paths + for (const [i, skill] of config.skills.entries()) { + if (skill.triggers) { + for (const trigger of skill.triggers) { + if (trigger.type === 'schedule' && (!skill.paths || skill.paths.length === 0)) { + ctx.addIssue({ + code: compat/* ZodIssueCode */.eq.custom, + message: "paths is required for skills with schedule triggers", + path: ['skills', i, 'paths'], + }); + } + } + } + } +}); + + +/***/ }), + +/***/ 96497: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + TX: () => (/* reexport */ classifyFile), + x$: () => (/* reexport */ coalesceHunks), + ZC: () => (/* reexport */ expandDiffContext), + xP: () => (/* reexport */ formatHunkForAnalysis), + sK: () => (/* reexport */ getHunkLineRange), + jx: () => (/* reexport */ parseFileDiff), + iz: () => (/* reexport */ parsePatch), + PQ: () => (/* reexport */ splitLargeHunks) +}); + +// UNUSED EXPORTS: DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_GAP_LINES, applyDiffToContent, clearFileCache, expandHunkContext, getExpandedLineRange, wouldCoalesceReduce + +;// CONCATENATED MODULE: ./src/diff/parser.ts +/** + * Unified diff parser - extracts hunks from patch strings + */ +/** + * Parse a unified diff hunk header. + * Format: @@ -oldStart,oldCount +newStart,newCount @@ optional header + */ +function parseHunkHeader(line) { + const match = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/); + if (!match || !match[1] || !match[3]) + return null; + return { + oldStart: parseInt(match[1], 10), + oldCount: parseInt(match[2] ?? '1', 10), + newStart: parseInt(match[3], 10), + newCount: parseInt(match[4] ?? '1', 10), + header: match[5]?.trim() || undefined, + }; +} +/** + * Parse a unified diff patch into hunks. + */ +function parsePatch(patch) { + const lines = patch.split('\n'); + const hunks = []; + let currentHunk = null; + for (const line of lines) { + const header = parseHunkHeader(line); + if (header) { + // Save previous hunk if exists + if (currentHunk) { + hunks.push({ + ...currentHunk, + content: currentHunk.contentParts.join('\n'), + }); + } + // Start new hunk with array-based content builder + currentHunk = { + ...header, + contentParts: [line], + lines: [], + }; + } + else if (currentHunk) { + // Add line to current hunk (skip diff metadata lines) + if (!line.startsWith('diff --git') && + !line.startsWith('index ') && + !line.startsWith('--- ') && + !line.startsWith('+++ ') && + !line.startsWith('\\ No newline')) { + currentHunk.contentParts.push(line); + currentHunk.lines.push(line); + } + } + } + // Don't forget the last hunk + if (currentHunk) { + hunks.push({ + ...currentHunk, + content: currentHunk.contentParts.join('\n'), + }); + } + return hunks; +} +/** + * Parse a file's patch into a structured diff object. + */ +function parseFileDiff(filename, patch, status = 'modified') { + return { + filename, + status, + hunks: parsePatch(patch), + rawPatch: patch, + }; +} +/** + * Get the line range covered by a hunk (in the new file). + */ +function getHunkLineRange(hunk) { + return { + start: hunk.newStart, + end: hunk.newStart + hunk.newCount - 1, + }; +} +/** + * Get an expanded line range for context. + */ +function getExpandedLineRange(hunk, contextLines = 20) { + const range = getHunkLineRange(hunk); + return { + start: Math.max(1, range.start - contextLines), + end: range.end + contextLines, + }; +} + +// EXTERNAL MODULE: external "node:child_process" +var external_node_child_process_ = __webpack_require__(31421); +// EXTERNAL MODULE: external "node:fs" +var external_node_fs_ = __webpack_require__(73024); +// EXTERNAL MODULE: external "node:path" +var external_node_path_ = __webpack_require__(76760); +// EXTERNAL MODULE: ./src/utils/exec.ts +var exec = __webpack_require__(82224); +;// CONCATENATED MODULE: ./src/diff/context.ts + + + + + +/** Cache for file contents to avoid repeated reads */ +const fileCache = new Map(); +/** Clear the file cache (useful for testing or long-running processes) */ +function clearFileCache() { + fileCache.clear(); +} +/** Get cached file lines or read and cache them */ +function normalizeOptions(options) { + if (typeof options === 'number') { + return { + contextLines: options, + contentSource: { type: 'working-tree' }, + }; + } + return { + contextLines: options.contextLines ?? 20, + contentSource: options.contentSource ?? { type: 'working-tree' }, + }; +} +function cacheKey(repoPath, filename, source) { + const sourceKey = source.type === 'git-ref' ? `${source.type}:${source.ref}` : source.type; + return `${sourceKey}:${repoPath}:${filename}`; +} +function isInsideRepo(repoPath, filename) { + const resolvedRepo = (0,external_node_path_.resolve)(repoPath); + const resolvedFile = (0,external_node_path_.resolve)((0,external_node_path_.join)(repoPath, filename)); + return resolvedFile === resolvedRepo || resolvedFile.startsWith(resolvedRepo + '/'); +} +function readWorkingTreeLines(repoPath, filename) { + const filePath = (0,external_node_path_.join)(repoPath, filename); + if (!(0,external_node_fs_.existsSync)(filePath)) { + return null; + } + try { + const content = (0,external_node_fs_.readFileSync)(filePath, 'utf-8'); + return content.split('\n'); + } + catch { + // Binary file or read error + return null; + } +} +function readGitSourceLines(repoPath, filename, source) { + const refPath = source.type === 'git-index' + ? `:${filename}` + : `${source.ref}:${filename}`; + const result = (0,external_node_child_process_.spawnSync)('git', ['show', refPath], { + cwd: repoPath, + encoding: 'utf-8', + env: { ...process.env, ...exec/* GIT_NON_INTERACTIVE_ENV */.OO }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + if (result.error || result.status !== 0 || typeof result.stdout !== 'string') { + return null; + } + return result.stdout.split('\n'); +} +/** Get cached file lines or read and cache them */ +function getCachedFileLines(repoPath, filename, source) { + const key = cacheKey(repoPath, filename, source); + if (fileCache.has(key)) { + return fileCache.get(key) ?? null; + } + if (!isInsideRepo(repoPath, filename)) { + fileCache.set(key, null); + return null; + } + const lines = source.type === 'working-tree' + ? readWorkingTreeLines(repoPath, filename) + : readGitSourceLines(repoPath, filename, source); + fileCache.set(key, lines); + return lines; +} +/** + * Detect language from filename. + */ +function detectLanguage(filename) { + const ext = filename.split('.').pop()?.toLowerCase() ?? ''; + const languageMap = { + ts: 'typescript', + tsx: 'typescript', + js: 'javascript', + jsx: 'javascript', + py: 'python', + rb: 'ruby', + go: 'go', + rs: 'rust', + java: 'java', + kt: 'kotlin', + cs: 'csharp', + cpp: 'cpp', + c: 'c', + h: 'c', + hpp: 'cpp', + swift: 'swift', + php: 'php', + sh: 'bash', + bash: 'bash', + zsh: 'bash', + yml: 'yaml', + yaml: 'yaml', + json: 'json', + toml: 'toml', + md: 'markdown', + sql: 'sql', + html: 'html', + css: 'css', + scss: 'scss', + less: 'less', + }; + return languageMap[ext] ?? ext; +} +/** + * Read specific lines from a file using the cache. + * Returns empty array if file doesn't exist or is binary. + */ +function readFileLines(repoPath, filename, source, startLine, endLine) { + const lines = getCachedFileLines(repoPath, filename, source); + if (!lines) { + return []; + } + // Lines are 1-indexed, arrays are 0-indexed + return lines.slice(startLine - 1, endLine); +} +/** + * Expand a hunk with surrounding context from the actual file. + */ +function expandHunkContext(repoPath, filename, hunk, options = 20) { + const { contextLines, contentSource } = normalizeOptions(options); + // Defense-in-depth: ensure filename doesn't escape repo directory + if (!isInsideRepo(repoPath, filename)) { + return { filename, hunk, contextBefore: [], contextAfter: [], contextStartLine: 1, language: detectLanguage(filename) }; + } + const expandedRange = getExpandedLineRange(hunk, contextLines); + // Read context before the hunk + const contextBefore = readFileLines(repoPath, filename, contentSource, expandedRange.start, hunk.newStart - 1); + // Read context after the hunk + const contextAfter = readFileLines(repoPath, filename, contentSource, hunk.newStart + hunk.newCount, expandedRange.end); + return { + filename, + hunk, + contextBefore, + contextAfter, + contextStartLine: expandedRange.start, + language: detectLanguage(filename), + }; +} +/** + * Expand all hunks in a parsed diff with context. + */ +function expandDiffContext(repoPath, diff, options = 20) { + return diff.hunks.map((hunk) => expandHunkContext(repoPath, diff.filename, hunk, options)); +} +/** + * Format a hunk with context for LLM analysis. + */ +function formatHunkForAnalysis(hunkCtx) { + const lines = []; + lines.push(`## File: ${hunkCtx.filename}`); + lines.push(`## Language: ${hunkCtx.language}`); + lines.push(`## Hunk: lines ${hunkCtx.hunk.newStart}-${hunkCtx.hunk.newStart + hunkCtx.hunk.newCount - 1}`); + if (hunkCtx.hunk.header) { + lines.push(`## Scope: ${hunkCtx.hunk.header}`); + } + lines.push(''); + // Context before + if (hunkCtx.contextBefore.length > 0) { + lines.push(`### Context Before (lines ${hunkCtx.contextStartLine}-${hunkCtx.hunk.newStart - 1})`); + lines.push('```' + hunkCtx.language); + lines.push(hunkCtx.contextBefore.join('\n')); + lines.push('```'); + lines.push(''); + } + // The actual changes + lines.push(`### Changes`); + lines.push('```diff'); + lines.push(hunkCtx.hunk.content); + lines.push('```'); + lines.push(''); + // Context after + if (hunkCtx.contextAfter.length > 0) { + const afterStart = hunkCtx.hunk.newStart + hunkCtx.hunk.newCount; + const afterEnd = afterStart + hunkCtx.contextAfter.length - 1; + lines.push(`### Context After (lines ${afterStart}-${afterEnd})`); + lines.push('```' + hunkCtx.language); + lines.push(hunkCtx.contextAfter.join('\n')); + lines.push('```'); + } + return lines.join('\n'); +} + +// EXTERNAL MODULE: ./src/triggers/matcher.ts +var matcher = __webpack_require__(49431); +;// CONCATENATED MODULE: ./src/diff/classify.ts +/** + * File classification for chunking - determines how files should be processed + */ + +/** + * Classify a file to determine how it should be processed. + * + * @param filename - The file path to classify + * @param userPatterns - Optional user-defined chunking patterns + * @returns The processing mode: 'per-hunk', 'whole-file', or 'skip' + */ +function classifyFile(filename, userPatterns) { + for (const { pattern, mode } of userPatterns ?? []) { + if ((0,matcher/* matchGlob */.sB)(pattern, filename)) { + return mode; + } + } + return 'per-hunk'; +} + +;// CONCATENATED MODULE: ./src/diff/coalesce.ts +/** + * Hunk coalescing and splitting - manages hunk sizes for LLM analysis. + * + * - splitLargeHunks: Breaks large hunks into smaller chunks at logical breakpoints + * - coalesceHunks: Merges nearby small hunks into fewer, larger chunks + * + * Pipeline: parsePatch() → splitLargeHunks() → coalesceHunks() → expandDiffContext() + */ +/** Default maximum gap in lines between hunks to merge */ +const DEFAULT_MAX_GAP_LINES = 30; +/** Default maximum chunk size in characters */ +const DEFAULT_MAX_CHUNK_SIZE = 8000; +/** + * Merge two adjacent hunks into one. + * + * The merged hunk spans from the start of the first hunk to the end of the second, + * with content combined using '...' as a visual separator. When both hunks have + * different headers (indicating different function/class scopes), both are preserved. + */ +function mergeHunks(a, b) { + // Calculate the new range that spans both hunks + const newStart = Math.min(a.newStart, b.newStart); + const newEnd = Math.max(a.newStart + a.newCount, b.newStart + b.newCount); + const oldStart = Math.min(a.oldStart, b.oldStart); + const oldEnd = Math.max(a.oldStart + a.oldCount, b.oldStart + b.oldCount); + // Combine headers when both exist and are different + let header; + if (a.header && b.header && a.header !== b.header) { + header = `${a.header} → ${b.header}`; + } + else { + header = a.header ?? b.header; + } + return { + oldStart, + oldCount: oldEnd - oldStart, + newStart, + newCount: newEnd - newStart, + header, + content: a.content + '\n...\n' + b.content, + lines: [...a.lines, ...b.lines], + }; +} +/** + * Calculate the gap in lines between two hunks. + * Returns the number of lines between the end of hunk A and the start of hunk B. + */ +function calculateGap(a, b) { + const aEnd = a.newStart + a.newCount; + return b.newStart - aEnd; +} +/** + * Coalesce hunks that are close together into larger chunks. + * + * This reduces the number of LLM API calls by merging nearby hunks, + * while respecting size limits to keep chunks manageable. + * + * @param hunks - Array of hunks to coalesce + * @param options - Coalescing options (maxGapLines, maxChunkSize) + * @returns Array of coalesced hunks (may be smaller than input) + * + * Algorithm: + * 1. Sort hunks by start line + * 2. For each hunk, check if it can be merged with the previous: + * - Gap between hunks <= maxGapLines + * - Combined size <= maxChunkSize + * 3. If both conditions are met, merge; otherwise start a new chunk + */ +function coalesceHunks(hunks, options = {}) { + const { maxGapLines = DEFAULT_MAX_GAP_LINES, maxChunkSize = DEFAULT_MAX_CHUNK_SIZE } = options; + // Nothing to coalesce with 0 or 1 hunks + if (hunks.length <= 1) { + return hunks; + } + // Sort hunks by start line to ensure we process them in order + const sorted = [...hunks].sort((a, b) => a.newStart - b.newStart); + const result = []; + // sorted[0] is guaranteed to exist since we checked hunks.length > 1 above + let current = sorted[0]; + for (let i = 1; i < sorted.length; i++) { + const next = sorted[i]; + const gap = calculateGap(current, next); + const combinedSize = current.content.length + next.content.length; + // Merge if: close enough AND combined size under limit + if (gap <= maxGapLines && combinedSize <= maxChunkSize) { + current = mergeHunks(current, next); + } + else { + // Can't merge - save current and start a new chunk + result.push(current); + current = next; + } + } + // Don't forget the last chunk + result.push(current); + return result; +} +/** + * Check if coalescing would reduce the number of hunks. + * Useful for deciding whether to show coalescing stats. + */ +function wouldCoalesceReduce(hunks, options = {}) { + if (hunks.length <= 1) + return false; + const coalesced = coalesceHunks(hunks, options); + return coalesced.length < hunks.length; +} +/** + * Patterns that indicate logical breakpoints for splitting. + * Prioritized in order: blank lines are best, then function/class definitions. + */ +const LOGICAL_BREAKPOINT_PATTERNS = [ + // Blank lines (highest priority - natural paragraph breaks) + /^[ ]?$/, + // Function/method definitions (various languages) + /^[ ]?(export\s+)?(async\s+)?function\s+\w+/, + /^[ ]?(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s+)?\(/, + /^[ ]?(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s+)?function/, + /^[ ]?(public|private|protected)?\s*(static\s+)?(async\s+)?\w+\s*\([^)]*\)\s*[:{]/, + /^[ ]?def\s+\w+/, + /^[ ]?fn\s+\w+/, + /^[ ]?func\s+\w+/, + // Class/struct/interface definitions + /^[ ]?(export\s+)?(abstract\s+)?class\s+\w+/, + /^[ ]?(export\s+)?interface\s+\w+/, + /^[ ]?(export\s+)?type\s+\w+\s*=/, + /^[ ]?struct\s+\w+/, + /^[ ]?impl\s+/, + // Block comments (often precede logical sections) + /^[ ]?\/\*\*/, + /^[ ]?\/\//, + /^[ ]?#\s/, +]; +/** + * Check if a line is a good logical breakpoint for splitting. + * Returns a priority score (lower is better) or -1 if not a breakpoint. + */ +function getBreakpointPriority(line) { + // Match source syntax, not the unified-diff marker. File scans use '+' on + // every line, including the blank lines that should separate chunks. + const source = /^[ +-]/.test(line) ? line.slice(1) : line; + const index = LOGICAL_BREAKPOINT_PATTERNS.findIndex((pattern) => pattern.test(source)); + return index; +} +/** + * Find the best split point in a range of lines. + * Prefers logical breakpoints; falls back to midpoint if none found. + * + * @param lines - Array of lines to search + * @param startIdx - Start index in the lines array + * @param endIdx - End index (exclusive) in the lines array + * @param targetIdx - Ideal split point (used for fallback) + * @returns Index of the best split point + */ +function findBestSplitPoint(lines, startIdx, endIdx, targetIdx) { + // Search window: look within 20% of chunk size from target + const windowSize = Math.max(10, Math.floor((targetIdx - startIdx) * 0.2)); + const searchStart = Math.max(startIdx + 1, targetIdx - windowSize); + const searchEnd = Math.min(endIdx - 1, targetIdx + windowSize); + let bestIdx = targetIdx; + let bestPriority = Infinity; + for (let i = searchStart; i <= searchEnd; i++) { + const line = lines[i]; + if (line === undefined) + continue; + const priority = getBreakpointPriority(line); + if (priority >= 0 && (priority < bestPriority + || (priority === bestPriority && Math.abs(i - targetIdx) < Math.abs(bestIdx - targetIdx)))) { + bestPriority = priority; + bestIdx = i; + } + } + return bestIdx; +} +/** + * Create a sub-hunk from a portion of lines. + * + * @param originalHunk - The original hunk being split + * @param lines - The lines for this sub-hunk + * @param lineOffset - How many lines into the original hunk this sub-hunk starts + */ +function createSubHunk(originalHunk, lines, lineOffset) { + // Calculate how many "new" lines we've passed to get the new start position + // We need to count actual new-file lines, not just array indices + let newLinesBeforeOffset = 0; + let oldLinesBeforeOffset = 0; + for (let i = 0; i < lineOffset && i < originalHunk.lines.length; i++) { + const line = originalHunk.lines[i]; + if (line === undefined) + continue; + if (!line.startsWith('-')) { + newLinesBeforeOffset++; + } + if (!line.startsWith('+')) { + oldLinesBeforeOffset++; + } + } + // Count lines in this sub-hunk (lines without '-' are in new file, without '+' are in old file) + const newCount = lines.filter((line) => !line.startsWith('-')).length; + const oldCount = lines.filter((line) => !line.startsWith('+')).length; + // Build the @@ header for this sub-hunk + const newStart = originalHunk.newStart + newLinesBeforeOffset; + const oldStart = originalHunk.oldStart + oldLinesBeforeOffset; + const header = originalHunk.header; + const headerSuffix = header ? ` ${header}` : ''; + const hunkHeader = `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@${headerSuffix}`; + return { + oldStart, + oldCount, + newStart, + newCount, + header, + content: [hunkHeader, ...lines].join('\n'), + lines, + }; +} +/** + * Split a single large hunk into smaller chunks. + * + * @param hunk - The hunk to split + * @param maxChunkSize - Maximum size in characters per chunk + * @returns Array of smaller hunks (may be single element if no split needed) + */ +function splitHunk(hunk, maxChunkSize) { + // If hunk is small enough, return as-is + if (hunk.content.length <= maxChunkSize) { + return [hunk]; + } + const result = []; + const lines = hunk.lines; + let currentStart = 0; + while (currentStart < lines.length) { + // Estimate how many lines fit in maxChunkSize + // Use average line length as a rough guide + const avgLineLength = hunk.content.length / Math.max(1, lines.length); + const estimatedLines = Math.floor(maxChunkSize / avgLineLength); + const targetEnd = Math.min(currentStart + estimatedLines, lines.length); + // Calculate remaining content size + const remainingLines = lines.slice(currentStart); + const remainingSize = remainingLines.join('\n').length; + // If remaining content fits in maxChunkSize, take it all + if (remainingSize <= maxChunkSize) { + result.push(createSubHunk(hunk, remainingLines, currentStart)); + break; + } + // Find best split point, ensuring we advance by at least one line + let splitIdx = findBestSplitPoint(lines, currentStart, lines.length, targetEnd); + if (splitIdx <= currentStart) { + splitIdx = currentStart + 1; + } + // Keep a small blank-only tail here instead of starting another agent for + // trailing whitespace. Large whitespace changes must still be split. + const tail = lines.slice(splitIdx); + if (tail.join('\n').length <= maxChunkSize * 0.1 + && tail.every((line) => /^[ +-]?\s*$/.test(line))) { + splitIdx = lines.length; + } + // Extract lines for this chunk + const chunkLines = lines.slice(currentStart, splitIdx); + result.push(createSubHunk(hunk, chunkLines, currentStart)); + currentStart = splitIdx; + } + return result; +} +/** + * Split large hunks into smaller chunks for LLM analysis. + * + * Large files (1000+ lines) that become single hunks in file-based analysis + * can generate prompts exceeding practical limits. This function splits + * such hunks at logical breakpoints (blank lines, function definitions) + * to keep chunk sizes manageable. + * + * @param hunks - Array of hunks to potentially split + * @param options - Split options (maxChunkSize) + * @returns Array of hunks (may be larger than input if splits occurred) + * + * @example + * // Pipeline usage: + * const diff = parseFileDiff(filename, patch, status); + * const splitHunks = splitLargeHunks(diff.hunks, { maxChunkSize: 8000 }); + * const coalescedHunks = coalesceHunks(splitHunks, { maxGapLines: 30 }); + */ +function splitLargeHunks(hunks, options = {}) { + const { maxChunkSize = DEFAULT_MAX_CHUNK_SIZE } = options; + return hunks.flatMap((hunk) => splitHunk(hunk, maxChunkSize)); +} + +;// CONCATENATED MODULE: ./src/diff/index.ts + + + + + + + +/***/ }), + +/***/ 58147: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ e: () => (/* binding */ buildEventContext) +/* harmony export */ }); +/* unused harmony export EventContextError */ +/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51737); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78481); + + +// GitHub Action event payload schemas +const GitHubUserSchema = zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + login: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), +}); +const GitHubLabelSchema = zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + name: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), +}); +const GitHubRepoSchema = zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + name: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + full_name: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + default_branch: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + owner: GitHubUserSchema, +}); +const GitHubPullRequestSchema = zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + number: zod__WEBPACK_IMPORTED_MODULE_1__/* .number */ .aig(), + title: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + body: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP().nullable(), + draft: zod__WEBPACK_IMPORTED_MODULE_1__/* .boolean */ .zMY().optional(), + labels: zod__WEBPACK_IMPORTED_MODULE_1__/* .array */ .YOg(GitHubLabelSchema).optional(), + user: GitHubUserSchema, + base: zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + ref: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + sha: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + }), + head: zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + ref: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + sha: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + }), +}); +const GitHubEventPayloadSchema = zod__WEBPACK_IMPORTED_MODULE_1__/* .object */ .Ikc({ + action: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP(), + /** Head SHA before the push, sent on `synchronize` events. */ + before: zod__WEBPACK_IMPORTED_MODULE_1__/* .string */ .YjP().optional(), + label: GitHubLabelSchema.optional(), + repository: GitHubRepoSchema, + pull_request: GitHubPullRequestSchema.optional(), +}); +class EventContextError extends Error { + constructor(message, options) { + super(message, options); + this.name = 'EventContextError'; + } +} +async function buildEventContext(eventName, eventPayload, repoPath, octokit) { + const payloadResult = GitHubEventPayloadSchema.safeParse(eventPayload); + if (!payloadResult.success) { + throw new EventContextError('Invalid event payload', { cause: payloadResult.error }); + } + const payload = payloadResult.data; + const repository = { + owner: payload.repository.owner.login, + name: payload.repository.name, + fullName: payload.repository.full_name, + defaultBranch: payload.repository.default_branch, + }; + let pullRequest; + if (eventName === 'pull_request' && payload.pull_request) { + const pr = payload.pull_request; + // Fetch files changed in the PR + const files = await fetchPullRequestFiles(octokit, repository.owner, repository.name, pr.number); + const push = payload.action === 'synchronize' && payload.before + ? await fetchPushChanges(octokit, repository.owner, repository.name, payload.before, pr.head.sha) + : undefined; + pullRequest = { + number: pr.number, + title: pr.title, + body: pr.body, + author: pr.user.login, + draft: pr.draft ?? false, + labels: pr.labels?.map((label) => label.name) ?? [], + baseBranch: pr.base.ref, + headBranch: pr.head.ref, + headSha: pr.head.sha, + baseSha: pr.base.sha, + files, + ...(push ? { push } : {}), + }; + } + const context = { + eventType: eventName, + action: payload.action, + label: payload.label?.name, + repository, + pullRequest, + diffContextSource: { type: 'working-tree' }, + repoPath, + }; + // Validate the final context + const result = _types_index_js__WEBPACK_IMPORTED_MODULE_0__/* .EventContextSchema */ .hA.safeParse(context); + if (!result.success) { + throw new EventContextError('Failed to build valid event context', { cause: result.error }); + } + return result.data; +} +/** GitHub's compare API returns at most this many files and omits the rest. */ +const COMPARE_FILE_LIMIT = 300; +/** + * Fetch the files changed by one push. Returns undefined when the push did + * not fast-forward `before` (a force-push or rebase, which GitHub reports as + * `diverged` or fails to compare), or the file list is truncated or missing, + * so callers fall back to the full PR diff. + */ +async function fetchPushChanges(octokit, owner, repo, beforeSha, headSha) { + try { + const { data } = await octokit.repos.compareCommitsWithBasehead({ + owner, + repo, + basehead: `${beforeSha}...${headSha}`, + }); + // A rewritten branch compares from the merge base, so its file list is not the push. + if (data.status !== 'ahead') { + return undefined; + } + const files = data.files; + // GitHub drops `files` entirely on some oversized compares; treat that like truncation. + if (!files || files.length >= COMPARE_FILE_LIMIT) { + return undefined; + } + return { + beforeSha, + files: files.map((file) => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch, + })), + }; + } + catch { + return undefined; + } +} +async function fetchPullRequestFiles(octokit, owner, repo, pullNumber) { + const files = await octokit.paginate(octokit.pulls.listFiles, { + owner, + repo, + pull_number: pullNumber, + per_page: 100, + }); + return files.map((file) => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch, + })); +} + + +/***/ }), + +/***/ 65997: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ J: () => (/* binding */ buildScheduleEventContext) +/* harmony export */ }); +/* unused harmony export filterFilesByPatterns */ +/* harmony import */ var _cli_files_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20453); +/* harmony import */ var _triggers_matcher_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49431); + + +/** + * Build an EventContext for scheduled runs. + * + * Creates a synthetic pullRequest context from file globs using real repo info. + * The runner processes this normally because the files have patch data. + */ +async function buildScheduleEventContext(options) { + const { patterns, ignorePatterns, ignore, scan, repoPath, owner, name, defaultBranch, headSha, } = options; + // Expand glob patterns and create FileChange objects with full content as patch + let fileChanges = await (0,_cli_files_js__WEBPACK_IMPORTED_MODULE_0__/* .expandAndCreateFileChanges */ .Rq)(patterns, repoPath, { ignore, scan }); + // Filter out ignored patterns + if (ignorePatterns && ignorePatterns.length > 0) { + fileChanges = fileChanges.filter((file) => { + const isIgnored = ignorePatterns.some((pattern) => (0,_triggers_matcher_js__WEBPACK_IMPORTED_MODULE_1__/* .matchGlob */ .sB)(pattern, file.filename)); + return !isIgnored; + }); + } + return { + eventType: 'schedule', + action: 'scheduled', + repository: { + owner, + name, + fullName: `${owner}/${name}`, + defaultBranch, + }, + // Synthetic pullRequest context for runner compatibility + pullRequest: { + number: 0, // No actual PR + title: 'Scheduled Analysis', + body: null, + author: 'warden', + baseBranch: defaultBranch, + headBranch: defaultBranch, + headSha, + baseSha: headSha, // No actual base for scheduled runs + files: fileChanges, + }, + diffContextSource: { type: 'working-tree' }, + repoPath, + }; +} +/** + * Filter file changes to only include files matching the given patterns. + * Used when a schedule trigger has specific path filters. + */ +function filterFilesByPatterns(files, patterns, ignorePatterns) { + let filtered = files.filter((file) => patterns.some((pattern) => matchGlob(pattern, file.filename))); + if (ignorePatterns && ignorePatterns.length > 0) { + filtered = filtered.filter((file) => { + const isIgnored = ignorePatterns.some((pattern) => matchGlob(pattern, file.filename)); + return !isIgnored; + }); + } + return filtered; +} + + +/***/ }), + +/***/ 3941: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ EF: () => (/* binding */ generateMarker), +/* harmony export */ G$: () => (/* binding */ processDuplicateActions), +/* harmony export */ LQ: () => (/* binding */ generateContentHash), +/* harmony export */ Op: () => (/* binding */ generateFindingMetadata), +/* harmony export */ Xi: () => (/* binding */ findingToExistingComment), +/* harmony export */ aw: () => (/* binding */ consolidateBatchFindings), +/* harmony export */ dh: () => (/* binding */ parseWardenSkills), +/* harmony export */ kX: () => (/* binding */ fetchExistingComments), +/* harmony export */ rW: () => (/* binding */ parseWardenFindingId), +/* harmony export */ v9: () => (/* binding */ deduplicateFindings) +/* harmony export */ }); +/* unused harmony exports generateLocationHashKey, parseMarker, parseWardenFindingMetadata, parseWardenComment, isWardenComment, updateWardenCommentBody, fetchExistingWardenComments, updateWardenComment, addReactionToComment */ +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77598); +/* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_crypto__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(51737); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(78481); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82272); +/* harmony import */ var _sdk_runtimes_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(23473); +/* harmony import */ var _sdk_extract_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(29709); +/* harmony import */ var _sdk_prompt_sections_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(49893); + + + + + + + +/** + * Generate a short content hash from title and description. + * Used for exact-match deduplication. + */ +function generateContentHash(title, description) { + const content = `${title}\n${description}`; + return (0,node_crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(content).digest('hex').slice(0, 8); +} +/** + * Location+content key that disambiguates findings sharing the same content + * hash (e.g. identical generic wording from two different skills at two + * different locations). Mirrors the key this file already builds inline for + * existing-comment matching — reuse this instead of hashing content alone. + */ +function generateLocationHashKey(path, line, hash) { + return `${path ?? ''}:${line}:${hash}`; +} +/** + * Generate the marker HTML comment to embed in comment body. + * Format: + */ +function generateMarker(path, line, contentHash) { + return ``; +} +/** Generate the hidden metadata marker embedded in Warden comments. */ +function generateFindingMetadata(finding) { + const metadata = { + id: finding.id, + severity: finding.severity, + confidence: finding.confidence, + }; + return ``; +} +/** + * Parse a Warden marker from a comment body. + * Returns null if no valid marker is found. + */ +function parseMarker(body) { + const match = body.match(//); + if (!match || match.length < 4) { + return null; + } + const path = match[1]; + const lineStr = match[2]; + const contentHash = match[3]; + // Validate that all capture groups exist (defensive, should always be true when regex matches) + if (!path || !lineStr || !contentHash) { + return null; + } + return { + path, + line: parseInt(lineStr, 10), + contentHash, + }; +} +/** Parse and validate a Warden finding metadata marker. */ +function parseWardenFindingMetadata(body) { + const match = body.match(//); + const encoded = match?.[1]; + if (!encoded) + return null; + try { + const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); + const id = parsed.id; + if (id !== undefined && typeof id !== 'string') + return null; + const severity = parsed.severity; + if (severity !== 'high' && severity !== 'medium' && severity !== 'low') + return null; + const confidence = parsed.confidence; + if (confidence !== undefined && + confidence !== 'high' && + confidence !== 'medium' && + confidence !== 'low') { + return null; + } + return { id, severity, confidence }; + } + catch { + return null; + } +} +/** + * Parse title and description from a Warden comment body. + * Expected format: **:emoji: Title**\n\nDescription or **Title**\n\nDescription + * Strips legacy [ID] prefix from titles for backward compat. + */ +function parseWardenComment(body) { + // Match the title pattern: **:emoji: Title** or **Title** + // Use non-greedy match to handle titles containing asterisks + const titleMatch = body.match(/\*\*(?::[a-z_]+:\s*)?(.+?)\*\*/); + if (!titleMatch || !titleMatch[1]) { + return null; + } + // Strip legacy [ID] prefix (e.g., "[2K5-29B] Title" → "Title") + const title = titleMatch[1].replace(/^\[[A-Z0-9-]+\]\s*/, '').trim(); + // Get the description - everything after the title until the first --- + const titleEnd = body.indexOf('**', body.indexOf('**') + 2) + 2; + const separatorIndex = body.indexOf('---'); + const descEnd = separatorIndex > -1 ? separatorIndex : body.length; + const description = body.slice(titleEnd, descEnd).trim(); + return { title, description }; +} +function sanitizeReviewCommentText(body) { + return body + .replaceAll(//gi, ' ') + .replaceAll(//g, ' ') + .replaceAll(/<[^>]+>/g, ' ') + .replaceAll(/!\[[^\]]*\]\([^)]*\)/g, ' ') + .replaceAll(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replaceAll(/[*_`>#~-]+/g, ' ') + .replaceAll(/\s+/g, ' ') + .trim(); +} +function truncateText(value, maxLength) { + if (value.length <= maxLength) { + return value; + } + return value.slice(0, maxLength - 3).trimEnd() + '...'; +} +function fallbackCommentDescription(body) { + return truncateText(sanitizeReviewCommentText(body), 500); +} +function fallbackCommentTitle(body, commentId) { + const description = sanitizeReviewCommentText(body); + if (!description) { + return `Review comment ${commentId}`; + } + return truncateText(description, 80); +} +const FINDING_ID_PATTERN = '[^<\\r\\n]+'; +const SKILL_LIST_PATTERN = '[^<\\r\\n]+?'; +const CURRENT_FOOTER_PATTERN = new RegExp(`Identified by Warden · (${SKILL_LIST_PATTERN})(?: · (${FINDING_ID_PATTERN}))?`); +const PRIOR_FOOTER_PATTERN = new RegExp(`Identified by Warden (${SKILL_LIST_PATTERN})(?: · (${FINDING_ID_PATTERN}))?`); +function decodeFooterValue(value) { + return value.replaceAll('<', '<').replaceAll('>', '>').replaceAll('&', '&'); +} +function parseSkillList(value) { + return value.split(',').map((skill) => decodeFooterValue(skill.trim())); +} +function parseWardenFooter(body) { + const currentMatch = body.match(CURRENT_FOOTER_PATTERN); + // TODO(2026-08-01): Remove PRIOR_FOOTER_PATTERN after comments using it have aged out. + const match = currentMatch ?? body.match(PRIOR_FOOTER_PATTERN); + const fullMatch = match?.[0]; + const skillList = match?.[1]; + if (!fullMatch || !skillList) + return null; + // Do not reinterpret historical bracket, backtick, or `via` footers as the prior plain format. + if (!currentMatch && (/^via\s+`/.test(skillList) || /^\[[^\]]+\](?:,\s*\[[^\]]+\])*$/.test(skillList))) { + return null; + } + return { + fullMatch, + skills: parseSkillList(skillList), + findingId: match[2] ? decodeFooterValue(match[2]) : undefined, + }; +} +/** Parse the finding ID from hidden metadata or a supported transitional footer. */ +function parseWardenFindingId(body) { + return parseWardenFindingMetadata(body)?.id ?? parseWardenFooter(body)?.findingId; +} +/** Check if a comment body is a supported Warden comment. */ +function isWardenComment(body) { + return body.includes('|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + setCloseTimer(this); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait + * for the closing handshake to finish after `websocket.close()` is called + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=131072] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + closeTimeout: CLOSE_TIMEOUT, + protocolVersion: protocolVersions[1], + maxBufferedChunks: 1024 * 1024, + maxFragments: 128 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + websocket._closeTimeout = opts.closeTimeout; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = + opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate({ + ...opts.perMessageDeflate, + isServer: false, + maxPayload: opts.maxPayload + }); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const upgrade = res.headers.upgrade; + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxBufferedChunks: opts.maxBufferedChunks, + maxFragments: opts.maxFragments, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + // + // The following assignment is practically useless and is done only for + // consistency. + // + websocket._errorEmitted = true; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The `Sender` error event handler. + * + * @param {Error} The error + * @private + */ +function senderOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket.readyState === WebSocket.CLOSED) return; + if (websocket.readyState === WebSocket.OPEN) { + websocket._readyState = WebSocket.CLOSING; + setCloseTimer(websocket); + } + + // + // `socket.end()` is used instead of `socket.destroy()` to allow the other + // peer to finish sending queued data. There is no need to set a timer here + // because `CLOSING` means that it is already set or not needed. + // + this._socket.end(); + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * Set a timer to destroy the underlying raw socket of a WebSocket. + * + * @param {WebSocket} websocket The WebSocket instance + * @private + */ +function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + websocket._closeTimeout + ); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written. If instead, the + // socket is paused, any possible buffered data will be read as a single + // chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + this._readableState.length !== 0 + ) { + const chunk = this.read(this._readableState.length); + + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} + + +/***/ }), + +/***/ 48812: +/***/ ((module) => { + +module.exports = eval("require")("bufferutil"); + + +/***/ }), + +/***/ 87823: +/***/ ((module) => { + +module.exports = eval("require")("react-devtools-core"); + + +/***/ }), + +/***/ 60710: +/***/ ((module) => { + +module.exports = eval("require")("utf-8-validate"); + + +/***/ }), + +/***/ 67928: +/***/ ((__unused_webpack___webpack_module__, __unused_webpack___webpack_exports__, __webpack_require__) => { + +/* harmony import */ var ws__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9117); +// Ignoring missing types error to avoid adding another dependency for this hack to work + +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment +const customGlobal = globalThis; +// These things must exist before importing `react-devtools-core` +// Using ||= intentionally to set falsy values, not just null/undefined +// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing +customGlobal.WebSocket ||= ws__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay; +// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing +customGlobal.window ||= globalThis; +// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing +customGlobal.self ||= globalThis; +// Filter out Ink's internal components from devtools for a cleaner view. +// Also, ince `react-devtools-shared` package isn't published on npm, we can't +// use its types, that's why there are hard-coded values in `type` fields below. +// See https://github.com/facebook/react/blob/edf6eac8a181860fd8a2d076a43806f1237495a1/packages/react-devtools-shared/src/types.js#L24 +customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [ + { + // ComponentFilterElementType + type: 1, + // ElementTypeHostComponent + value: 7, + isEnabled: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalApp', + isEnabled: true, + isValid: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalAppContext', + isEnabled: true, + isValid: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalStdoutContext', + isEnabled: true, + isValid: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalStderrContext', + isEnabled: true, + isValid: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalStdinContext', + isEnabled: true, + isValid: true, + }, + { + // ComponentFilterDisplayName + type: 2, + value: 'InternalFocusContext', + isEnabled: true, + isValid: true, + }, +]; +//# sourceMappingURL=devtools-window-polyfill.js.map + +/***/ }), + +/***/ 63053: +/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _devtools_window_polyfill_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67928); +/* harmony import */ var ws__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9117); +/* harmony import */ var react_devtools_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87823); +/* eslint-disable import-x/order */ +// eslint-disable-next-line import-x/no-unassigned-import + + +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-expect-error + +const isDevToolsReachable = async () => new Promise(resolve => { + const socket = new ws__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Ay('ws://localhost:8097'); + const timeout = setTimeout(() => { + socket.terminate(); + resolve(false); + }, 2000); + // Don't let the timeout keep the process alive on its own + timeout.unref(); + socket.on('open', () => { + clearTimeout(timeout); + socket.terminate(); + resolve(true); + }); + socket.on('error', () => { + clearTimeout(timeout); + socket.terminate(); + resolve(false); + }); +}); +if (await isDevToolsReachable()) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + react_devtools_core__WEBPACK_IMPORTED_MODULE_2__.initialize(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + react_devtools_core__WEBPACK_IMPORTED_MODULE_2__.connectToDevTools(); +} +else { + console.warn('DEV is set to true, but the React DevTools server is not running. Start it with:\n\n$ npx react-devtools\n'); +} +//# sourceMappingURL=devtools.js.map +__webpack_async_result__(); +} catch(e) { __webpack_async_result__(e); } }, 1); + +/***/ }), + +/***/ 9117: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ay: () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _lib_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83614); +/* harmony import */ var _lib_extension_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48165); +/* harmony import */ var _lib_permessage_deflate_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(94086); +/* harmony import */ var _lib_receiver_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(58479); +/* harmony import */ var _lib_sender_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7243); +/* harmony import */ var _lib_subprotocol_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(66094); +/* harmony import */ var _lib_websocket_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(73983); +/* harmony import */ var _lib_websocket_server_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(15243); + + + + + + + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_lib_websocket_js__WEBPACK_IMPORTED_MODULE_6__); + + +/***/ }) + +}; diff --git a/dist/action/548.index.js b/dist/action/548.index.js new file mode 100644 index 000000000..218a6110f --- /dev/null +++ b/dist/action/548.index.js @@ -0,0 +1,1763 @@ +export const id = 548; +export const ids = [548]; +export const modules = { + +/***/ 71548: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + closeOpenAICodexWebSocketSessions: () => (/* binding */ closeOpenAICodexWebSocketSessions), + getOpenAICodexWebSocketDebugStats: () => (/* binding */ getOpenAICodexWebSocketDebugStats), + resetOpenAICodexWebSocketDebugStats: () => (/* binding */ resetOpenAICodexWebSocketDebugStats), + stream: () => (/* binding */ stream), + streamSimple: () => (/* binding */ streamSimple) +}); + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/models.js +var models = __webpack_require__(25941); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/session-resources.js +var session_resources = __webpack_require__(79475); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.js +function combineAbortSignals(signals) { + const activeSignals = signals.filter((signal) => signal !== undefined); + if (activeSignals.length === 0) { + return { cleanup: () => { } }; + } + if (activeSignals.length === 1) { + return { signal: activeSignals[0], cleanup: () => { } }; + } + const controller = new AbortController(); + const listeners = []; + const abort = (signal) => { + if (!controller.signal.aborted) { + controller.abort(signal.reason); + } + }; + for (const signal of activeSignals) { + if (signal.aborted) { + abort(signal); + break; + } + const listener = () => abort(signal); + signal.addEventListener("abort", listener, { once: true }); + listeners.push({ signal, listener }); + } + return { + signal: controller.signal, + cleanup: () => { + for (const { signal, listener } of listeners) { + signal.removeEventListener("abort", listener); + } + }, + }; +} +//# sourceMappingURL=abort-signals.js.map +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js +var diagnostics = __webpack_require__(64921); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +var error_body = __webpack_require__(20372); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js +var event_stream = __webpack_require__(45174); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/headers.js +var utils_headers = __webpack_require__(82003); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/node-http-proxy.js +var node_http_proxy = __webpack_require__(78191); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +var pi_user_agent = __webpack_require__(55278); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/text.js +var utils_text = __webpack_require__(65678); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js +var transcript = __webpack_require__(19883); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/uuid.js +var uuid = __webpack_require__(33610); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js +var constrained_sampling = __webpack_require__(37776); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js +var openai_prompt_cache = __webpack_require__(95304); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +var openai_responses_shared = __webpack_require__(33115); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js + 1 modules +var simple_options = __webpack_require__(18296); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js + + + + + + + + + + + + + + + + +// ============================================================================ +// Configuration +// ============================================================================ +const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api"; +const JWT_CLAIM_PATH = "https://api.openai.com/auth"; +const DEFAULT_MAX_RETRIES = 0; +const BASE_DELAY_MS = 1000; +const DEFAULT_MAX_RETRY_DELAY_MS = 60_000; +const DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15_000; +// The Codex backend accepts zstd-compressed request bodies on the SSE responses +// endpoint (the same endpoint the official Codex client compresses against). +const REQUEST_COMPRESSION_ZSTD_LEVEL = 3; +const CODEX_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode"]); +const WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE = 1009; +const WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE = "websocket_connection_limit_reached"; +const PREVIOUS_RESPONSE_NOT_FOUND_CODE = "previous_response_not_found"; +const CODEX_RESPONSE_STATUSES = new Set([ + "completed", + "incomplete", + "failed", + "cancelled", + "queued", + "in_progress", +]); +function assertSuccessfulOutput(output) { + if (output.stopReason === "pending") { + throw new Error("Codex stream ended without a stop reason"); + } + if (output.stopReason === "error" || output.stopReason === "aborted") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } +} +// ============================================================================ +// Retry Helpers +// ============================================================================ +function isTerminalRateLimitError(errorText) { + return /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText); +} +function isRetryableError(status, errorText) { + if (status === 429 && isTerminalRateLimitError(errorText)) { + return false; + } + if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) { + return true; + } + return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText); +} +function getRetryAfterDelayMs(headers) { + const retryAfterMs = headers.get("retry-after-ms"); + if (retryAfterMs !== null) { + const millis = Number(retryAfterMs); + if (Number.isFinite(millis)) { + return Math.max(0, millis); + } + } + const retryAfter = headers.get("retry-after"); + if (!retryAfter) { + return undefined; + } + const seconds = Number(retryAfter); + if (Number.isFinite(seconds)) { + return Math.max(0, seconds * 1000); + } + const date = Date.parse(retryAfter); + if (!Number.isNaN(date)) { + return Math.max(0, date - Date.now()); + } + return undefined; +} +class RetryDelayExceededError extends Error { +} +function validateRetryDelayMs(delayMs, options) { + const maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS; + if (maxRetryDelayMs > 0 && delayMs > maxRetryDelayMs) { + throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs / 1000)}s retry delay (max: ${Math.ceil(maxRetryDelayMs / 1000)}s)`); + } + return delayMs; +} +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Request was aborted")); + return; + } + const timeout = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { + clearTimeout(timeout); + reject(new Error("Request was aborted")); + }); + }); +} +function normalizeTimeoutMs(value) { + if (value === undefined) + return undefined; + if (!Number.isFinite(value) || value < 0) { + throw new Error(`Invalid timeoutMs: ${String(value)}`); + } + return Math.floor(value); +} +function loadNodeZlib() { + if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) { + return null; + } + return process.getBuiltinModule?.("node:zlib") ?? null; +} +// Returns the zstd-compressed body bytes, or null when compression is +// unavailable (browser/Vite builds). Callers fall back to sending the +// uncompressed JSON when this returns null. +function compressRequestBodyZstd(bodyJson) { + const zlib = loadNodeZlib(); + if (!zlib || typeof zlib.zstdCompressSync !== "function") { + return null; + } + try { + const compressed = zlib.zstdCompressSync(bodyJson, { + params: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL }, + }); + return new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength); + } + catch { + return null; + } +} +// ============================================================================ +// Main Stream Function +// ============================================================================ +const stream = (model, context, options) => { + const stream = new event_stream/* AssistantMessageEventStream */.Q2(); + const normalizedContext = (0,transcript/* resolveTranscript */.lw)(context, model.compat?.supportsMidConvoSystemMessages); + (async () => { + const output = { + role: "assistant", + content: [], + api: "openai-codex-responses", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + try { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const accountId = extractAccountId(apiKey); + const grammarToolInputProperties = (0,constrained_sampling/* createGrammarToolInputProperties */.PJ)((0,transcript/* getDeclaredTools */.Wg)(normalizedContext.messages), model.compat?.supportsOpenAIGrammarTools ?? false); + const cacheSessionId = options?.cacheRetention === "none" ? undefined : options?.sessionId; + const codexSessionId = (0,openai_prompt_cache/* clampOpenAIPromptCacheKey */.l)(cacheSessionId); + let body = buildRequestBody(model, normalizedContext, options, codexSessionId, grammarToolInputProperties); + const nextBody = await options?.onPayload?.(body, model); + if (nextBody !== undefined) { + body = nextBody; + } + const websocketRequestId = codexSessionId || (0,uuid/* uuidv7 */.n)(); + const sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, codexSessionId); + const websocketHeaders = buildWebSocketHeaders(model.headers, options?.headers, accountId, apiKey, websocketRequestId); + const bodyJson = JSON.stringify(body); + const httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs); + const websocketConnectTimeoutMs = normalizeTimeoutMs(options?.websocketConnectTimeoutMs); + const transport = options?.transport || "auto"; + let startEmitted = false; + const websocketDisabledForSession = transport !== "sse" && isWebSocketSseFallbackActive(cacheSessionId); + if (websocketDisabledForSession) { + recordWebSocketSseFallback(cacheSessionId); + } + if (transport !== "sse" && !websocketDisabledForSession) { + let websocketStarted = false; + let retriedWebSocketConnectionLimit = false; + let retriedMissingWebSocketContinuation = false; + while (true) { + websocketStarted = false; + try { + await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl), body, websocketHeaders, output, stream, model, () => { + websocketStarted = true; + if (!startEmitted) { + startEmitted = true; + stream.push({ type: "start", partial: output }); + } + }, httpTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + assertSuccessfulOutput(output); + stream.push({ + type: "done", + reason: output.stopReason, + message: output, + }); + stream.end(); + return; + } + catch (error) { + const aborted = options?.signal?.aborted; + const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error); + const previousResponseNotFound = isPreviousResponseNotFoundError(error); + if (!aborted && previousResponseNotFound && !retriedMissingWebSocketContinuation) { + retriedMissingWebSocketContinuation = true; + continue; + } + if (!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit) { + retriedWebSocketConnectionLimit = true; + continue; + } + if (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) { + throw error; + } + (0,diagnostics/* appendAssistantMessageDiagnostic */.vF)(output, (0,diagnostics/* createAssistantMessageDiagnostic */.hY)("provider_transport_failure", error, { + configuredTransport: transport, + ...(websocketStarted ? {} : { fallbackTransport: "sse" }), + eventsEmitted: websocketStarted, + phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start", + requestBytes: new TextEncoder().encode(bodyJson).byteLength, + })); + recordWebSocketFailure(cacheSessionId, error); + if (websocketStarted) { + throw error; + } + recordWebSocketSseFallback(cacheSessionId); + break; + } + } + } + // Compress the request body once for the SSE path. The Codex backend + // decodes Content-Encoding: zstd; the WebSocket transport above sends the + // uncompressed JSON frame, matching the official Codex client. + const compressedBody = compressRequestBodyZstd(bodyJson); + if (compressedBody) { + sseHeaders.set("content-encoding", "zstd"); + } + const sseBody = compressedBody ?? bodyJson; + // Fetch with retry logic for rate limits and transient errors + let response; + let lastError; + const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES; + for (let attempt = 0; attempt <= maxRetries; attempt++) { + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + try { + const headerTimeoutSignal = httpTimeoutMs !== undefined && httpTimeoutMs > 0 ? AbortSignal.timeout(httpTimeoutMs) : undefined; + const combinedSignal = combineAbortSignals([options?.signal, headerTimeoutSignal]); + try { + response = await (options?.fetch ?? globalThis.fetch)(resolveCodexUrl(model.baseUrl), { + method: "POST", + headers: sseHeaders, + body: sseBody, + signal: combinedSignal.signal, + }); + } + catch (error) { + if (headerTimeoutSignal?.aborted && !options?.signal?.aborted) { + throw new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`); + } + throw error; + } + finally { + combinedSignal.cleanup(); + } + await options?.onResponse?.({ status: response.status, headers: (0,utils_headers/* headersToRecord */.j)(response.headers) }, model); + if (response.ok) { + break; + } + const errorText = await response.text(); + if (attempt < maxRetries && isRetryableError(response.status, errorText)) { + const retryAfterDelayMs = getRetryAfterDelayMs(response.headers); + const delayMs = retryAfterDelayMs === undefined + ? BASE_DELAY_MS * 2 ** attempt + : validateRetryDelayMs(retryAfterDelayMs, options); + await sleep(delayMs, options?.signal); + continue; + } + // Parse error for friendly message on final attempt or non-retryable error + const fakeResponse = new Response(errorText, { + status: response.status, + statusText: response.statusText, + }); + const info = await parseErrorResponse(fakeResponse); + throw new Error(info.friendlyMessage || info.message); + } + catch (error) { + if (error instanceof Error) { + if (error.name === "AbortError" || error.message === "Request was aborted") { + throw new Error("Request was aborted"); + } + } + lastError = error instanceof Error ? error : new Error(String(error)); + // Network errors are retryable + if (attempt < maxRetries && + !(lastError instanceof RetryDelayExceededError) && + !lastError.message.includes("usage limit")) { + const delayMs = BASE_DELAY_MS * 2 ** attempt; + await sleep(delayMs, options?.signal); + continue; + } + throw lastError; + } + } + if (!response?.ok) { + throw lastError ?? new Error("Failed after retries"); + } + if (!response.body) { + throw new Error("No response body"); + } + if (!startEmitted) { + startEmitted = true; + stream.push({ type: "start", partial: output }); + } + await processStream(response, output, stream, model, grammarToolInputProperties, options); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + assertSuccessfulOutput(output); + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + for (const block of output.content) { + // Streaming scratch buffers are only used during parsing; never persist them. + delete block.partialJson; + delete block.customInput; + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = (0,error_body/* formatProviderError */.lR)((0,error_body/* normalizeProviderError */.Jo)(error)); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +const streamSimple = (model, context, options) => { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = { + ...(0,simple_options/* buildBaseOptions */.QP)(model, context, options, apiKey), + toolChoice: options?.toolChoice, + }; + const clampedReasoning = options?.reasoning ? (0,models/* clampThinkingLevel */.Kt)(model, options.reasoning) : undefined; + const reasoningEffort = clampedReasoning === "off" ? undefined : clampedReasoning; + return stream(model, context, { + ...base, + reasoningEffort, + }); +}; +// ============================================================================ +// Request Building +// ============================================================================ +function buildRequestBody(model, context, options, cacheSessionId, grammarToolInputProperties = (0,constrained_sampling/* createGrammarToolInputProperties */.PJ)((0,transcript/* getDeclaredTools */.Wg)(context.messages), model.compat?.supportsOpenAIGrammarTools ?? false)) { + const supportsStrictMode = model.compat?.supportsStrictMode ?? true; + const supportsOpenAIGrammarTools = model.compat?.supportsOpenAIGrammarTools ?? false; + const supportsAdditionalTools = model.compat?.supportsAdditionalTools ?? false; + const supportsToolSearch = model.compat?.supportsToolSearch ?? false; + const transcriptTools = (0,transcript/* resolveTranscriptTools */.eW)(context.messages, supportsAdditionalTools || supportsToolSearch); + const messages = (0,openai_responses_shared/* convertResponsesMessages */.iq)(model, context, CODEX_TOOL_CALL_PROVIDERS, { + includeSystemPrompt: false, + grammarToolInputProperties, + supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false, + supportsAdditionalTools, + supportsToolSearch, + toolOptions: { strict: null, supportsStrictMode, supportsOpenAIGrammarTools }, + }); + const initialSystemMessage = (0,transcript/* getInitialSystemMessage */.xF)(context.messages); + const instructions = initialSystemMessage ? (0,utils_text/* getSystemMessageText */.Y8)(initialSystemMessage) : ""; + const body = { + model: model.id, + store: false, + stream: true, + instructions: instructions || "You are a helpful assistant.", + input: messages, + text: { verbosity: options?.textVerbosity || "low" }, + include: ["reasoning.encrypted_content"], + prompt_cache_key: cacheSessionId, + tool_choice: options?.toolChoice ?? "auto", + parallel_tool_calls: true, + }; + if (options?.temperature !== undefined) { + body.temperature = options.temperature; + } + if (options?.serviceTier !== undefined) { + body.service_tier = options.serviceTier; + } + if (transcriptTools.requestTools.length > 0) { + body.tools = (0,openai_responses_shared/* convertResponsesTools */.hX)(transcriptTools.requestTools, { + strict: null, + supportsStrictMode, + supportsOpenAIGrammarTools, + }); + } + if (options?.reasoningEffort !== undefined) { + const effort = options.reasoningEffort === "none" + ? model.thinkingLevelMap?.off === undefined + ? "none" + : model.thinkingLevelMap.off + : (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort); + if (effort !== null) { + body.reasoning = { + effort, + summary: options.reasoningSummary ?? "auto", + }; + } + } + else if (model.reasoning && model.thinkingLevelMap?.off !== null) { + body.reasoning = { effort: model.thinkingLevelMap?.off ?? "none" }; + } + return body; +} +function getServiceTierCostMultiplier(model, serviceTier) { + switch (serviceTier) { + case "flex": + return 0.5; + case "priority": + return model.id === "gpt-5.5" ? 2.5 : 2; + default: + return 1; + } +} +function applyServiceTierPricing(usage, serviceTier, model) { + const multiplier = getServiceTierCostMultiplier(model, serviceTier); + if (multiplier === 1) + return; + usage.cost.input *= multiplier; + usage.cost.output *= multiplier; + usage.cost.cacheRead *= multiplier; + usage.cost.cacheWrite *= multiplier; + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite; +} +function resolveCodexServiceTier(responseServiceTier, requestServiceTier) { + if (responseServiceTier === "default" && (requestServiceTier === "flex" || requestServiceTier === "priority")) { + return requestServiceTier; + } + return responseServiceTier ?? requestServiceTier; +} +function resolveCodexUrl(baseUrl) { + const raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL; + const normalized = raw.replace(/\/+$/, ""); + if (normalized.endsWith("/codex/responses")) + return normalized; + if (normalized.endsWith("/codex")) + return `${normalized}/responses`; + return `${normalized}/codex/responses`; +} +function resolveCodexWebSocketUrl(baseUrl) { + const url = new URL(resolveCodexUrl(baseUrl)); + if (url.protocol === "https:") + url.protocol = "wss:"; + if (url.protocol === "http:") + url.protocol = "ws:"; + return url.toString(); +} +// ============================================================================ +// Response Processing +// ============================================================================ +async function processStream(response, output, stream, model, grammarToolInputProperties, options) { + await (0,openai_responses_shared/* processResponsesStream */.KB)(mapCodexEvents(parseSSE(response, options?.signal), output), output, stream, model, { + serviceTier: options?.serviceTier, + grammarToolInputProperties, + resolveServiceTier: resolveCodexServiceTier, + applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model), + }); +} +class CodexApiError extends Error { + code; + payload; + constructor(message, options) { + super(message); + this.name = "CodexApiError"; + this.code = options?.code; + this.payload = options?.payload; + this.cause = options?.cause; + } +} +class CodexProtocolError extends Error { + payload; + constructor(message, options) { + super(message); + this.name = "CodexProtocolError"; + this.payload = options?.payload; + this.cause = options?.cause; + } +} +function isCodexNonTransportError(error) { + return error instanceof CodexApiError || error instanceof CodexProtocolError; +} +function isWebSocketConnectionLimitReachedError(error) { + return error instanceof CodexApiError && error.code === WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE; +} +function isPreviousResponseNotFoundError(error) { + return error instanceof CodexApiError && error.code === PREVIOUS_RESPONSE_NOT_FOUND_CODE; +} +function extractCodexEventError(event) { + const nested = event.error && typeof event.error === "object" ? event.error : undefined; + return { + code: typeof event.code === "string" ? event.code : typeof nested?.code === "string" ? nested.code : undefined, + message: typeof event.message === "string" + ? event.message + : typeof nested?.message === "string" + ? nested.message + : undefined, + }; +} +async function* mapCodexEvents(events, output) { + for await (const event of events) { + const type = typeof event.type === "string" ? event.type : undefined; + if (!type) + continue; + if (type === "error") { + const { code, message } = extractCodexEventError(event); + throw new CodexApiError(`Codex error: ${message || code || JSON.stringify(event)}`, { + code, + payload: event, + }); + } + if (type === "response.failed") { + const response = event.response; + const code = response?.error?.code; + const message = response?.error?.message; + throw new CodexApiError(message || "Codex response failed", { code, payload: event }); + } + if (type === "response.done" || type === "response.completed" || type === "response.incomplete") { + const response = event.response; + if (typeof response?.end_turn === "boolean") { + output.endTurn = response.end_turn; + } + const normalizedResponse = response + ? { ...response, status: normalizeCodexStatus(response.status) } + : response; + yield { ...event, type: "response.completed", response: normalizedResponse }; + return; + } + yield event; + } +} +function normalizeCodexStatus(status) { + if (typeof status !== "string") + return undefined; + return CODEX_RESPONSE_STATUSES.has(status) ? status : undefined; +} +// ============================================================================ +// SSE Parsing +// ============================================================================ +async function* parseSSE(response, signal) { + if (!response.body) + return; + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + const onAbort = () => { + void reader.cancel().catch(() => { }); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + try { + while (true) { + if (signal?.aborted) { + throw new Error("Request was aborted"); + } + const { done, value } = await reader.read(); + if (signal?.aborted) { + throw new Error("Request was aborted"); + } + buffer += done ? decoder.decode() : decoder.decode(value, { stream: true }); + // Treat EOF as terminating the residual SSE frame. + if (done && buffer.trim()) + buffer += "\n\n"; + let idx = buffer.indexOf("\n\n"); + while (idx !== -1) { + const chunk = buffer.slice(0, idx); + buffer = buffer.slice(idx + 2); + const dataLines = chunk + .split("\n") + .filter((l) => l.startsWith("data:")) + .map((l) => l.slice(5).trim()); + if (dataLines.length > 0) { + const data = dataLines.join("\n").trim(); + if (data && data !== "[DONE]") { + try { + yield JSON.parse(data); + } + catch (cause) { + throw new CodexProtocolError(`Invalid Codex SSE JSON: ${(0,diagnostics/* formatThrownValue */.Fu)(cause)}`, { + cause, + payload: data, + }); + } + } + } + idx = buffer.indexOf("\n\n"); + } + if (done) + break; + } + } + finally { + signal?.removeEventListener("abort", onAbort); + try { + await reader.cancel(); + } + catch { } + try { + reader.releaseLock(); + } + catch { } + } +} +// ============================================================================ +// WebSocket Parsing +// ============================================================================ +const OPENAI_BETA_RESPONSES_WEBSOCKETS = "responses_websockets=2026-02-06"; +const SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000; +const SESSION_WEBSOCKET_MAX_AGE_MS = 55 * 60 * 1000; +const websocketSessionCache = new Map(); +const websocketDebugStats = new Map(); +const websocketSseFallbackSessions = new Set(); +function getOrCreateWebSocketDebugStats(sessionId) { + let stats = websocketDebugStats.get(sessionId); + if (!stats) { + stats = { + requests: 0, + connectionsCreated: 0, + connectionsReused: 0, + cachedContextRequests: 0, + storeTrueRequests: 0, + fullContextRequests: 0, + deltaRequests: 0, + lastInputItems: 0, + websocketFailures: 0, + sseFallbacks: 0, + }; + websocketDebugStats.set(sessionId, stats); + } + return stats; +} +function getOpenAICodexWebSocketDebugStats(sessionId) { + const stats = websocketDebugStats.get(sessionId); + return stats ? { ...stats } : undefined; +} +function resetOpenAICodexWebSocketDebugStats(sessionId) { + if (sessionId) { + websocketDebugStats.delete(sessionId); + websocketSseFallbackSessions.delete(sessionId); + return; + } + websocketDebugStats.clear(); + websocketSseFallbackSessions.clear(); +} +function closeOpenAICodexWebSocketSessions(sessionId) { + const closeEntry = (entry) => { + if (entry.idleTimer) + clearTimeout(entry.idleTimer); + closeWebSocketSilently(entry.socket, 1000, "debug_close"); + }; + if (sessionId) { + for (const entry of websocketSessionCache.get(sessionId)?.values() ?? []) + closeEntry(entry); + websocketSessionCache.delete(sessionId); + return; + } + for (const accountEntries of websocketSessionCache.values()) { + for (const entry of accountEntries.values()) + closeEntry(entry); + } + websocketSessionCache.clear(); +} +(0,session_resources/* registerSessionResourceCleanup */.m)(closeOpenAICodexWebSocketSessions); +function isWebSocketSseFallbackActive(sessionId) { + return sessionId ? websocketSseFallbackSessions.has(sessionId) : false; +} +function recordWebSocketSseFallback(sessionId) { + if (!sessionId) + return; + const stats = getOrCreateWebSocketDebugStats(sessionId); + stats.sseFallbacks++; + stats.websocketFallbackActive = isWebSocketSseFallbackActive(sessionId); +} +function recordWebSocketFailure(sessionId, error) { + if (!sessionId) + return; + websocketSseFallbackSessions.add(sessionId); + const stats = getOrCreateWebSocketDebugStats(sessionId); + stats.websocketFailures++; + stats.lastWebSocketError = (0,diagnostics/* formatThrownValue */.Fu)(error); + stats.websocketFallbackActive = true; +} +let _cachedWebsocket = null; +async function getWebSocketConstructor(env) { + if (!env && _cachedWebsocket) + return _cachedWebsocket; + // bun doesn't respect http proxy envs, ref: https://github.com/oven-sh/bun/issues/15489 + // TODO: remove this when bun supports proxy envs in websocket. + if (typeof process !== "undefined" && process.versions?.bun) { + const WebSocketWithProxy = class extends WebSocket { + constructor(url, options) { + let _opts = {}; + if (Array.isArray(options) || typeof options === "string") { + _opts = { protocols: options }; + } + else { + _opts = { ...options }; + } + const proxyUrl = (0,node_http_proxy/* resolveHttpProxyUrlForTarget */.Q)(url.toString().replace(/^wss:/, "https:").replace(/^ws:/, "http:"), env); + super(url, { ..._opts, ...(proxyUrl ? { proxy: proxyUrl.toString() } : {}) }); + } + }; + if (!env) { + _cachedWebsocket = WebSocketWithProxy; + } + return WebSocketWithProxy; + } + const ctor = globalThis.WebSocket; + if (typeof ctor !== "function") + return null; + return ctor; +} +class WebSocketCloseError extends Error { + code; + reason; + wasClean; + constructor(message, options) { + super(message); + this.name = "WebSocketCloseError"; + this.code = options?.code; + this.reason = options?.reason; + this.wasClean = options?.wasClean; + } +} +function getWebSocketReadyState(socket) { + const readyState = socket.readyState; + return typeof readyState === "number" ? readyState : undefined; +} +function isWebSocketReusable(socket) { + const readyState = getWebSocketReadyState(socket); + // If readyState is unavailable, assume the runtime keeps it open/reusable. + return readyState === undefined || readyState === 1; +} +function isWebSocketSessionExpired(entry) { + return Date.now() - entry.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS; +} +function closeWebSocketSilently(socket, code = 1000, reason = "done") { + try { + socket.close(code, reason); + } + catch { } +} +function scheduleSessionWebSocketExpiry(sessionId, accountId, entry) { + if (entry.idleTimer) { + clearTimeout(entry.idleTimer); + } + entry.idleTimer = setTimeout(() => { + if (entry.busy) + return; + closeWebSocketSilently(entry.socket, 1000, "idle_timeout"); + const accountEntries = websocketSessionCache.get(sessionId); + if (accountEntries?.get(accountId) === entry) + accountEntries.delete(accountId); + if (accountEntries?.size === 0) + websocketSessionCache.delete(sessionId); + }, SESSION_WEBSOCKET_CACHE_TTL_MS); +} +async function connectWebSocket(url, headers, signal, connectTimeoutMs = DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS, env) { + const WebSocketCtor = await getWebSocketConstructor(env); + if (!WebSocketCtor) { + throw new Error("WebSocket transport is not available in this runtime"); + } + const wsHeaders = (0,utils_headers/* headersToRecord */.j)(headers); + delete wsHeaders["OpenAI-Beta"]; + return new Promise((resolve, reject) => { + let settled = false; + let timeout; + let socket; + try { + socket = new WebSocketCtor(url, { headers: wsHeaders }); + } + catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + return; + } + const cleanup = () => { + if (timeout) { + clearTimeout(timeout); + timeout = undefined; + } + socket.removeEventListener("open", onOpen); + socket.removeEventListener("error", onError); + socket.removeEventListener("close", onClose); + signal?.removeEventListener("abort", onAbort); + }; + const fail = (error, closeReason) => { + if (settled) + return; + settled = true; + cleanup(); + if (closeReason) { + closeWebSocketSilently(socket, 1000, closeReason); + } + reject(error); + }; + const onOpen = () => { + if (settled) + return; + settled = true; + cleanup(); + resolve(socket); + }; + const onError = (event) => { + fail(extractWebSocketError(event)); + }; + const onClose = (event) => { + fail(extractWebSocketCloseError(event)); + }; + const onAbort = () => { + fail(new Error("Request was aborted"), "aborted"); + }; + socket.addEventListener("open", onOpen); + socket.addEventListener("error", onError); + socket.addEventListener("close", onClose); + signal?.addEventListener("abort", onAbort); + if (connectTimeoutMs > 0) { + timeout = setTimeout(() => { + fail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`), "connect_timeout"); + }, connectTimeoutMs); + } + if (signal?.aborted) { + onAbort(); + } + }); +} +async function acquireWebSocket(url, headers, sessionId, accountId, signal, connectTimeoutMs, env) { + if (!sessionId) { + const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env); + return { + socket, + reused: false, + release: () => closeWebSocketSilently(socket), + }; + } + let accountEntries = websocketSessionCache.get(sessionId); + const cached = accountEntries?.get(accountId); + if (cached) { + if (cached.idleTimer) { + clearTimeout(cached.idleTimer); + cached.idleTimer = undefined; + } + if (!cached.busy && isWebSocketSessionExpired(cached)) { + closeWebSocketSilently(cached.socket, 1000, "connection_age_limit"); + accountEntries?.delete(accountId); + if (accountEntries?.size === 0) + websocketSessionCache.delete(sessionId); + } + else if (!cached.busy && isWebSocketReusable(cached.socket)) { + cached.busy = true; + return { + socket: cached.socket, + entry: cached, + reused: true, + release: ({ keep } = {}) => { + if (!keep || !isWebSocketReusable(cached.socket)) { + closeWebSocketSilently(cached.socket); + const currentEntries = websocketSessionCache.get(sessionId); + if (currentEntries?.get(accountId) === cached) + currentEntries.delete(accountId); + if (currentEntries?.size === 0) + websocketSessionCache.delete(sessionId); + return; + } + cached.busy = false; + scheduleSessionWebSocketExpiry(sessionId, accountId, cached); + }, + }; + } + if (cached.busy) { + const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env); + return { + socket, + reused: false, + release: () => { + closeWebSocketSilently(socket); + }, + }; + } + if (!isWebSocketReusable(cached.socket)) { + closeWebSocketSilently(cached.socket); + accountEntries?.delete(accountId); + if (accountEntries?.size === 0) + websocketSessionCache.delete(sessionId); + } + } + const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env); + const entry = { socket, busy: true, createdAt: Date.now() }; + accountEntries = websocketSessionCache.get(sessionId); + if (!accountEntries) { + accountEntries = new Map(); + websocketSessionCache.set(sessionId, accountEntries); + } + accountEntries.set(accountId, entry); + return { + socket, + entry, + reused: false, + release: ({ keep } = {}) => { + if (!keep || !isWebSocketReusable(entry.socket)) { + closeWebSocketSilently(entry.socket); + if (entry.idleTimer) + clearTimeout(entry.idleTimer); + const currentEntries = websocketSessionCache.get(sessionId); + if (currentEntries?.get(accountId) === entry) + currentEntries.delete(accountId); + if (currentEntries?.size === 0) + websocketSessionCache.delete(sessionId); + return; + } + entry.busy = false; + scheduleSessionWebSocketExpiry(sessionId, accountId, entry); + }, + }; +} +function extractWebSocketError(event) { + if (event && typeof event === "object") { + const message = "message" in event ? event.message : undefined; + if (typeof message === "string" && message.length > 0) { + return new Error(message); + } + const nestedError = "error" in event ? event.error : undefined; + if (nestedError instanceof Error && nestedError.message.length > 0) { + return nestedError; + } + if (nestedError && typeof nestedError === "object" && "message" in nestedError) { + const nestedMessage = nestedError.message; + if (typeof nestedMessage === "string" && nestedMessage.length > 0) { + return new Error(nestedMessage); + } + } + } + return new Error("WebSocket error"); +} +function extractWebSocketCloseError(event) { + if (event && typeof event === "object") { + const code = "code" in event ? event.code : undefined; + const reason = "reason" in event ? event.reason : undefined; + const wasClean = "wasClean" in event ? event.wasClean : undefined; + const codeText = typeof code === "number" ? ` ${code}` : ""; + let reasonText = typeof reason === "string" && reason.length > 0 ? ` ${reason}` : ""; + if (!reasonText && code === WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE) { + reasonText = " message too big"; + } + return new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(), { + code: typeof code === "number" ? code : undefined, + reason: typeof reason === "string" && reason.length > 0 ? reason : undefined, + wasClean: typeof wasClean === "boolean" ? wasClean : undefined, + }); + } + return new Error("WebSocket closed"); +} +async function decodeWebSocketData(data) { + if (typeof data === "string") + return data; + if (data instanceof ArrayBuffer) { + return new TextDecoder().decode(new Uint8Array(data)); + } + if (ArrayBuffer.isView(data)) { + const view = data; + return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)); + } + if (data && typeof data === "object" && "arrayBuffer" in data) { + const blobLike = data; + const arrayBuffer = await blobLike.arrayBuffer(); + return new TextDecoder().decode(new Uint8Array(arrayBuffer)); + } + return null; +} +async function* parseWebSocket(socket, signal, idleTimeoutMs) { + const queue = []; + let pending = null; + let done = false; + let failed = null; + let sawCompletion = false; + const wake = () => { + if (!pending) + return; + const resolve = pending; + pending = null; + resolve(); + }; + const onMessage = (event) => { + void (async () => { + let text = null; + try { + if (!event || typeof event !== "object" || !("data" in event)) + return; + text = await decodeWebSocketData(event.data); + if (!text) + return; + const parsed = JSON.parse(text); + const type = typeof parsed.type === "string" ? parsed.type : ""; + if (type === "response.completed" || type === "response.done" || type === "response.incomplete") { + sawCompletion = true; + done = true; + } + queue.push(parsed); + wake(); + } + catch (cause) { + failed = new CodexProtocolError(`Invalid Codex WebSocket JSON: ${(0,diagnostics/* formatThrownValue */.Fu)(cause)}`, { + cause, + payload: text, + }); + done = true; + wake(); + } + })(); + }; + const onError = (event) => { + failed = extractWebSocketError(event); + done = true; + wake(); + }; + const onClose = (event) => { + if (sawCompletion) { + done = true; + wake(); + return; + } + if (!failed) { + failed = extractWebSocketCloseError(event); + } + done = true; + wake(); + }; + const onAbort = () => { + failed = new Error("Request was aborted"); + done = true; + wake(); + }; + socket.addEventListener("message", onMessage); + socket.addEventListener("error", onError); + socket.addEventListener("close", onClose); + signal?.addEventListener("abort", onAbort); + try { + while (true) { + if (signal?.aborted) { + throw new Error("Request was aborted"); + } + if (queue.length > 0) { + yield queue.shift(); + continue; + } + if (done) + break; + let timeout; + await new Promise((resolve, reject) => { + pending = resolve; + if (idleTimeoutMs !== undefined && idleTimeoutMs > 0) { + timeout = setTimeout(() => { + const error = new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`); + failed = error; + done = true; + pending = null; + closeWebSocketSilently(socket, 1000, "idle_timeout"); + reject(error); + }, idleTimeoutMs); + } + }).finally(() => { + if (timeout) { + clearTimeout(timeout); + } + }); + } + if (failed) { + throw failed; + } + if (!sawCompletion) { + throw new Error("WebSocket stream closed before response.completed"); + } + } + finally { + socket.removeEventListener("message", onMessage); + socket.removeEventListener("error", onError); + socket.removeEventListener("close", onClose); + signal?.removeEventListener("abort", onAbort); + } +} +function requestBodyWithoutInput(body) { + const { input: _input, previous_response_id: _previousResponseId, ...rest } = body; + return rest; +} +function responseInputsEqual(a, b) { + return JSON.stringify(a ?? []) === JSON.stringify(b ?? []); +} +function requestBodiesMatchExceptInput(a, b) { + return JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b)); +} +function getCachedWebSocketInputDelta(body, continuation) { + if (!requestBodiesMatchExceptInput(body, continuation.lastRequestBody)) { + return undefined; + } + const currentInput = body.input ?? []; + const baseline = [...(continuation.lastRequestBody.input ?? []), ...continuation.lastResponseItems]; + if (currentInput.length < baseline.length) { + return undefined; + } + const prefix = currentInput.slice(0, baseline.length); + if (!responseInputsEqual(prefix, baseline)) { + return undefined; + } + return currentInput.slice(baseline.length); +} +function buildCachedWebSocketRequestBody(entry, body) { + const continuation = entry.continuation; + if (!continuation) { + return body; + } + const delta = getCachedWebSocketInputDelta(body, continuation); + if (!delta || !continuation.lastResponseId) { + entry.continuation = undefined; + return body; + } + return { + ...body, + previous_response_id: continuation.lastResponseId, + input: delta, + }; +} +async function* startWebSocketOutputOnFirstEvent(events, onStart) { + let started = false; + for await (const event of events) { + if (!started) { + started = true; + onStart(); + } + yield event; + } +} +async function processWebSocketStream(url, body, headers, output, stream, model, onStart, idleTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options) { + const { socket, entry, reused, release } = await acquireWebSocket(url, headers, cacheSessionId, accountId, options?.signal, websocketConnectTimeoutMs, options?.env); + let keepConnection = true; + const useCachedContext = options?.transport === "websocket-cached" || options?.transport === "auto"; + // ChatGPT Codex Responses rejects `store: true` ("Store must be set to false"). + // WebSocket continuation still works via connection-scoped previous_response_id state. + const fullBody = body; + const requestBody = useCachedContext && entry ? buildCachedWebSocketRequestBody(entry, fullBody) : fullBody; + const stats = cacheSessionId ? getOrCreateWebSocketDebugStats(cacheSessionId) : undefined; + if (stats) { + stats.requests++; + if (reused) + stats.connectionsReused++; + else + stats.connectionsCreated++; + if (useCachedContext) + stats.cachedContextRequests++; + if (requestBody.store === true) + stats.storeTrueRequests++; + stats.lastInputItems = requestBody.input?.length ?? 0; + if (requestBody.previous_response_id) { + stats.deltaRequests++; + stats.lastDeltaInputItems = requestBody.input?.length ?? 0; + stats.lastPreviousResponseId = requestBody.previous_response_id; + } + else { + stats.fullContextRequests++; + stats.lastDeltaInputItems = undefined; + stats.lastPreviousResponseId = undefined; + } + } + try { + socket.send(JSON.stringify({ type: "response.create", ...requestBody })); + await (0,openai_responses_shared/* processResponsesStream */.KB)(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket, options?.signal, idleTimeoutMs), output), onStart), output, stream, model, { + serviceTier: options?.serviceTier, + grammarToolInputProperties, + resolveServiceTier: resolveCodexServiceTier, + applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model), + }); + if (options?.signal?.aborted) { + keepConnection = false; + } + else if (useCachedContext && entry && output.responseId) { + const responseItems = (0,openai_responses_shared/* convertResponsesMessages */.iq)(model, (0,transcript/* normalizeContext */.dF)({ messages: [output] }), CODEX_TOOL_CALL_PROVIDERS, { + includeSystemPrompt: false, + grammarToolInputProperties, + }).filter((item) => item.type !== "function_call_output" && item.type !== "custom_tool_call_output"); + entry.continuation = { + lastRequestBody: fullBody, + lastResponseId: output.responseId, + lastResponseItems: responseItems, + }; + } + } + catch (error) { + if (entry) { + entry.continuation = undefined; + } + keepConnection = false; + throw error; + } + finally { + release({ keep: keepConnection }); + } +} +// ============================================================================ +// Error Handling +// ============================================================================ +async function parseErrorResponse(response) { + const raw = await response.text(); + let message = raw || response.statusText || "Request failed"; + let friendlyMessage; + try { + const parsed = JSON.parse(raw); + const err = parsed?.error; + if (err) { + const code = err.code || err.type || ""; + if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) { + const plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : ""; + const mins = err.resets_at + ? Math.max(0, Math.round((err.resets_at * 1000 - Date.now()) / 60000)) + : undefined; + const when = mins !== undefined ? ` Try again in ~${mins} min.` : ""; + friendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim(); + } + message = err.message || friendlyMessage || message; + } + } + catch { } + return { message, friendlyMessage }; +} +// ============================================================================ +// Auth & Headers +// ============================================================================ +function extractAccountId(token) { + try { + const parts = token.split("."); + if (parts.length !== 3) + throw new Error("Invalid token"); + const payload = JSON.parse(atob(parts[1])); + const accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id; + if (!accountId) + throw new Error("No account ID in token"); + return accountId; + } + catch { + throw new Error("Failed to extract accountId from token"); + } +} +function buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token) { + const headers = new Headers(initHeaders); + for (const [key, value] of Object.entries(additionalHeaders || {})) { + if (value === null) { + headers.delete(key); + } + else { + headers.set(key, value); + } + } + headers.set("Authorization", `Bearer ${token}`); + headers.set("chatgpt-account-id", accountId); + headers.set("originator", "pi"); + headers.set("User-Agent", (0,pi_user_agent/* getPiUserAgent */.w)()); + return headers; +} +function buildSSEHeaders(initHeaders, additionalHeaders, accountId, token, sessionId) { + const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token); + headers.set("OpenAI-Beta", "responses=experimental"); + headers.set("accept", "text/event-stream"); + headers.set("content-type", "application/json"); + if (sessionId) { + headers.set("session-id", sessionId); + headers.set("x-client-request-id", sessionId); + } + return headers; +} +function buildWebSocketHeaders(initHeaders, additionalHeaders, accountId, token, requestId) { + const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token); + headers.delete("accept"); + headers.delete("content-type"); + headers.delete("OpenAI-Beta"); + headers.delete("openai-beta"); + headers.set("OpenAI-Beta", OPENAI_BETA_RESPONSES_WEBSOCKETS); + headers.set("x-client-request-id", requestId); + headers.set("session-id", requestId); + return headers; +} +//# sourceMappingURL=openai-codex-responses.js.map + +/***/ }), + +/***/ 79475: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ K: () => (/* binding */ cleanupSessionResources), +/* harmony export */ m: () => (/* binding */ registerSessionResourceCleanup) +/* harmony export */ }); +const sessionResourceCleanups = new Set(); +function registerSessionResourceCleanup(cleanup) { + sessionResourceCleanups.add(cleanup); + return () => { + sessionResourceCleanups.delete(cleanup); + }; +} +function cleanupSessionResources(sessionId) { + const errors = []; + for (const cleanup of sessionResourceCleanups) { + try { + cleanup(sessionId); + } + catch (error) { + errors.push(error); + } + } + if (errors.length > 0) { + throw new AggregateError(errors, "Failed to cleanup session resources"); + } +} +//# sourceMappingURL=session-resources.js.map + +/***/ }), + +/***/ 20372: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Jo: () => (/* binding */ normalizeProviderError), +/* harmony export */ lR: () => (/* binding */ formatProviderError) +/* harmony export */ }); +/* unused harmony exports MAX_PROVIDER_ERROR_BODY_CHARS, truncateErrorText, safeJsonStringify */ +// Shared normalization for provider HTTP error objects. +// +// Endpoints behind a proxy / gateway may return a non-2xx response whose body +// the provider SDK cannot fold into `error.message`. The SDK error object still +// carries the HTTP status and the raw/parsed body, but under SDK-specific field +// names. Provider catch blocks that read only `error.message` therefore drop +// the body and surface opaque messages like `"403 status code (no body)"` or +// collapse to `"Unknown: UnknownError"`. +// +// `normalizeProviderError` probes the known SDK field shapes (Mistral, +// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider +// composes into its display string. The `messageCarriesBody` flag captures the +// Anthropic / `@google/genai` happy path where the SDK already folded the body +// into the message, so providers can preserve it without double-printing. +const MAX_PROVIDER_ERROR_BODY_CHARS = 4000; +function normalizeProviderError(error) { + if (!(error instanceof Error)) { + return { message: safeJsonStringify(error), messageCarriesBody: false }; + } + const sdkError = error; + const status = extractStatus(sdkError); + const body = extractBody(sdkError); + const messageCarriesBody = body === undefined || error.message.includes(body); + return { + status, + body, + message: error.message, + messageCarriesBody, + }; +} +/** + * Probe the HTTP status, first numeric hit wins, in SDK-field order: + * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) → + * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock). + */ +function extractStatus(error) { + if (typeof error.statusCode === "number") + return error.statusCode; + if (typeof error.status === "number") + return error.status; + if (typeof error.$metadata?.httpStatusCode === "number") + return error.$metadata.httpStatusCode; + if (typeof error.$response?.statusCode === "number") + return error.$response.statusCode; + return undefined; +} +/** + * Probe the raw body reason, first usable hit wins, in SDK-field order: + * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's + * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response + * streams are treated as no body so they do not surface as `"{}"` or serialized + * stream internals. The chosen body is truncated to the cap. + */ +function extractBody(error) { + const bodyText = pickBodyText(error); + if (bodyText === undefined) + return undefined; + const trimmed = bodyText.trim(); + if (trimmed.length === 0) + return undefined; + return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS); +} +function pickBodyText(error) { + if (typeof error.body === "string") + return error.body; + if (isPlainNonEmptyObject(error.error)) + return safeJsonStringify(error.error); + const responseBody = error.$response?.body; + if (typeof responseBody === "string") + return responseBody; + if (isReadableStreamLike(responseBody)) + return undefined; + if (isPlainNonEmptyObject(responseBody)) + return safeJsonStringify(responseBody); + return undefined; +} +function isReadableStreamLike(value) { + return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function"; +} +/** + * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class + * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an + * HTTP stream/response wrapper object, and stringifying one produced garbage + * like `{"_events":...}` as the "body", which then REPLACED `error.message` + * in the composed display string. `error.message` is where the SDK puts the + * real deserialized exception text ("Input is too long...", schema validation + * details, ...), so the one useful string was discarded for noise. A class + * instance yields no body, `messageCarriesBody` stays true, and the real + * message survives. Complements the `pipe` sniffing above: web + * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper + * classes fail the prototype check, while parsed JSON bodies (plain objects + * by construction) still pass. + */ +function isPlainNonEmptyObject(value) { + if (typeof value !== "object" || value === null) + return false; + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + return false; + return Object.keys(value).length > 0; +} +/** + * Compose a display string from a normalized error. When the message already + * carries the body (Anthropic / `@google/genai` happy path) or no body/status + * was extracted, the message is returned unchanged. Otherwise the status and + * body are surfaced, with an optional provider prefix. + * + * - no prefix: `": "` + * - prefix: `" (): "` + */ +function formatProviderError(norm, prefix) { + if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) { + return prefix !== undefined && norm.status !== undefined + ? `${prefix} (${norm.status}): ${norm.message}` + : norm.message; + } + return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`; +} +function truncateErrorText(text, maxChars) { + if (text.length <= maxChars) + return text; + return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`; +} +function safeJsonStringify(value) { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? String(value) : serialized; + } + catch { + return String(value); + } +} +//# sourceMappingURL=error-body.js.map + +/***/ }), + +/***/ 78191: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Q: () => (/* binding */ resolveHttpProxyUrlForTarget) +/* harmony export */ }); +/* unused harmony export UNSUPPORTED_PROXY_PROTOCOL_MESSAGE */ +/* harmony import */ var _provider_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67982); + +const DEFAULT_PROXY_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; +function getProxyEnv(key, env) { + const lowercaseKey = key.toLowerCase(); + const uppercaseKey = key.toUpperCase(); + return (env?.[lowercaseKey] || + env?.[uppercaseKey] || + (0,_provider_env_js__WEBPACK_IMPORTED_MODULE_0__/* .getProviderEnvValue */ .Y)(lowercaseKey) || + (0,_provider_env_js__WEBPACK_IMPORTED_MODULE_0__/* .getProviderEnvValue */ .Y)(uppercaseKey) || + ""); +} +function parseProxyTargetUrl(targetUrl) { + if (targetUrl instanceof URL) { + return targetUrl; + } + try { + return new URL(targetUrl); + } + catch { + return undefined; + } +} +function stripBrackets(host) { + return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; +} +function parseNoProxyEntry(entry) { + const trimmed = entry.trim().toLowerCase(); + if (!trimmed) + return undefined; + if (trimmed.startsWith("[")) { + const closingBracket = trimmed.indexOf("]"); + if (closingBracket !== -1) { + const host = trimmed.slice(1, closingBracket); + const rest = trimmed.slice(closingBracket + 1); + if (rest.startsWith(":")) { + const port = Number.parseInt(rest.slice(1), 10); + return { host, port: Number.isNaN(port) ? 0 : port }; + } + return { host, port: 0 }; + } + } + if (trimmed.includes(":") && trimmed.split(":").length > 2) { + return { host: trimmed, port: 0 }; + } + const colonIndex = trimmed.lastIndexOf(":"); + if (colonIndex !== -1 && colonIndex === trimmed.indexOf(":")) { + const host = trimmed.slice(0, colonIndex); + const port = Number.parseInt(trimmed.slice(colonIndex + 1), 10); + if (!Number.isNaN(port)) { + return { host, port }; + } + } + return { host: trimmed, port: 0 }; +} +function shouldProxyHostname(hostname, port, env) { + const noProxy = getProxyEnv("no_proxy", env).toLowerCase(); + if (!noProxy) { + return true; + } + if (noProxy === "*") { + return false; + } + const normalizedTargetHost = stripBrackets(hostname.toLowerCase()); + return noProxy.split(/[,\s]/).every((entry) => { + const parsed = parseNoProxyEntry(entry); + if (!parsed) { + return true; + } + if (parsed.port && parsed.port !== port) { + return true; + } + let domain = stripBrackets(parsed.host); + if (domain.startsWith("*.")) { + domain = domain.slice(2); + } + else if (domain.startsWith(".") || domain.startsWith("*")) { + domain = domain.slice(1); + } + if (!domain) { + return true; + } + if (normalizedTargetHost === domain) { + return false; + } + if (normalizedTargetHost.endsWith(`.${domain}`)) { + return false; + } + return true; + }); +} +function getProxyForUrl(targetUrl, env) { + const parsedUrl = parseProxyTargetUrl(targetUrl); + if (!parsedUrl?.protocol || !parsedUrl.host) { + return ""; + } + const protocol = parsedUrl.protocol.split(":", 1)[0]; + const hostname = stripBrackets(parsedUrl.hostname || parsedUrl.host.replace(/:\d*$/, "")); + const port = Number.parseInt(parsedUrl.port, 10) || DEFAULT_PROXY_PORTS[protocol] || 0; + if (!shouldProxyHostname(hostname, port, env)) { + return ""; + } + let proxy = getProxyEnv(`${protocol}_proxy`, env) || getProxyEnv("all_proxy", env); + if (proxy && !proxy.includes("://")) { + proxy = `${protocol}://${proxy}`; + } + return proxy; +} +const UNSUPPORTED_PROXY_PROTOCOL_MESSAGE = "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL."; +function resolveHttpProxyUrlForTarget(targetUrl, env) { + const proxy = getProxyForUrl(targetUrl, env); + if (!proxy) { + return undefined; + } + let proxyUrl; + try { + proxyUrl = new URL(proxy); + } + catch (error) { + throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error ? error.message : String(error)}`); + } + if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") { + throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`); + } + return proxyUrl; +} +//# sourceMappingURL=node-http-proxy.js.map + +/***/ }), + +/***/ 33610: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ n: () => (/* binding */ uuidv7) +/* harmony export */ }); +const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff; +const MAX_SEQUENCE = (1n << 41n) - 1n; +let lastOrdinaryTimestamp = -1; +let sequence; +/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */ +function uuidv7(timestampMs) { + const requestedTimestamp = timestampMs ?? Date.now(); + if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) { + throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`); + } + const effectiveTimestamp = timestampMs === undefined ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs; + if (timestampMs === undefined) + lastOrdinaryTimestamp = effectiveTimestamp; + const bytes = new Uint8Array(16); + globalThis.crypto.getRandomValues(bytes); + if (sequence === undefined) { + sequence = + (BigInt(bytes[1]) << 32n) | + (BigInt(bytes[2]) << 24n) | + (BigInt(bytes[3]) << 16n) | + (BigInt(bytes[4]) << 8n) | + BigInt(bytes[5]); + } + else { + if (sequence === MAX_SEQUENCE) + throw new RangeError("UUIDv7 generator sequence exhausted"); + sequence++; + } + const timestamp = BigInt(effectiveTimestamp); + for (let index = 5; index >= 0; index--) { + bytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 0xff; + } + bytes[6] = 0x70 | Number((sequence >> 37n) & 0x0fn); + bytes[7] = Number((sequence >> 29n) & 0xffn); + bytes[8] = 0x80 | Number((sequence >> 23n) & 0x3fn); + bytes[9] = Number((sequence >> 15n) & 0xffn); + bytes[10] = Number((sequence >> 7n) & 0xffn); + bytes[11] = Number((sequence & 0x7fn) << 1n) | (bytes[11] & 0x01); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")); + return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`; +} +//# sourceMappingURL=uuid.js.map + +/***/ }) + +}; diff --git a/dist/action/550.index.js b/dist/action/550.index.js new file mode 100644 index 000000000..812c78cd3 --- /dev/null +++ b/dist/action/550.index.js @@ -0,0 +1,215 @@ +export const id = 550; +export const ids = [550]; +export const modules = { + +/***/ 32550: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ generateImages: () => (/* binding */ generateImages) +/* harmony export */ }); +/* harmony import */ var openai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3840); +/* harmony import */ var _utils_error_body_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20372); +/* harmony import */ var _utils_headers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82003); +/* harmony import */ var _utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46863); +/* harmony import */ var _utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(43780); + + + + + +const generateImages = async (model, context, options) => { + const output = { + api: model.api, + provider: model.provider, + model: model.id, + output: [], + stopReason: "stop", + timestamp: Date.now(), + }; + try { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const client = createClient(model, apiKey, options?.headers, options?.fetch); + let params = buildParams(model, context); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== undefined) { + params = nextParams; + } + const requestOptions = { + ...(options?.signal ? { signal: options.signal } : {}), + ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), + maxRetries: 0, + }; + const { data: response, response: rawResponse } = await (0,_utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_1__/* .retryProviderRequest */ .T)(() => client.chat.completions + .create(params, requestOptions) + .withResponse(), { + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + signal: options?.signal, + }); + await options?.onResponse?.({ status: rawResponse.status, headers: (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_2__/* .headersToRecord */ .j)(rawResponse.headers) }, model); + const imageResponse = response; + output.responseId = imageResponse.id; + if (imageResponse.usage) { + output.usage = parseUsage(imageResponse.usage, model); + } + const choice = imageResponse.choices[0]; + if (choice) { + const content = choice.message.content; + if (typeof content === "string" && content.length > 0) { + output.output.push({ type: "text", text: content }); + } + for (const image of choice.message.images ?? []) { + const imageUrl = typeof image.image_url === "string" ? image.image_url : image.image_url?.url; + if (!imageUrl?.startsWith("data:")) + continue; + const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/); + if (!matches) + continue; + output.output.push({ + type: "image", + mimeType: matches[1], + data: matches[2], + }); + } + } + return output; + } + catch (error) { + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = (0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_3__/* .formatProviderError */ .lR)((0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_3__/* .normalizeProviderError */ .Jo)(error)); + return output; + } +}; +function createClient(model, apiKey, optionsHeaders, fetch) { + return new openai__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + fetch, + defaultHeaders: (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_2__/* .providerHeadersToRecord */ .m)({ ...model.headers, ...optionsHeaders }), + }); +} +function buildParams(model, context) { + const content = context.input.map((item) => { + if (item.type === "text") { + return { + type: "text", + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(item.text), + }; + } + return { + type: "image_url", + image_url: { + url: `data:${item.mimeType};base64,${item.data}`, + }, + }; + }); + return { + model: model.id, + messages: [ + { + role: "user", + content, + }, + ], + stream: false, + modalities: model.output.includes("text") ? ["image", "text"] : ["image"], + }; +} +function parseUsage(rawUsage, model) { + const promptTokens = rawUsage.prompt_tokens || 0; + const reportedCachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0; + const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0; + const cacheReadTokens = cacheWriteTokens > 0 ? Math.max(0, reportedCachedTokens - cacheWriteTokens) : reportedCachedTokens; + const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens); + const output = rawUsage.completion_tokens || 0; + const usage = { + input, + output, + cacheRead: cacheReadTokens, + cacheWrite: cacheWriteTokens, + totalTokens: input + output + cacheReadTokens + cacheWriteTokens, + cost: { + input: (model.cost.input / 1000000) * input, + output: (model.cost.output / 1000000) * output, + cacheRead: (model.cost.cacheRead / 1000000) * cacheReadTokens, + cacheWrite: (model.cost.cacheWrite / 1000000) * cacheWriteTokens, + total: 0, + }, + }; + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite; + return usage; +} +//# sourceMappingURL=openrouter-images.js.map + +/***/ }), + +/***/ 82003: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ headersToRecord), +/* harmony export */ m: () => (/* binding */ providerHeadersToRecord) +/* harmony export */ }); +function headersToRecord(headers) { + const result = {}; + for (const [key, value] of headers.entries()) { + result[key] = value; + } + return result; +} +function providerHeadersToRecord(headers) { + if (!headers) + return undefined; + const result = {}; + for (const [key, value] of Object.entries(headers)) { + if (value !== null) + result[key] = value; + } + return Object.keys(result).length > 0 ? result : undefined; +} +//# sourceMappingURL=headers.js.map + +/***/ }), + +/***/ 43780: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ J: () => (/* binding */ sanitizeSurrogates) +/* harmony export */ }); +/** + * Removes unpaired Unicode surrogate characters from a string. + * + * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF, + * or vice versa) cause JSON serialization errors in many API providers. + * + * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired + * surrogates and will NOT be affected by this function. + * + * @param text - The text to sanitize + * @returns The sanitized text with unpaired surrogates removed + * + * @example + * // Valid emoji (properly paired surrogates) are preserved + * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World" + * + * // Unpaired high surrogate is removed + * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low + * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here" + */ +function sanitizeSurrogates(text) { + // Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate) + // Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate) + return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + VIRTUAL_MODULES: () => (/* binding */ VIRTUAL_MODULES) +}); + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/oauth.js +var oauth_namespaceObject = {}; +__webpack_require__.r(oauth_namespaceObject); + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-agent-core@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-agent-core/dist/index.js + 78 modules +var dist = __webpack_require__(94265); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/compat.js + 8 modules +var compat = __webpack_require__(45610); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/oauth.js + +//# sourceMappingURL=oauth.js.map +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/providers/all.js + 124 modules +var providers_all = __webpack_require__(75252); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-tui@0.86.1/node_modules/@earendil-works/pi-tui/dist/index.js + 41 modules +var pi_tui_dist = __webpack_require__(80040); +// EXTERNAL MODULE: ../../node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/index.mjs + 1 modules +var build = __webpack_require__(91862); +// EXTERNAL MODULE: ../../node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/compile/index.mjs + 3 modules +var compile = __webpack_require__(71257); +// EXTERNAL MODULE: ../../node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/index.mjs + 142 modules +var value = __webpack_require__(20352); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-coding-agent@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-coding-agent/dist/index.js + 221 modules +var pi_coding_agent_dist = __webpack_require__(53406); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-coding-agent@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/virtual-modules.js + + + + + + + + +// This import is safe because loader.ts exports are not re-exported from index.ts. +// Extensions can therefore import from @earendil-works/pi-coding-agent. + +/** Modules available to extensions in source and compiled binary runtimes. */ +const VIRTUAL_MODULES = { + typebox: build, + "typebox/compile": compile, + "typebox/value": value, + "@sinclair/typebox": build, + "@sinclair/typebox/compile": compile, + "@sinclair/typebox/value": value, + "@earendil-works/pi-agent-core": dist, + "@earendil-works/pi-tui": pi_tui_dist, + // Extensions resolve the pi-ai root to the compat entrypoint (a strict + // superset of the core entrypoint): existing extensions using the old + // global API keep working at runtime until compat is removed. + "@earendil-works/pi-ai": compat, + "@earendil-works/pi-ai/compat": compat, + "@earendil-works/pi-ai/oauth": oauth_namespaceObject, + "@earendil-works/pi-ai/providers/all": providers_all, + "@earendil-works/pi-coding-agent": pi_coding_agent_dist, + "@mariozechner/pi-agent-core": dist, + "@mariozechner/pi-tui": pi_tui_dist, + "@mariozechner/pi-ai": compat, + "@mariozechner/pi-ai/compat": compat, + "@mariozechner/pi-ai/oauth": oauth_namespaceObject, + "@mariozechner/pi-ai/providers/all": providers_all, + "@mariozechner/pi-coding-agent": pi_coding_agent_dist, +}; +//# sourceMappingURL=virtual-modules.js.map + +/***/ }) + +}; diff --git a/dist/action/599.index.js b/dist/action/599.index.js new file mode 100644 index 000000000..53360cecd --- /dev/null +++ b/dist/action/599.index.js @@ -0,0 +1,554 @@ +export const id = 599; +export const ids = [599]; +export const modules = { + +/***/ 93323: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +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.req = exports.json = exports.toBuffer = void 0; +const http = __importStar(__webpack_require__(58611)); +const https = __importStar(__webpack_require__(65692)); +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +exports.toBuffer = toBuffer; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString('utf8'); + try { + return JSON.parse(str); + } + catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } +} +exports.json = json; +function req(url, opts = {}) { + const href = typeof url === 'string' ? url : url.href; + const req = (href.startsWith('https:') ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req + .once('response', resolve) + .once('error', reject) + .end(); + }); + req.then = promise.then.bind(promise); + return req; +} +exports.req = req; +//# sourceMappingURL=helpers.js.map + +/***/ }), + +/***/ 66714: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Agent = void 0; +const net = __importStar(__webpack_require__(69278)); +const http = __importStar(__webpack_require__(58611)); +const https_1 = __webpack_require__(65692); +__exportStar(__webpack_require__(93323), exports); +const INTERNAL = Symbol('AgentBaseInternalState'); +class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof options.secureEndpoint === 'boolean') { + return options.secureEndpoint; + } + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } + } + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack + .split('\n') + .some((l) => l.indexOf('(https.js:') !== -1 || + l.indexOf('node:https:') !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no + // need to create a fake socket because Node.js native connection pooling + // will never be invoked. + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + // All instances of `sockets` are expected TypeScript errors. The + // alternative is to add it as a private property of this class but that + // will break TypeScript subclassing. + if (!this.sockets[name]) { + // @ts-expect-error `sockets` is readonly in `@types/node` + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount--; + if (sockets.length === 0) { + // @ts-expect-error `sockets` is readonly in `@types/node` + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + // @ts-expect-error `getName()` isn't defined in `@types/node` + return https_1.Agent.prototype.getName.call(this, options); + } + // @ts-expect-error `getName()` isn't defined in `@types/node` + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + return socket.addRequest(req, connectOpts); + } + catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } + get defaultPort() { + return (this[INTERNAL].defaultPort ?? + (this.protocol === 'https:' ? 443 : 80)); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return (this[INTERNAL].protocol ?? + (this.isSecureEndpoint() ? 'https:' : 'http:')); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } +} +exports.Agent = Agent; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4599: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +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.HttpsProxyAgent = void 0; +const net = __importStar(__webpack_require__(69278)); +const tls = __importStar(__webpack_require__(64756)); +const assert_1 = __importDefault(__webpack_require__(42613)); +const debug_1 = __importDefault(__webpack_require__(26675)); +const agent_base_1 = __webpack_require__(66714); +const url_1 = __webpack_require__(87016); +const parse_proxy_response_1 = __webpack_require__(25701); +const debug = (0, debug_1.default)('https-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !net.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; + } + return options; +}; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + (0, assert_1.default)(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } +} +HttpsProxyAgent.protocols = ['http', 'https']; +exports.HttpsProxyAgent = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 25701: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseProxyResponse = void 0; +const debug_1 = __importDefault(__webpack_require__(26675)); +const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + +/***/ }) + +}; diff --git a/dist/action/627.index.js b/dist/action/627.index.js new file mode 100644 index 000000000..06d5c11c3 --- /dev/null +++ b/dist/action/627.index.js @@ -0,0 +1,257 @@ +export const id = 627; +export const ids = [627]; +export const modules = { + +/***/ 14420: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 14420; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 81627: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ bedrockConverseStreamApi: () => (/* binding */ bedrockConverseStreamApi), +/* harmony export */ setBedrockProviderModule: () => (/* binding */ setBedrockProviderModule) +/* harmony export */ }); +/* harmony import */ var _lazy_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78932); +var __rewriteRelativeImportExtension = (undefined && undefined.__rewriteRelativeImportExtension) || function (path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +}; + +/** + * Loads the bedrock implementation through a variable specifier so bundlers + * (browser smoke, Bun compile) cannot follow the import into the Node-only + * AWS SDK. The `.ts`/`.js` rewrite keeps the trick working from both source + * and built output. + */ +const importNodeOnlyApi = (specifier) => { + const runtimeSpecifier = import.meta.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier; + return __webpack_require__(14420)(__rewriteRelativeImportExtension(runtimeSpecifier)); +}; +let bedrockModuleOverride; +/** + * Overrides the dynamically imported bedrock implementation. Used by the Bun + * binary build, where the variable-specifier import cannot be bundled; the + * build registers a statically imported module instead. + */ +function setBedrockProviderModule(module) { + bedrockModuleOverride = module; +} +const bedrockConverseStreamApi = () => (0,_lazy_js__WEBPACK_IMPORTED_MODULE_0__/* .lazyApi */ .X)(async () => bedrockModuleOverride ?? (await importNodeOnlyApi("./bedrock-converse-stream.ts"))); +//# sourceMappingURL=bedrock-converse-stream.lazy.js.map + +/***/ }), + +/***/ 78932: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ lazyApi), +/* harmony export */ n: () => (/* binding */ lazyStream) +/* harmony export */ }); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45174); + +function createSetupErrorMessage(model, error) { + return { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "error", + errorMessage: error instanceof Error ? error.message : String(error), + timestamp: Date.now(), + }; +} +function hasResult(source) { + return typeof source.result === "function"; +} +async function forwardStream(target, source) { + for await (const event of source) { + target.push(event); + } + target.end(hasResult(source) ? await source.result() : undefined); +} +/** + * Returns a stream synchronously while running async setup (auth resolution, + * lazy module loading) behind it. Setup failures terminate the stream with an + * error event. + */ +function lazyStream(model, setup) { + const outer = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__/* .AssistantMessageEventStream */ .Q2(); + setup() + .then((inner) => forwardStream(outer, inner)) + .catch((error) => { + const message = createSetupErrorMessage(model, error); + outer.push({ type: "error", reason: "error", error: message }); + outer.end(message); + }); + return outer; +} +function lazyApi(load, capabilities) { + const api = { + stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)), + streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options)), + }; + if (capabilities?.fetchDeferred) { + api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => { + const implementation = await load(); + if (!implementation.fetchDeferred) + throw new Error("API does not support deferred responses"); + return implementation.fetchDeferred(model, handle, options); + }); + } + if (capabilities?.cancelDeferred) { + api.cancelDeferred = async (model, handle, options) => { + const implementation = await load(); + if (!implementation.cancelDeferred) + throw new Error("API cannot cancel deferred responses"); + await implementation.cancelDeferred(model, handle, options); + }; + } + return api; +} +//# sourceMappingURL=lazy.js.map + +/***/ }), + +/***/ 45174: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Q2: () => (/* binding */ AssistantMessageEventStream), +/* harmony export */ sM: () => (/* binding */ createAssistantMessageEventStream), +/* harmony export */ vC: () => (/* binding */ EventStream) +/* harmony export */ }); +class FifoQueue { + incoming = []; + outgoing = []; + get length() { + return this.incoming.length + this.outgoing.length; + } + enqueue(value) { + this.incoming.push(value); + } + dequeue() { + if (this.outgoing.length === 0) { + while (this.incoming.length > 0) { + this.outgoing.push(this.incoming.pop()); + } + } + return this.outgoing.pop(); + } +} +// Generic event stream class for async iteration +class EventStream { + queue = new FifoQueue(); + waiting = new FifoQueue(); + done = false; + finalResultPromise; + resolveFinalResult; + isComplete; + extractResult; + constructor(isComplete, extractResult) { + this.isComplete = isComplete; + this.extractResult = extractResult; + this.finalResultPromise = new Promise((resolve) => { + this.resolveFinalResult = resolve; + }); + } + push(event) { + if (this.done) + return; + if (this.isComplete(event)) { + this.done = true; + this.resolveFinalResult(this.extractResult(event)); + } + // Deliver to waiting consumer or queue it + const waiter = this.waiting.dequeue(); + if (waiter) { + waiter({ value: event, done: false }); + } + else { + this.queue.enqueue(event); + } + } + end(result) { + this.done = true; + if (result !== undefined) { + this.resolveFinalResult(result); + } + // Notify all waiting consumers that we're done + while (this.waiting.length > 0) { + const waiter = this.waiting.dequeue(); + waiter({ value: undefined, done: true }); + } + } + async *[Symbol.asyncIterator]() { + while (true) { + if (this.queue.length > 0) { + yield this.queue.dequeue(); + } + else if (this.done) { + return; + } + else { + const result = await new Promise((resolve) => this.waiting.enqueue(resolve)); + if (result.done) + return; + yield result.value; + } + } + } + result() { + return this.finalResultPromise; + } +} +class AssistantMessageEventStream extends EventStream { + constructor() { + super((event) => event.type === "done" || event.type === "error", (event) => { + if (event.type === "done") { + return event.message; + } + else if (event.type === "error") { + return event.error; + } + throw new Error("Unexpected event type for final result"); + }); + } +} +/** Factory function for AssistantMessageEventStream (for use in extensions) */ +function createAssistantMessageEventStream() { + return new AssistantMessageEventStream(); +} +//# sourceMappingURL=event-stream.js.map + +/***/ }) + +}; diff --git a/dist/action/629.index.js b/dist/action/629.index.js new file mode 100644 index 000000000..439b4c028 --- /dev/null +++ b/dist/action/629.index.js @@ -0,0 +1,820 @@ +export const id = 629; +export const ids = [629]; +export const modules = { + +/***/ 88629: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ stream: () => (/* binding */ stream), +/* harmony export */ streamSimple: () => (/* binding */ streamSimple) +/* harmony export */ }); +/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25941); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45174); +/* harmony import */ var _utils_hash_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1901); +/* harmony import */ var _utils_headers_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(82003); +/* harmony import */ var _utils_json_parse_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(84781); +/* harmony import */ var _utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(55278); +/* harmony import */ var _utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(43780); +/* harmony import */ var _utils_text_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(65678); +/* harmony import */ var _utils_transcript_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(19883); +/* harmony import */ var _constrained_sampling_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(37776); +/* harmony import */ var _simple_options_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(18296); +/* harmony import */ var _transform_messages_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48809); + + + + + + + + + + + + +const MISTRAL_TOOL_CALL_ID_LENGTH = 9; +const MAX_MISTRAL_ERROR_BODY_CHARS = 4000; +/** + * Stream responses from the native Mistral Chat Completions endpoint. + */ +const stream = (model, context, options) => { + const stream = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__/* .AssistantMessageEventStream */ .Q2(); + const normalizedContext = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_1__/* .resolveTranscript */ .lw)(context, model.compat?.supportsMidConvoSystemMessages); + (async () => { + const output = createOutput(model); + try { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const normalizeMistralToolCallId = createMistralToolCallIdNormalizer(); + const transformedMessages = (0,_transform_messages_js__WEBPACK_IMPORTED_MODULE_2__/* .transformMessages */ .b)(normalizedContext.messages, model, (id) => normalizeMistralToolCallId(id)); + let payload = buildChatPayload(model, normalizedContext, transformedMessages, options); + const nextPayload = await options?.onPayload?.(payload, model); + if (nextPayload !== undefined) { + payload = nextPayload; + } + const mistralStream = await requestMistralStream(model, payload, apiKey, options); + stream.push({ type: "start", partial: output }); + await consumeChatStream(model, output, stream, mistralStream); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "pending") { + throw new Error("Mistral stream ended without a finish reason"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + for (const block of output.content) { + // partialArgs is only a streaming scratch buffer; never persist it. + delete block.partialArgs; + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = formatMistralError(error); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +/** + * Maps provider-agnostic `SimpleStreamOptions` to Mistral options. + */ +const streamSimple = (model, context, options) => { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = { + ...(0,_simple_options_js__WEBPACK_IMPORTED_MODULE_3__/* .buildBaseOptions */ .QP)(model, context, options, apiKey), + toolChoice: options?.toolChoice, + }; + const clampedReasoning = options?.reasoning ? (0,_models_js__WEBPACK_IMPORTED_MODULE_4__/* .clampThinkingLevel */ .Kt)(model, options.reasoning) : undefined; + const reasoning = clampedReasoning === "off" ? undefined : clampedReasoning; + const shouldUseReasoning = model.reasoning && reasoning !== undefined; + return stream(model, context, { + ...base, + promptMode: shouldUseReasoning && usesPromptModeReasoning(model) ? "reasoning" : undefined, + reasoningEffort: shouldUseReasoning && usesReasoningEffort(model) ? mapReasoningEffort(model, reasoning) : undefined, + }); +}; +function createOutput(model) { + return { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; +} +function createMistralToolCallIdNormalizer() { + const idMap = new Map(); + const reverseMap = new Map(); + return (id) => { + const existing = idMap.get(id); + if (existing) + return existing; + let attempt = 0; + while (true) { + const candidate = deriveMistralToolCallId(id, attempt); + const owner = reverseMap.get(candidate); + if (!owner || owner === id) { + idMap.set(id, candidate); + reverseMap.set(candidate, id); + return candidate; + } + attempt++; + } + }; +} +function deriveMistralToolCallId(id, attempt) { + const normalized = id.replace(/[^a-zA-Z0-9]/g, ""); + if (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) + return normalized; + const seedBase = normalized || id; + const seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`; + return (0,_utils_hash_js__WEBPACK_IMPORTED_MODULE_5__/* .shortHash */ .B)(seed) + .replace(/[^a-zA-Z0-9]/g, "") + .slice(0, MISTRAL_TOOL_CALL_ID_LENGTH); +} +function formatMistralError(error) { + if (error instanceof Error) { + const httpError = error; + const statusCode = typeof httpError.statusCode === "number" ? httpError.statusCode : undefined; + const bodyText = typeof httpError.body === "string" ? httpError.body.trim() : undefined; + if (statusCode !== undefined && bodyText) { + return `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`; + } + if (statusCode !== undefined) + return `Mistral API error (${statusCode}): ${error.message}`; + return error.message; + } + return safeJsonStringify(error); +} +function truncateErrorText(text, maxChars) { + if (text.length <= maxChars) + return text; + return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`; +} +function safeJsonStringify(value) { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? String(value) : serialized; + } + catch { + return String(value); + } +} +async function requestMistralStream(model, payload, apiKey, options) { + const baseUrl = new URL(model.baseUrl); + baseUrl.pathname = `${baseUrl.pathname.replace(/\/+$/u, "")}/`; + const url = new URL("v1/chat/completions", baseUrl); + const headers = buildMistralHeaders(model, apiKey, options); + const timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 60_000); + const signal = options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal; + const response = await (options?.fetch ?? globalThis.fetch)(url, { + method: "POST", + headers, + body: JSON.stringify(toMistralWirePayload(payload)), + signal, + }); + await options?.onResponse?.({ status: response.status, headers: (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_6__/* .headersToRecord */ .j)(response.headers) }, model); + if (!response.ok) { + const body = await response.text(); + throw new MistralHttpError(response.status, body, response.statusText); + } + if (!response.body) { + throw new Error("Mistral response has no body"); + } + return readMistralEvents(response.body, signal); +} +class MistralHttpError extends Error { + statusCode; + body; + constructor(statusCode, body, statusText) { + super(statusText || `Request failed with status ${statusCode}`); + this.name = "MistralHttpError"; + this.statusCode = statusCode; + this.body = body; + } +} +function buildMistralHeaders(model, apiKey, options) { + const headers = new Headers({ + "User-Agent": (0,_utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_7__/* .getPiUserAgent */ .w)(), + accept: "text/event-stream", + authorization: `Bearer ${apiKey}`, + "content-type": "application/json", + }); + applyMistralHeaderOverrides(headers, model.headers); + applyMistralHeaderOverrides(headers, options?.headers); + const hasExplicitAffinity = hasMistralHeaderOverride(model.headers, "x-affinity") || hasMistralHeaderOverride(options?.headers, "x-affinity"); + if (shouldUsePromptCaching(options) && !hasExplicitAffinity) { + headers.set("x-affinity", options.sessionId); + } + return headers; +} +function applyMistralHeaderOverrides(headers, overrides) { + if (!overrides) + return; + for (const [name, value] of Object.entries(overrides)) { + if (value === null) + headers.delete(name); + else + headers.set(name, value); + } +} +function hasMistralHeaderOverride(overrides, target) { + return !!overrides && Object.keys(overrides).some((name) => name.toLowerCase() === target); +} +function toMistralWirePayload(payload) { + const wirePayload = { ...payload }; + for (const [source, target] of [ + ["topP", "top_p"], + ["maxTokens", "max_tokens"], + ["randomSeed", "random_seed"], + ["responseFormat", "response_format"], + ["toolChoice", "tool_choice"], + ["presencePenalty", "presence_penalty"], + ["frequencyPenalty", "frequency_penalty"], + ["parallelToolCalls", "parallel_tool_calls"], + ["reasoningEffort", "reasoning_effort"], + ["promptMode", "prompt_mode"], + ["promptCacheKey", "prompt_cache_key"], + ["safePrompt", "safe_prompt"], + ]) { + remapMistralProperty(wirePayload, source, target); + } + wirePayload.messages = payload.messages.map((message) => toMistralWireMessage(message)); + const responseFormat = wirePayload.response_format; + if (isMistralRecord(responseFormat)) { + const wireResponseFormat = { ...responseFormat }; + remapMistralProperty(wireResponseFormat, "jsonSchema", "json_schema"); + const jsonSchema = wireResponseFormat.json_schema; + if (isMistralRecord(jsonSchema)) { + const wireJsonSchema = { ...jsonSchema }; + remapMistralProperty(wireJsonSchema, "schemaDefinition", "schema"); + wireResponseFormat.json_schema = wireJsonSchema; + } + wirePayload.response_format = wireResponseFormat; + } + return wirePayload; +} +function toMistralWireMessage(message) { + const wireMessage = { ...message }; + remapMistralProperty(wireMessage, "toolCalls", "tool_calls"); + remapMistralProperty(wireMessage, "toolCallId", "tool_call_id"); + if (Array.isArray(message.content)) { + wireMessage.content = message.content.map((chunk) => toMistralWireContentChunk(chunk)); + } + return wireMessage; +} +function toMistralWireContentChunk(chunk) { + const wireChunk = { ...chunk }; + for (const [source, target] of [ + ["imageUrl", "image_url"], + ["documentUrl", "document_url"], + ["documentName", "document_name"], + ["fileId", "file_id"], + ["referenceIds", "reference_ids"], + ["inputAudio", "input_audio"], + ]) { + remapMistralProperty(wireChunk, source, target); + } + return wireChunk; +} +function remapMistralProperty(record, source, target) { + if (!(source in record)) + return; + record[target] = record[source]; + delete record[source]; +} +function isMistralRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +const MISTRAL_STREAM_DONE = Symbol("mistral-stream-done"); +async function* readMistralEvents(body, signal) { + const reader = body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + const onAbort = () => { + void reader.cancel().catch(() => { }); + }; + signal.addEventListener("abort", onAbort, { once: true }); + try { + while (true) { + if (signal.aborted) + throw signal.reason; + const { done, value } = await reader.read(); + if (signal.aborted) + throw signal.reason; + buffer += done ? decoder.decode() : decoder.decode(value, { stream: true }); + let boundary = findMistralEventBoundary(buffer); + while (boundary) { + const event = parseMistralEvent(buffer.slice(0, boundary.index)); + buffer = buffer.slice(boundary.index + boundary.length); + if (event === MISTRAL_STREAM_DONE) + return; + if (event) + yield event; + boundary = findMistralEventBoundary(buffer); + } + if (done) + break; + } + if (buffer.trim()) { + const event = parseMistralEvent(buffer); + if (event !== MISTRAL_STREAM_DONE && event) + yield event; + } + } + finally { + signal.removeEventListener("abort", onAbort); + try { + await reader.cancel(); + } + catch { } + try { + reader.releaseLock(); + } + catch { } + } +} +function findMistralEventBoundary(buffer) { + const match = /\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer); + return match?.index === undefined ? undefined : { index: match.index, length: match[0].length }; +} +function parseMistralEvent(raw) { + const data = raw + .split(/\r\n|\r|\n/u) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trimStart()) + .join("\n") + .trim(); + if (!data) + return undefined; + if (data === "[DONE]") + return MISTRAL_STREAM_DONE; + const parsed = JSON.parse(data); + if (!isMistralRecord(parsed) || !Array.isArray(parsed.choices)) { + throw new Error("Invalid Mistral streaming event"); + } + return { data: parsed }; +} +function buildChatPayload(model, context, messages, options) { + const payload = { + model: model.id, + stream: true, + messages: toChatMessages(messages, model.input.includes("image")), + }; + const currentTools = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_1__/* .getCurrentTools */ .Fh)(context.messages); + if (currentTools.length > 0) + payload.tools = toFunctionTools(currentTools); + if (options?.temperature !== undefined) + payload.temperature = options.temperature; + if (options?.maxTokens !== undefined) + payload.maxTokens = options.maxTokens; + if (options?.toolChoice) + payload.toolChoice = mapToolChoice(options.toolChoice); + if (options?.promptMode) + payload.promptMode = options.promptMode; + if (options?.reasoningEffort) + payload.reasoningEffort = options.reasoningEffort; + if (shouldUsePromptCaching(options)) + payload.promptCacheKey = options.sessionId; + return payload; +} +function shouldUsePromptCaching(options) { + return options?.cacheRetention !== "none" && !!options?.sessionId; +} +function getMistralCachedPromptTokens(usage, promptTokens) { + const rawUsage = usage; + const rawCachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? + rawUsage.prompt_tokens_details?.cached_tokens ?? + rawUsage.promptTokenDetails?.cachedTokens ?? + rawUsage.prompt_token_details?.cached_tokens ?? + rawUsage.numCachedTokens ?? + rawUsage.num_cached_tokens ?? + 0; + const cachedTokens = typeof rawCachedTokens === "number" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0; + return Math.min(promptTokens, Math.max(0, cachedTokens)); +} +async function consumeChatStream(model, output, stream, mistralStream) { + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + const toolBlocksByKey = new Map(); + const finishCurrentBlock = (block) => { + if (!block) + return; + if (block.type === "text") { + stream.push({ + type: "text_end", + contentIndex: blockIndex(), + content: block.text, + partial: output, + }); + return; + } + if (block.type === "thinking") { + stream.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: block.thinking, + partial: output, + }); + } + }; + for await (const event of mistralStream) { + const chunk = event.data; + // Mistral's streamed CompletionChunk carries an id field. Keep the first non-empty one, + // mirroring how OpenAI-style streaming exposes a stable response identifier per stream. + output.responseId ||= chunk.id; + if (chunk.usage) { + const promptTokens = chunk.usage.prompt_tokens || 0; + const cachedPromptTokens = getMistralCachedPromptTokens(chunk.usage, promptTokens); + output.usage.input = Math.max(0, promptTokens - cachedPromptTokens); + output.usage.output = chunk.usage.completion_tokens || 0; + output.usage.cacheRead = cachedPromptTokens; + output.usage.cacheWrite = 0; + output.usage.totalTokens = + chunk.usage.total_tokens || + output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; + (0,_models_js__WEBPACK_IMPORTED_MODULE_4__/* .calculateCost */ .yN)(model, output.usage); + } + const choice = chunk.choices[0]; + if (!choice) + continue; + if (choice.finish_reason) { + output.rawStopReason = choice.finish_reason; + const stopReasonResult = mapChatStopReason(choice.finish_reason); + output.stopReason = stopReasonResult.stopReason; + if (stopReasonResult.errorMessage) { + output.errorMessage = stopReasonResult.errorMessage; + } + } + const delta = choice.delta; + if (delta.content !== null && delta.content !== undefined) { + const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content; + for (const item of contentItems) { + if (typeof item === "string") { + const textDelta = (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(item); + if (!currentBlock || currentBlock.type !== "text") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.text += textDelta; + stream.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: textDelta, + partial: output, + }); + continue; + } + if (item.type === "thinking") { + const deltaText = (item.thinking ?? []) + .map((part) => part.text ?? "") + .filter((text) => text.length > 0) + .join(""); + const thinkingDelta = (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(deltaText); + if (!thinkingDelta) + continue; + if (!currentBlock || currentBlock.type !== "thinking") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "thinking", thinking: "" }; + output.content.push(currentBlock); + stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.thinking += thinkingDelta; + stream.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: thinkingDelta, + partial: output, + }); + continue; + } + if (item.type === "text") { + const textDelta = (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(item.text ?? ""); + if (!currentBlock || currentBlock.type !== "text") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.text += textDelta; + stream.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: textDelta, + partial: output, + }); + } + } + } + const toolCalls = delta.tool_calls || []; + for (const toolCall of toolCalls) { + if (currentBlock) { + finishCurrentBlock(currentBlock); + currentBlock = null; + } + const callId = toolCall.id && toolCall.id !== "null" + ? toolCall.id + : deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0); + const key = toolCall.index ?? callId; + const existingIndex = toolBlocksByKey.get(key); + let block; + if (existingIndex !== undefined) { + const existing = output.content[existingIndex]; + if (existing?.type === "toolCall") { + block = existing; + } + } + if (!block) { + block = { + type: "toolCall", + id: callId, + name: toolCall.function.name, + arguments: {}, + partialArgs: "", + }; + output.content.push(block); + toolBlocksByKey.set(key, output.content.length - 1); + stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }); + } + const argsDelta = typeof toolCall.function.arguments === "string" + ? toolCall.function.arguments + : JSON.stringify(toolCall.function.arguments || {}); + block.partialArgs = (block.partialArgs || "") + argsDelta; + block.arguments = (0,_utils_json_parse_js__WEBPACK_IMPORTED_MODULE_9__/* .parseStreamingJson */ .o2)(block.partialArgs); + stream.push({ + type: "toolcall_delta", + contentIndex: toolBlocksByKey.get(key), + delta: argsDelta, + partial: output, + }); + } + } + finishCurrentBlock(currentBlock); + for (const index of toolBlocksByKey.values()) { + const block = output.content[index]; + if (block.type !== "toolCall") + continue; + const toolBlock = block; + toolBlock.arguments = (0,_utils_json_parse_js__WEBPACK_IMPORTED_MODULE_9__/* .parseStreamingJson */ .o2)(toolBlock.partialArgs); + // Finalize in-place and strip the scratch buffer so replay only + // carries parsed arguments. + delete toolBlock.partialArgs; + stream.push({ + type: "toolcall_end", + contentIndex: index, + toolCall: toolBlock, + partial: output, + }); + } +} +function toFunctionTools(tools) { + return tools.map((tool) => { + const strict = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_10__/* .resolveJsonSchemaStrictSampling */ ._F)(tool, true); + return { + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: stripSymbolKeys((0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_10__/* .getJsonSchemaToolParameters */ .Km)(tool, strict)), + strict: strict ?? false, + }, + }; + }); +} +function stripSymbolKeys(value) { + if (Array.isArray(value)) { + return value.map((item) => stripSymbolKeys(item)); + } + if (value && typeof value === "object") { + const result = {}; + for (const [key, entry] of Object.entries(value)) { + result[key] = stripSymbolKeys(entry); + } + return result; + } + return value; +} +function toChatMessages(messages, supportsImages) { + const result = []; + for (const [index, msg] of messages.entries()) { + if (msg.role === "system") { + const text = index === 0 ? (0,_utils_text_js__WEBPACK_IMPORTED_MODULE_11__/* .getSystemMessageText */ .Y8)(msg) : (0,_utils_text_js__WEBPACK_IMPORTED_MODULE_11__/* .renderSystemMessageUpdate */ .m$)(msg); + if (text.length > 0) + result.push({ role: "system", content: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(text) }); + continue; + } + if (msg.role === "user") { + if (typeof msg.content === "string") { + result.push({ role: "user", content: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(msg.content) }); + continue; + } + const hadImages = msg.content.some((item) => item.type === "image"); + const content = msg.content + .filter((item) => item.type === "text" || supportsImages) + .map((item) => { + if (item.type === "text") + return { type: "text", text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(item.text) }; + return { type: "image_url", imageUrl: `data:${item.mimeType};base64,${item.data}` }; + }); + if (content.length > 0) { + result.push({ role: "user", content }); + continue; + } + if (hadImages && !supportsImages) { + result.push({ role: "user", content: "(image omitted: model does not support images)" }); + } + continue; + } + if (msg.role === "assistant") { + const contentParts = []; + const toolCalls = []; + for (const block of msg.content) { + if (block.type === "text") { + if (block.text.trim().length > 0) { + contentParts.push({ type: "text", text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(block.text) }); + } + continue; + } + if (block.type === "thinking") { + if (block.thinking.trim().length > 0) { + contentParts.push({ + type: "thinking", + thinking: [{ type: "text", text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(block.thinking) }], + }); + } + continue; + } + toolCalls.push({ + id: block.id, + type: "function", + function: { name: block.name, arguments: JSON.stringify(block.arguments || {}) }, + index: 0, + }); + } + const assistantMessage = { role: "assistant", prefix: false }; + if (contentParts.length > 0) + assistantMessage.content = contentParts; + if (toolCalls.length > 0) + assistantMessage.toolCalls = toolCalls; + if (contentParts.length > 0 || toolCalls.length > 0) + result.push(assistantMessage); + continue; + } + const toolContent = []; + const textResult = msg.content + .filter((part) => part.type === "text") + .map((part) => (part.type === "text" ? (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_8__/* .sanitizeSurrogates */ .J)(part.text) : "")) + .join("\n"); + const hasImages = msg.content.some((part) => part.type === "image"); + const toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError); + toolContent.push({ type: "text", text: toolText }); + for (const part of msg.content) { + if (!supportsImages) + continue; + if (part.type !== "image") + continue; + toolContent.push({ + type: "image_url", + imageUrl: `data:${part.mimeType};base64,${part.data}`, + }); + } + result.push({ + role: "tool", + toolCallId: msg.toolCallId, + name: msg.toolName, + content: toolContent, + }); + } + return result; +} +function buildToolResultText(text, hasImages, supportsImages, isError) { + const trimmed = text.trim(); + const errorPrefix = isError ? "[tool error] " : ""; + if (trimmed.length > 0) { + const imageSuffix = hasImages && !supportsImages ? "\n[tool image omitted: model does not support images]" : ""; + return `${errorPrefix}${trimmed}${imageSuffix}`; + } + if (hasImages) { + if (supportsImages) { + return isError ? "[tool error] (see attached image)" : "(see attached image)"; + } + return isError + ? "[tool error] (image omitted: model does not support images)" + : "(image omitted: model does not support images)"; + } + return isError ? "[tool error] (no tool output)" : "(no tool output)"; +} +function usesReasoningEffort(model) { + return (model.id === "mistral-small-2603" || + model.id === "mistral-small-latest" || + model.id.startsWith("mistral-medium-") || + model.id === "zai-glm-5-2"); +} +function usesPromptModeReasoning(model) { + return model.reasoning && !usesReasoningEffort(model); +} +function mapReasoningEffort(model, level) { + return (model.thinkingLevelMap?.[level] ?? "high"); +} +function mapToolChoice(choice) { + if (!choice) + return undefined; + if (choice === "auto" || choice === "none" || choice === "any" || choice === "required") { + return choice; + } + return { + type: "function", + function: { name: choice.function.name }, + }; +} +function mapChatStopReason(reason) { + if (reason === null) + return { stopReason: "stop" }; + switch (reason) { + case "stop": + return { stopReason: "stop" }; + case "length": + case "model_length": + return { stopReason: "length" }; + case "tool_calls": + return { stopReason: "toolUse" }; + case "error": + return { stopReason: "error", errorMessage: "Provider stopped with: error" }; + default: + return { stopReason: "error", errorMessage: `Provider stopped with: ${reason}` }; + } +} +//# sourceMappingURL=mistral-conversations.js.map + +/***/ }), + +/***/ 1901: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ B: () => (/* binding */ shortHash) +/* harmony export */ }); +/** Fast deterministic hash to shorten long strings */ +function shortHash(str) { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < str.length; i++) { + const ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36); +} +//# sourceMappingURL=hash.js.map + +/***/ }), + +/***/ 55278: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ w: () => (/* binding */ getPiUserAgent) +/* harmony export */ }); +function loadNodeOs() { + if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) { + return null; + } + return process.getBuiltinModule?.("node:os") ?? null; +} +// Keep runtime OS loading browser-safe. A top-level runtime import of node:os breaks browser/Vite builds. +const nodeOs = loadNodeOs(); +function getPiUserAgent() { + return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)"; +} +//# sourceMappingURL=pi-user-agent.js.map + +/***/ }) + +}; diff --git a/dist/action/643.index.js b/dist/action/643.index.js new file mode 100644 index 000000000..04b229100 --- /dev/null +++ b/dist/action/643.index.js @@ -0,0 +1,1356 @@ +export const id = 643; +export const ids = [643]; +export const modules = { + +/***/ 46643: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + BashSession: () => (/* binding */ BashSession), + betaAgentToolset20260401: () => (/* binding */ betaAgentToolset20260401), + betaBashTool: () => (/* binding */ betaBashTool), + betaEditTool: () => (/* binding */ betaEditTool), + betaGlobTool: () => (/* binding */ betaGlobTool), + betaGrepTool: () => (/* binding */ betaGrepTool), + betaReadTool: () => (/* binding */ betaReadTool), + betaWriteTool: () => (/* binding */ betaWriteTool), + extractSkillArchive: () => (/* reexport */ extractSkillArchive), + resolvePath: () => (/* binding */ resolvePath), + resolveSkillVersion: () => (/* reexport */ resolveSkillVersion), + setupSkills: () => (/* reexport */ setupSkills) +}); + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/tslib.mjs +var tslib = __webpack_require__(71251); +// EXTERNAL MODULE: external "node:fs/promises" +var promises_ = __webpack_require__(51455); +// EXTERNAL MODULE: external "node:fs" +var external_node_fs_ = __webpack_require__(73024); +// EXTERNAL MODULE: external "node:path" +var external_node_path_ = __webpack_require__(76760); +// EXTERNAL MODULE: external "node:child_process" +var external_node_child_process_ = __webpack_require__(31421); +// EXTERNAL MODULE: external "node:crypto" +var external_node_crypto_ = __webpack_require__(77598); +// EXTERNAL MODULE: external "node:readline" +var external_node_readline_ = __webpack_require__(80481); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/core/error.mjs +var error = __webpack_require__(26911); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs +var ToolError = __webpack_require__(28547); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/index.mjs + 75 modules +var sdk = __webpack_require__(35035); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils.mjs + 1 modules +var utils = __webpack_require__(16360); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs + +// Supported string formats +const SUPPORTED_STRING_FORMATS = new Set([ + 'date-time', + 'time', + 'date', + 'duration', + 'email', + 'hostname', + 'uri', + 'ipv4', + 'ipv6', + 'uuid', +]); +function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +function transform_json_schema_transformJSONSchema(jsonSchema) { + const workingCopy = deepClone(jsonSchema); + return _transformJSONSchema(workingCopy); +} +function _transformJSONSchema(jsonSchema) { + const strictSchema = {}; + const ref = pop(jsonSchema, '$ref'); + if (ref !== undefined) { + strictSchema['$ref'] = ref; + return strictSchema; + } + const defs = pop(jsonSchema, '$defs'); + if (defs !== undefined) { + const strictDefs = {}; + strictSchema['$defs'] = strictDefs; + for (const [name, defSchema] of Object.entries(defs)) { + strictDefs[name] = _transformJSONSchema(defSchema); + } + } + const type = pop(jsonSchema, 'type'); + const anyOf = pop(jsonSchema, 'anyOf'); + const oneOf = pop(jsonSchema, 'oneOf'); + const allOf = pop(jsonSchema, 'allOf'); + if (Array.isArray(anyOf)) { + strictSchema['anyOf'] = anyOf.map((variant) => _transformJSONSchema(variant)); + } + else if (Array.isArray(oneOf)) { + strictSchema['anyOf'] = oneOf.map((variant) => _transformJSONSchema(variant)); + } + else if (Array.isArray(allOf)) { + strictSchema['allOf'] = allOf.map((entry) => _transformJSONSchema(entry)); + } + else { + if (type === undefined) { + throw new Error('JSON schema must have a type defined if anyOf/oneOf/allOf are not used'); + } + strictSchema['type'] = type; + } + const description = pop(jsonSchema, 'description'); + if (description !== undefined) { + strictSchema['description'] = description; + } + const title = pop(jsonSchema, 'title'); + if (title !== undefined) { + strictSchema['title'] = title; + } + if (type === 'object') { + const properties = pop(jsonSchema, 'properties') || {}; + strictSchema['properties'] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ + key, + _transformJSONSchema(propSchema), + ])); + pop(jsonSchema, 'additionalProperties'); + strictSchema['additionalProperties'] = false; + const required = pop(jsonSchema, 'required'); + if (required !== undefined) { + strictSchema['required'] = required; + } + } + else if (type === 'string') { + const format = pop(jsonSchema, 'format'); + if (format !== undefined && SUPPORTED_STRING_FORMATS.has(format)) { + strictSchema['format'] = format; + } + else if (format !== undefined) { + jsonSchema['format'] = format; + } + } + else if (type === 'array') { + const items = pop(jsonSchema, 'items'); + if (items !== undefined) { + strictSchema['items'] = _transformJSONSchema(items); + } + const minItems = pop(jsonSchema, 'minItems'); + if (minItems !== undefined && (minItems === 0 || minItems === 1)) { + strictSchema['minItems'] = minItems; + } + else if (minItems !== undefined) { + jsonSchema['minItems'] = minItems; + } + } + if (Object.keys(jsonSchema).length > 0) { + const existingDescription = strictSchema['description']; + strictSchema['description'] = + (existingDescription ? existingDescription + '\n\n' : '') + + '{' + + Object.entries(jsonSchema) + .map(([key, value]) => `${key}: ${JSON.stringify(value)}`) + .join(', ') + + '}'; + } + return strictSchema; +} +//# sourceMappingURL=transform-json-schema.mjs.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/helpers/beta/json-schema.mjs + + +/** + * Creates a Tool with a provided JSON schema that can be passed + * to the `.toolRunner()` method. The schema is used to automatically validate + * the input arguments for the tool. + */ +function betaTool(options) { + if (options.inputSchema.type !== 'object') { + throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`); + } + return { + type: 'custom', + name: options.name, + input_schema: options.inputSchema, + description: options.description, + run: options.run, + parse: (content) => content, + ...(options.close ? { close: options.close } : {}), + }; +} +/** + * Creates a JSON schema output format object from the given JSON schema. + * If this is passed to the `.parse()` method then the response message will contain a + * `.parsed_output` property that is the result of parsing the content with the given JSON schema. + * + */ +function betaJSONSchemaOutputFormat(jsonSchema, options) { + if (jsonSchema.type !== 'object') { + throw new Error(`JSON schema for tool must be an object, but got ${jsonSchema.type}`); + } + const transform = options?.transform ?? true; + if (transform) { + // todo: doing this is arguably necessary, but it does change the schema the user passed in + // so I'm not sure how we should handle that + jsonSchema = transformJSONSchema(jsonSchema); + } + return { + type: 'json_schema', + schema: { + ...jsonSchema, + }, + parse: (content) => { + try { + return JSON.parse(content); + } + catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } + }, + }; +} +//# sourceMappingURL=json-schema.mjs.map +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs +var promise = __webpack_require__(43846); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/tools/agent-toolset/fs-util.mjs +/** + * Shared, Node-only filesystem helpers for the agent toolset's file tools: + * path confinement (symlink-aware), an atomic write, and language-independent + * error messages. Kept out of `node.ts` so the tool implementations stay focused + * and these helpers can be reused by every file tool. + */ + + + + +/** Mode for directories the file tools create — not world-writable under a 0 umask. */ +const DIR_CREATE_MODE = 0o755; +/** Mode for files the file tools create. */ +const FILE_CREATE_MODE = 0o644; +/** `realpath` `p`, or return `p` unchanged when it cannot be resolved. */ +async function realpathOrSelf(p) { + try { + return await promises_.realpath(p); + } + catch { + return p; + } +} +/** + * Fully resolve `abs`: `realpath` the longest existing ancestor and re-append + * the rest, but never re-append a component that is itself a symlink — read the + * link and continue from its target instead. This handles paths being created + * (write/edit) without letting a symlink leaf (e.g. a dangling one pointing + * outside a confinement root) slip through unresolved. + */ +async function canonicalize(abs) { + const tail = []; + let prefix = abs; + for (;;) { + let real; + try { + real = await promises_.realpath(prefix); + } + catch { + let isLink = false; + try { + isLink = (await promises_.lstat(prefix)).isSymbolicLink(); + } + catch { + /* prefix truly doesn't exist (ENOENT) — fall through and walk up */ + } + if (isLink) { + // Resolve the symlink ourselves and retry; `tail` (the part below it) + // still applies to the link's target. + prefix = external_node_path_.resolve(external_node_path_.dirname(prefix), await promises_.readlink(prefix)); + continue; + } + const parent = external_node_path_.dirname(prefix); + if (parent === prefix) + return abs; // walked past the FS root without a hit + tail.push(external_node_path_.basename(prefix)); + prefix = parent; + continue; + } + return tail.length ? external_node_path_.join(real, ...tail.reverse()) : real; + } +} +/** + * Resolve `p` and confine it to `root`. + * + * Unless `allowOutside` is set, absolute inputs are rejected and the + * **canonical** path is returned — every symlink in `p` (including the leaf, + * even a dangling one) is resolved before the confinement check, and the + * resolved path is what the caller then operates on, so a symlink inside `root` + * that points outside it can neither pass the check nor be followed afterwards. + * + * Residual TOCTOU: a component could still be swapped for a symlink between this + * call and the eventual `fs` operation. Closing that fully needs per-component + * `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; this is why a + * sandbox is still recommended for the toolset as a whole. + */ +async function confineToRoot(root, p, opts) { + const allowOutside = opts?.allowOutside ?? false; + if (external_node_path_.isAbsolute(p)) { + if (!allowOutside) { + throw new ToolError/* ToolError */.v(`absolute path ${JSON.stringify(p)} not permitted`); + } + return external_node_path_.resolve(p); + } + const realRoot = await realpathOrSelf(external_node_path_.resolve(root)); + const abs = external_node_path_.resolve(realRoot, p); + if (allowOutside) + return abs; + const real = await canonicalize(abs); + const rootSep = realRoot.endsWith(external_node_path_.sep) ? realRoot : realRoot + external_node_path_.sep; + if (real !== realRoot && !real.startsWith(rootSep)) { + throw new ToolError/* ToolError */.v(`path ${JSON.stringify(p)} escapes workdir`); + } + return real; +} +/** + * Atomically write `content` to `targetPath`: write a sibling temp file, fsync + * it, then rename over the target. The rename is atomic on most filesystems, so + * a crash mid-write never leaves the target half-written. + */ +async function atomicWriteFile(targetPath, content) { + const dir = external_node_path_.dirname(targetPath); + const tempPath = external_node_path_.join(dir, `.tmp-${process.pid}-${(0,external_node_crypto_.randomUUID)()}`); + let handle; + try { + handle = await promises_.open(tempPath, 'wx', FILE_CREATE_MODE); + await handle.writeFile(content, 'utf-8'); + await handle.sync(); + await handle.close(); + handle = undefined; + await promises_.rename(tempPath, targetPath); + } + catch (err) { + if (handle) + await handle.close().catch(() => { }); + await promises_.unlink(tempPath).catch(() => { }); + throw err; + } +} +/** + * Map a thrown filesystem error to a consistent, language-independent message, + * so the model sees the same wording regardless of the runtime (Node's raw + * `ENOENT: no such file...` text would otherwise leak through). Falls back to + * the raw error message for codes we don't special-case. + */ +function fsErrorMessage(err, file) { + const code = err?.code; + switch (code) { + case 'ENOENT': + return `${file}: no such file or directory`; + case 'EACCES': + case 'EPERM': + return `${file}: permission denied`; + case 'ENOTDIR': + return `${file}: not a directory`; + case 'EISDIR': + return `${file}: is a directory`; + case 'ELOOP': + return `${file}: too many levels of symbolic links`; + case 'ENAMETOOLONG': + return `${file}: file name too long`; + case 'ENOSPC': + return `${file}: no space left on device`; + case 'EMFILE': + case 'ENFILE': + return `${file}: too many open files`; + default: + return `${file}: ${err instanceof Error ? err.message : String(err)}`; + } +} +//# sourceMappingURL=fs-util.mjs.map +// EXTERNAL MODULE: external "node:util" +var external_node_util_ = __webpack_require__(57975); +// EXTERNAL MODULE: external "node:stream" +var external_node_stream_ = __webpack_require__(57075); +// EXTERNAL MODULE: external "node:stream/promises" +var external_node_stream_promises_ = __webpack_require__(46466); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +var utils_log = __webpack_require__(24191); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/tools/agent-toolset/skills.mjs +/** + * Node-only skill plumbing for the agent toolset: downloading a session + * agent's skills into the workdir and extracting the archives. Kept in its own + * file because it is a distinct concern from the tool implementations in + * `node.ts` — distinct enough, and large enough, to review on its own. + */ + + + + + + + + + + +const execFileAsync = (0,external_node_util_.promisify)(external_node_child_process_.execFile); +/** + * Download the session agent's skills into `{ctx.workdir}/skills//`. + * + * No-op (returns a no-op cleanup) unless both `ctx.client` and `ctx.sessionId` + * are set. Looks up the session's resolved agent and, for each skill, fetches + * its files via `client.beta.skills.versions.download` and extracts the archive + * (a zip or tar.* archive) into a directory named after the skill. A failure on + * one skill is logged and does not block the others. Call this before starting + * the session tool runner (e.g. right after the bash session / workdir is + * ready). + * + * Returns a cleanup function that removes the skill directories this call + * created — call it once the work item is done so downloaded skills do not + * accumulate in the workdir across sessions. + */ +async function setupSkills(ctx) { + const { client, sessionId } = ctx; + if (!client || !sessionId) + return async () => { }; + const log = (0,utils_log/* loggerFor */.WG)(client); + const session = await client.beta.sessions.retrieve(sessionId); + const skillsRoot = external_node_path_.resolve(ctx.workdir, 'skills'); + const created = []; + for (const skill of session.agent.skills) { + try { + const versionId = await resolveSkillVersion(client, skill.skill_id, skill.version); + const version = await client.beta.skills.versions.retrieve(versionId, { skill_id: skill.skill_id }); + // The directory is the skill's name, reduced to a single safe path + // component so a hostile name can't escape `skillsRoot`. + let dirname = external_node_path_.basename(version.name.trim()); + if (dirname === '' || dirname === '.' || dirname === '..') + dirname = skill.skill_id; + const dest = external_node_path_.resolve(skillsRoot, dirname); + if (dest !== skillsRoot && !dest.startsWith(skillsRoot + external_node_path_.sep)) { + log.warn('skill name escapes the skills dir; skipping', { + component: 'agent-tool-context', + name: version.name, + }); + continue; + } + const resp = await client.beta.skills.versions.download(versionId, { skill_id: skill.skill_id }); + await promises_.rm(dest, { recursive: true, force: true }); + await promises_.mkdir(dest, { recursive: true, mode: DIR_CREATE_MODE }); + created.push(dest); + await extractSkillArchive(resp, dest); + log.info('downloaded skill', { + component: 'agent-tool-context', + skill_id: skill.skill_id, + version: versionId, + dest, + }); + } + catch (e) { + log.warn('failed to download skill', { + component: 'agent-tool-context', + skill_id: skill.skill_id, + error: String(e), + }); + } + } + return async () => { + for (const dest of created) { + await promises_.rm(dest, { recursive: true, force: true }).catch((e) => { + log.warn('failed to clean up skill', { component: 'agent-tool-context', dest, error: String(e) }); + }); + } + }; +} +/** + * Resolve `version` to the concrete numeric timestamp the + * `/v1/skills/{id}/versions/{version}` endpoints require — `session.agent.skills[].version` + * can be an alias such as `"latest"`, which those endpoints reject. Numeric + * versions pass through unchanged. + */ +async function resolveSkillVersion(client, skillId, version) { + if (/^\d+$/.test(version)) + return version; + let newest; + for await (const v of client.beta.skills.versions.list(skillId)) { + if (/^\d+$/.test(v.version) && (newest === undefined || BigInt(v.version) > BigInt(newest))) { + newest = v.version; + } + } + if (newest === undefined) { + throw new error/* AnthropicError */.pJ(`skill ${JSON.stringify(skillId)} has no concrete version to resolve ${JSON.stringify(version)} against`); + } + return newest; +} +/** Reject archive members that are absolute or contain a `..` component. */ +function assertSafeMemberNames(names) { + for (const raw of names.split('\n')) { + const entry = raw.trim(); + if (!entry) + continue; + if (external_node_path_.isAbsolute(entry) || entry.split(/[\\/]/).includes('..')) { + throw new error/* AnthropicError */.pJ(`refusing to extract unsafe archive member: ${entry}`); + } + } +} +/** + * Reject archives that contain anything other than regular files and + * directories. The type char is the first byte of each `ls`-style line emitted + * by `tar -tvf` / `unzip -Z`: `-` file, `d` dir, `l` symlink, `h` hardlink, + * `b`/`c` device, `p` fifo, `s` socket. A symlink/hardlink member is how an + * archive escapes its extraction dir even when no name contains `..`. + */ +function assertNoSpecialMembers(verboseListing) { + for (const line of verboseListing.split('\n')) { + const type = line.trimStart()[0]; + if (type === 'l' || type === 'h' || type === 'b' || type === 'c' || type === 'p' || type === 's') { + throw new error/* AnthropicError */.pJ('refusing to extract archive with symlink/hardlink/device member'); + } + } +} +/** + * Run an archive CLI (`unzip` for zip archives, `tar` for everything else), + * returning its stdout. Both binaries must be on `PATH`; a missing one would + * otherwise surface as an opaque `ENOENT` spawn failure, so it is turned into a + * clear, specific error naming the missing command. + */ +async function runArchiveTool(cmd, args) { + try { + const { stdout } = await execFileAsync(cmd, args); + return stdout; + } + catch (e) { + if (e != null && typeof e === 'object' && e.code === 'ENOENT') { + throw new error/* AnthropicError */.pJ(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`); + } + throw e; + } +} +/** + * The single top-level directory shared by every entry in a newline-separated + * archive listing, or `''` if entries don't all live under one common + * directory. Skill bundles are packaged wrapped in one directory named after + * the skill (e.g. `pdf/SKILL.md`, `pdf/scripts/...`); the extractor strips it + * so contents land directly in the skill's dir instead of a redundant nested + * `//` level. A flat or multi-root archive yields `''`. + */ +function archiveTopDir(listing) { + let top; + let nested = false; + for (const raw of listing.split('\n')) { + // Drop `.` / empty segments so a `./pdf/...`-style listing (e.g. from + // `tar -C dir .`) is treated the same as `pdf/...`. + const parts = raw + .trim() + .split('/') + .filter((p) => p !== '' && p !== '.'); + if (parts.length === 0) + continue; + const first = parts[0]; + if (top === undefined) + top = first; + else if (first !== top) + return ''; + if (parts.length > 1) + nested = true; + } + return top !== undefined && nested ? top : ''; +} +/** + * Extract a skill download (a zip or tar.* archive) into `dest`. Streams the + * response body straight to a temp file beside `dest` (so the whole archive is + * never buffered in memory — skills can contain large binaries), then shells out + * to `unzip`/`tar` — consistent with the rest of the toolset, which already + * invokes `bash` and `rg`. Both `unzip` and `tar` must be available on `PATH`; a + * missing binary surfaces as a clear error (see {@link runArchiveTool}). Refuses + * any member that would escape `dest` (zip-slip / tar-slip), including + * symlink/hardlink members: skill archives come from the API, but skills can be + * third-party. + * + * The skill bundle's single wrapper directory is stripped: the archive is + * extracted into a staging dir and the wrapper's contents are promoted into + * `dest`, so files land at `dest/SKILL.md` rather than a doubled + * `dest//SKILL.md` (`unzip` has no `--strip-components`, so this is + * done uniformly by staging + promote rather than per-tool flags). + */ +async function extractSkillArchive(resp, dest) { + const tmp = external_node_path_.join(dest, `.skill-archive-${process.pid}-${Date.now()}`); + if (!resp.body) { + throw new error/* AnthropicError */.pJ('skill download response had no body'); + } + await (0,external_node_stream_promises_.pipeline)(external_node_stream_.Readable.fromWeb(resp.body), external_node_fs_.createWriteStream(tmp)); + const stage = external_node_path_.join(external_node_path_.dirname(dest), `.skill-stage-${process.pid}-${Date.now()}`); + try { + // Sniff the first bytes: zip archives start with "PK\x03\x04"; treat + // anything else as a tar.* archive (`tar -xf` autodetects gzip/bzip2/xz). + const head = await readHead(tmp, 4); + const isZip = head.length >= 4 && head[0] === 0x50 && head[1] === 0x4b && head[2] === 0x03 && head[3] === 0x04; + const archiveCmd = isZip ? 'unzip' : 'tar'; + // List first, validate, then extract — `tar`/`unzip` will happily write a + // `../` member (or follow a symlink member) outside `-C`/`-d` otherwise. + const listing = await runArchiveTool(archiveCmd, isZip ? ['-Z1', tmp] : ['-tf', tmp]); + assertSafeMemberNames(listing); + assertNoSpecialMembers(await runArchiveTool(archiveCmd, isZip ? ['-Z', tmp] : ['-tvf', tmp])); + const top = archiveTopDir(listing); + await promises_.mkdir(stage, { recursive: true, mode: DIR_CREATE_MODE }); + await runArchiveTool(archiveCmd, isZip ? ['-oq', tmp, '-d', stage] : ['-xf', tmp, '-C', stage]); + // Promote the wrapper's contents (or the staged tree itself, if the + // archive wasn't wrapped) into the already-created empty `dest`. `stage` + // is a sibling of `dest`, so each rename stays on one filesystem. + const srcRoot = top ? external_node_path_.join(stage, top) : stage; + for (const entry of await promises_.readdir(srcRoot)) { + await promises_.rename(external_node_path_.join(srcRoot, entry), external_node_path_.join(dest, entry)); + } + } + finally { + await promises_.rm(tmp, { force: true }); + await promises_.rm(stage, { recursive: true, force: true }); + } +} +/** Read the first `n` bytes of `file`. */ +async function readHead(file, n) { + const handle = await promises_.open(file, 'r'); + try { + const buf = Buffer.alloc(n); + const { bytesRead } = await handle.read(buf, 0, n, 0); + return buf.subarray(0, bytesRead); + } + finally { + await handle.close(); + } +} +//# sourceMappingURL=skills.mjs.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@anthropic-ai+sdk@0.98.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/tools/agent-toolset/node.mjs +/** + * Node implementation of the `agent_toolset_20260401` tools — `bash`, `read`, + * `write`, `edit`, `glob`, `grep` — plus the workdir/skills + * {@link AgentToolContext}. + * + * This mirrors `@anthropic-ai/sdk/tools/memory/node`: it is the explicit, + * Node-only entry point for these implementations. Importing it pulls in + * `node:child_process`, `node:fs`, etc., so it is kept separate from the rest of + * the SDK — depending on it is an opt-in. + * + * **Node 22+ is required** for this module: the `glob` tool uses the native + * `fs.glob`, added in Node 22. The rest of the SDK still supports Node 18+; only + * the agent toolset has this requirement. + * + * The result of {@link betaAgentToolset20260401} is a plain `BetaRunnableTool[]`; + * hand it to any tool runner — `client.beta.messages.toolRunner({ …, tools })` + * for the Messages API, or `client.beta.sessions.events.toolRunner({ …, tools })` + * for a managed-agents session: + * + * ```ts + * import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; + * + * const tools = betaAgentToolset20260401({ workdir: '/work' }); + * const tools2 = betaAgentToolset20260401({ workdir: '/work' }).filter((t) => t.name !== 'bash'); + * ``` + * + * Trust model: the file tools confine to `workdir` (symlink-aware) and are safe + * without a sandbox; `bash` is unrestricted and should run inside one. See + * {@link AgentToolContext}. + */ +var _BashSession_instances, _BashSession_proc, _BashSession_buf, _BashSession_truncated, _BashSession_closed, _BashSession_waiting, _BashSession_append; + + + + + + + + + + + + + +const BASH_OUTPUT_LIMIT = 100 * 1024; +const BASH_DEFAULT_TIMEOUT_MS = 120000; +const READ_MAX_BYTES = 256 * 1024; +// `edit` reads the whole file before rewriting it, so it carries the same +// OOM/FIFO exposure as `read`. Kept as a symmetric alias for now; the cap value +// (and reject-vs-truncate behaviour) is intentionally a separate knob pending +// validation with the CMA team. +const EDIT_MAX_BYTES = READ_MAX_BYTES; +const GREP_OUTPUT_LIMIT = 100 * 1024; +const GREP_MAX_LINE_LENGTH = 2000; +const GLOB_RESULT_LIMIT = 200; +const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; +const fsGlob = promises_.glob; +/** + * Returns the `agent_toolset_20260401` implementations bound to `ctx`. The + * result is a plain array of `BetaRunnableTool`; filter or extend it before + * handing it to a tool runner: + * + * ```ts + * const tools = [...betaAgentToolset20260401(ctx), myCustomTool]; + * const tools = betaAgentToolset20260401(ctx).filter((t) => t.name !== 'grep'); + * ``` + * + * Concurrency note: `client.beta.sessions.events.toolRunner` dispatches a + * session's tool calls serially (the sessions API delivers one `agent.tool_use` + * at a time). `client.beta.messages.toolRunner` runs a turn's `tool.run` calls + * via `Promise.all`. The toolset below is safe under either model — + * {@link betaBashTool} serializes its persistent shell internally and the FS + * tools are independent per call — but {@link betaEditTool}/{@link betaWriteTool} + * cannot synchronize concurrent writes to the *same* file across processes, so a + * multi-edit turn touching one path is still subject to inherent FS lost-update + * races. Custom tools that close over mutable state should do their own queueing. + */ +function betaAgentToolset20260401(ctx) { + return [ + betaBashTool(ctx), + betaReadTool(ctx), + betaWriteTool(ctx), + betaEditTool(ctx), + betaGlobTool(ctx), + betaGrepTool(ctx), + ]; +} +/** + * Resolve `p` relative to `ctx.workdir`. Unless `unrestrictedPaths` is set, + * absolute inputs are rejected and the **canonical** path is returned — every + * symlink in `p` (including the leaf, even a dangling one) is resolved before + * the workdir check, and the resolved path is what the tool then operates on, so + * a symlink inside the workdir that points outside it can neither pass the check + * nor be followed afterwards. See the trust model on {@link AgentToolContext}. + * + * Residual TOCTOU: a component could still be swapped for a symlink between this + * call and the eventual `fs` operation. Closing that fully needs per-component + * `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; the same + * residual exposure exists in `tools/memory/node` and is why a sandbox is still + * recommended for the toolset as a whole. + */ +function resolvePath(ctx, p) { + return confineToRoot(ctx.workdir, p, { allowOutside: ctx.unrestrictedPaths ?? false }); +} +// ---- bash ---------------------------------------------------------------- +/** + * Build the environment for the spawned bash shell. The runner process holds + * Anthropic credentials in `ANTHROPIC_*` env vars — the API key, the auth token, + * and the per-work session token among them. `bash` runs an unrestricted shell, + * so any command the agent runs could read those straight out of `process.env`; + * strip the whole `ANTHROPIC_*` namespace from the child's environment. + * Everything else (PATH, HOME, locale, …) is passed through unchanged. + * + * Passing an explicit `env` to {@link AgentToolContext} does NOT add to this + * default — it FULLY REPLACES it. The provided mapping becomes the entire bash + * environment verbatim; nothing here is merged in, so callers who want the + * scrubbed process environment plus extras must build that mapping themselves. + */ +function scrubbedShellEnv() { + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key.startsWith('ANTHROPIC_')) + continue; + env[key] = value; + } + return env; +} +/** + * A persistent /bin/bash process. State (cwd, env, background jobs) survives + * across exec() calls. Uses pipes rather than a PTY so input is never echoed. + */ +class BashSession { + constructor(dir, env = scrubbedShellEnv()) { + _BashSession_instances.add(this); + _BashSession_proc.set(this, void 0); + _BashSession_buf.set(this, ''); + _BashSession_truncated.set(this, false); + _BashSession_closed.set(this, false); + // While a command is in flight, the resolver to fire once its sentinel lands + // in `#buf` (or once the shell dies). Event-driven: no polling loop. + _BashSession_waiting.set(this, null); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_proc, external_node_child_process_.spawn('/bin/bash', ['--noprofile', '--norc'], { + cwd: dir, + // `env` is the full base environment (the scrubbed process env by + // default, or the verbatim replacement from `AgentToolContext.env`). + // PS1/PS2/TERM are shell-control settings BashSession always applies so + // the pipe-based sentinel exec parsing works — not part of the + // user-facing environment. + env: { ...env, PS1: '', PS2: '', TERM: 'dumb' }, + stdio: ['pipe', 'pipe', 'pipe'], + detached: true, + }), "f"); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stdout.setEncoding('utf8'); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stderr.setEncoding('utf8'); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stdout.on('data', (d) => (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stderr.on('data', (d) => (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").once('close', () => { + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_closed, true, "f"); + // Wake any in-flight exec so it fails fast instead of waiting for its deadline. + const w = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_waiting, "f"); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_waiting, null, "f"); + w?.resolve(); + }); + } + /** Whether the underlying shell process has exited. */ + get closed() { + return (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_closed, "f"); + } + async exec(command, opts = {}) { + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_closed, "f")) { + throw new error/* AnthropicError */.pJ('bash session terminated'); + } + const timeoutMs = opts.timeoutMs ?? BASH_DEFAULT_TIMEOUT_MS; + const signal = opts.signal; + if (signal?.aborted) { + throw new error/* AnthropicError */.pJ('bash command aborted'); + } + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_buf, '', "f"); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_truncated, false, "f"); + // Per-call nonce so a command that prints a fixed marker can't spoof the + // exit-code framing. The `''` split keeps the literal out of what we write + // to stdin — only the shell's printf reassembles it. + const sentinel = `__ANT_CMD_${external_node_crypto_.randomUUID()}_DONE__`; + const sentinelSplit = `${sentinel.slice(0, 8)}''${sentinel.slice(8)}`; + // &1; printf '\\n${sentinelSplit}%d\\n' $?\n`; + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stdin.write(wrapped); + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").indexOf(sentinel) < 0) { + // Park until the sentinel lands, the deadline passes, the caller aborts, + // or the shell dies — whichever comes first. `#append` (and the `close` + // handler) resolve `sentinelSeen`; the deadline / abort reject. + const { promise: sentinelSeen, resolve } = (0,promise/* promiseWithResolvers */.n)(); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_waiting, { sentinel, resolve }, "f"); + let timer; + let onAbort; + try { + await Promise.race([ + sentinelSeen, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new error/* AnthropicError */.pJ(`bash command timed out after ${timeoutMs}ms`)), timeoutMs); + }), + new Promise((_, reject) => { + if (!signal) + return; + onAbort = () => reject(new error/* AnthropicError */.pJ('bash command aborted')); + signal.addEventListener('abort', onAbort, { once: true }); + }), + ]); + } + finally { + if (timer) + clearTimeout(timer); + if (onAbort && signal) + signal.removeEventListener('abort', onAbort); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_waiting, null, "f"); + } + } + const idx = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").indexOf(sentinel); + if (idx < 0) { + // The shell closed (or was killed) before emitting the sentinel. + throw new error/* AnthropicError */.pJ('bash session terminated'); + } + const tail = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").slice(idx + sentinel.length); + const m = tail.match(/^(-?\d+)/); + const exitCode = m ? parseInt(m[1], 10) : -1; + let out = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").slice(0, idx).replace(ANSI_RE, '').replace(/\n+$/, ''); + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_truncated, "f")) { + out = `[output truncated]\n${out}`; + } + return { output: out, exitCode }; + } + close() { + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_closed, "f")) + return; + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_closed, true, "f"); + const w = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_waiting, "f"); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_waiting, null, "f"); + w?.resolve(); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stdout.destroy(); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stderr.destroy(); + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").stdin.destroy(); + try { + // Negative PID targets the process group so foreground jobs (e.g. a + // hung sleep) die with the shell. + process.kill(-(0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").pid, 'SIGKILL'); + } + catch { + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").kill('SIGKILL'); + } + (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_proc, "f").unref(); + } +} +_BashSession_proc = new WeakMap(), _BashSession_buf = new WeakMap(), _BashSession_truncated = new WeakMap(), _BashSession_closed = new WeakMap(), _BashSession_waiting = new WeakMap(), _BashSession_instances = new WeakSet(), _BashSession_append = function _BashSession_append(d) { + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_buf, (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f") + d, "f"); + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").length > BASH_OUTPUT_LIMIT) { + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_buf, (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").slice((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").length - BASH_OUTPUT_LIMIT), "f"); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_truncated, true, "f"); + } + if ((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_waiting, "f") && (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_buf, "f").indexOf((0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_waiting, "f").sentinel) >= 0) { + const w = (0,tslib/* __classPrivateFieldGet */.g)(this, _BashSession_waiting, "f"); + (0,tslib/* __classPrivateFieldSet */.G)(this, _BashSession_waiting, null, "f"); + w.resolve(); + } +}; +function betaBashTool(ctx) { + let session; + // Concurrent run() callers chain onto this promise so writes to the shared + // shell's stdin can't interleave (which would corrupt the sentinel-match + // exit-code parsing in BashSession.exec). Each call replaces `tail` with a + // promise that resolves only after its own exec settles. + let tail = Promise.resolve(); + return betaTool({ + name: 'bash', + description: 'Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.', + inputSchema: { + type: 'object', + properties: { + command: { type: 'string', description: 'The command to run' }, + restart: { type: 'boolean', description: 'Restart the persistent shell before running' }, + timeout_ms: { type: 'integer', description: 'Per-call timeout in milliseconds' }, + }, + }, + run: async ({ command, restart, timeout_ms }, context) => { + const prev = tail; + const gate = (0,promise/* promiseWithResolvers */.n)(); + tail = gate.promise; + // Swallow prior rejections — earlier callers got their own error path; + // we just need to wait for the shell to be free. + try { + await prev; + } + catch { + // ignore + } + try { + if (restart) { + session?.close(); + session = undefined; + } + if (!command) { + if (restart) + return 'bash session restarted'; + throw new ToolError/* ToolError */.v('bash: command is required'); + } + session ?? (session = new BashSession(ctx.workdir, ctx.env)); + try { + const { output, exitCode } = await session.exec(command, { + timeoutMs: timeout_ms ?? BASH_DEFAULT_TIMEOUT_MS, + signal: context?.signal, + }); + if (exitCode !== 0) + throw new ToolError/* ToolError */.v(output || `exit ${exitCode}`); + return output; + } + catch (e) { + if (e instanceof ToolError/* ToolError */.v) + throw e; + // Timeout, abort, or terminated: the still-running command will emit + // a stale sentinel, so discard this session and let the next call + // start fresh. + session.close(); + session = undefined; + throw new ToolError/* ToolError */.v(`bash: ${e instanceof Error ? e.message : String(e)}`); + } + } + finally { + gate.resolve(); + } + }, + close: () => { + session?.close(); + session = undefined; + }, + }); +} +// ---- fs ------------------------------------------------------------------ +function betaReadTool(ctx) { + return betaTool({ + name: 'read', + description: 'Read a UTF-8 text file relative to the workdir.', + inputSchema: { + type: 'object', + properties: { + file_path: { type: 'string' }, + view_range: { + type: 'array', + items: { type: 'integer' }, + description: '[start_line, end_line] 1-indexed inclusive', + }, + }, + required: ['file_path'], + }, + run: async ({ file_path, view_range }) => { + if (!file_path) + throw new ToolError/* ToolError */.v('read: file_path is required'); + const abs = await resolvePath(ctx, file_path); + let data; + try { + // stat() before any open(): the size cap stops a multi-GB file from + // OOM'ing the runner, and isFile() rejects FIFOs/devices/dirs without + // opening them (open() on an unconnected FIFO blocks indefinitely). + const st = await promises_.stat(abs); + if (!st.isFile()) { + throw new ToolError/* ToolError */.v(`read: ${file_path} is not a regular file`); + } + if (st.size > READ_MAX_BYTES) { + throw new ToolError/* ToolError */.v(`read: ${file_path} is ${st.size} bytes, exceeds ${READ_MAX_BYTES}-byte limit. ` + + 'Use bash (head/tail/sed) to read a slice.'); + } + data = await promises_.readFile(abs, 'utf8'); + } + catch (e) { + if (e instanceof ToolError/* ToolError */.v) + throw e; + throw new ToolError/* ToolError */.v(`read: ${fsErrorMessage(e, file_path)}`); + } + if (!view_range) + return data; + if (view_range.length !== 2) + throw new ToolError/* ToolError */.v('read: view_range must be [start_line, end_line]'); + const [startLine, endLine] = view_range; + const lines = data.split('\n'); + const start = Math.max(0, startLine - 1); + const end = endLine > 0 ? endLine : lines.length; + return lines.slice(start, end).join('\n'); + }, + }); +} +function betaWriteTool(ctx) { + return betaTool({ + name: 'write', + description: 'Write a UTF-8 text file relative to the workdir, creating parent directories as needed.', + inputSchema: { + type: 'object', + properties: { file_path: { type: 'string' }, content: { type: 'string' } }, + required: ['file_path', 'content'], + }, + run: async ({ file_path, content }) => { + if (!file_path) + throw new ToolError/* ToolError */.v('write: file_path is required'); + const abs = await resolvePath(ctx, file_path); + try { + await promises_.mkdir(external_node_path_.dirname(abs), { recursive: true, mode: DIR_CREATE_MODE }); + await atomicWriteFile(abs, content ?? ''); + } + catch (e) { + throw new ToolError/* ToolError */.v(`write: ${fsErrorMessage(e, file_path)}`); + } + return `wrote ${Buffer.byteLength(content ?? '')} bytes to ${file_path}`; + }, + }); +} +function betaEditTool(ctx) { + return betaTool({ + name: 'edit', + description: 'Replace old_string with new_string in a file. old_string must be unique unless replace_all.', + inputSchema: { + type: 'object', + properties: { + file_path: { type: 'string' }, + old_string: { type: 'string' }, + new_string: { type: 'string' }, + replace_all: { type: 'boolean' }, + }, + required: ['file_path', 'old_string', 'new_string'], + }, + run: async ({ file_path, old_string, new_string, replace_all }) => { + if (!file_path) + throw new ToolError/* ToolError */.v('edit: file_path is required'); + if (!old_string) + throw new ToolError/* ToolError */.v('edit: old_string is required'); + const abs = await resolvePath(ctx, file_path); + let data; + try { + // stat() before any open() — same guard as `read`: the size cap stops a + // multi-GB file from OOM'ing the runner, and isFile() rejects + // FIFOs/devices/dirs without opening them (open() on an unconnected FIFO + // blocks indefinitely). The edit path is model-controlled, so it needs + // the same bound `read` already has. + const st = await promises_.stat(abs); + if (!st.isFile()) { + throw new ToolError/* ToolError */.v(`edit: ${file_path} is not a regular file`); + } + if (st.size > EDIT_MAX_BYTES) { + throw new ToolError/* ToolError */.v(`edit: ${file_path} is ${st.size} bytes, exceeds ${EDIT_MAX_BYTES}-byte limit. ` + + 'Use bash (sed/awk) to edit a large file.'); + } + data = await promises_.readFile(abs, 'utf8'); + } + catch (e) { + if (e instanceof ToolError/* ToolError */.v) + throw e; + throw new ToolError/* ToolError */.v(`edit: ${fsErrorMessage(e, file_path)}`); + } + const count = data.split(old_string).length - 1; + if (count === 0) + throw new ToolError/* ToolError */.v(`edit: old_string not found in ${file_path}`); + let updated; + if (replace_all) { + updated = data.split(old_string).join(new_string); + } + else { + if (count > 1) + throw new ToolError/* ToolError */.v(`edit: old_string appears ${count} times in ${file_path} (must be unique)`); + // Callback form so `$&`/`$1`/`` $` `` in new_string are inserted + // literally instead of expanded as replacement patterns. + updated = data.replace(old_string, () => new_string); + } + try { + await atomicWriteFile(abs, updated); + } + catch (e) { + throw new ToolError/* ToolError */.v(`edit: write: ${fsErrorMessage(e, file_path)}`); + } + return `edited ${file_path} (${replace_all ? count : 1} replacement(s))`; + }, + }); +} +// ---- search -------------------------------------------------------------- +function betaGlobTool(ctx) { + return betaTool({ + name: 'glob', + description: 'Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.', + inputSchema: { + type: 'object', + properties: { + pattern: { type: 'string' }, + path: { type: 'string', description: 'Directory to search in. Defaults to the workdir.' }, + }, + required: ['pattern'], + }, + run: async ({ pattern, path: searchPath }) => { + if (!pattern) + throw new ToolError/* ToolError */.v('glob: pattern is required'); + let root = external_node_path_.resolve(ctx.workdir); + let pat = pattern; + if (external_node_path_.isAbsolute(pattern)) { + if (!ctx.unrestrictedPaths) + throw new ToolError/* ToolError */.v('glob: absolute pattern not permitted'); + root = external_node_path_.parse(pattern).root; + pat = external_node_path_.relative(root, pattern); + } + else if (searchPath) { + root = await resolvePath(ctx, searchPath); + } + // A `..` in the *pattern itself* (e.g. `../../*`) walks `fs.glob` out of + // the search root — this is separate from the `searchPath` confinement + // above, which only covers the path argument. Reject it outright when the + // toolset is confined. + if (!ctx.unrestrictedPaths && pat.split(/[\\/]/).includes('..')) { + throw new ToolError/* ToolError */.v('glob: ".." is not permitted in the pattern'); + } + const matches = []; + try { + // Native `fs.glob` (Node 22+). `exclude` prunes the noisy dirs the + // legacy walker skipped; only regular files are collected. + for await (const entry of fsGlob(pat, { + cwd: root, + withFileTypes: true, + exclude: (d) => d.name === '.git' || d.name === 'node_modules', + })) { + if (!entry.isFile()) + continue; + const full = external_node_path_.join(entry.parentPath, entry.name); + // Defense in depth: drop any match that resolved outside the search + // root (e.g. via a symlinked directory in the tree) when confined. + if (!ctx.unrestrictedPaths && !isWithin(root, full)) + continue; + let mtime = 0; + try { + mtime = (await promises_.stat(full)).mtimeMs; + } + catch { + // unreadable — keep it in the list with mtime 0 + } + matches.push({ path: full, mtime }); + } + } + catch (e) { + throw new ToolError/* ToolError */.v(`glob: ${e instanceof Error ? e.message : String(e)}`); + } + if (matches.length === 0) + return 'no matches'; + matches.sort((a, b) => b.mtime - a.mtime); + return matches + .slice(0, GLOB_RESULT_LIMIT) + .map((m) => m.path) + .join('\n'); + }, + }); +} +function betaGrepTool(ctx) { + return betaTool({ + name: 'grep', + description: 'Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.', + inputSchema: { + type: 'object', + properties: { pattern: { type: 'string' }, path: { type: 'string' } }, + required: ['pattern'], + }, + run: async ({ pattern, path: p }, context) => { + if (!pattern) + throw new ToolError/* ToolError */.v('grep: pattern is required'); + let searchPath = external_node_path_.resolve(ctx.workdir); + if (p) + searchPath = await resolvePath(ctx, p); + const rg = await findRg(); + return rg ? + runRipgrep(rg, pattern, searchPath, context?.signal) + : runWalkGrep(pattern, searchPath, context?.signal); + }, + }); +} +function runRipgrep(rg, pattern, searchPath, signal) { + return new Promise((resolve, reject) => { + const proc = external_node_child_process_.spawn(rg, ['-n', '--no-heading', '-e', pattern, '--', searchPath], { + ...(signal ? { signal } : {}), + }); + let out = ''; + let errOut = ''; + let truncated = false; + proc.stdout.on('data', (d) => { + if (truncated) + return; + out += d; + if (out.length > GREP_OUTPUT_LIMIT) { + truncated = true; + out = out.slice(0, GREP_OUTPUT_LIMIT); + proc.kill('SIGKILL'); + } + }); + proc.stderr.on('data', (d) => (errOut += d)); + proc.on('close', (code) => { + if (signal?.aborted) + return reject(new ToolError/* ToolError */.v('grep: aborted')); + if (truncated) + return resolve(out + `\n[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); + if (code === 0) + return resolve(out); + if (code === 1) + return resolve('no matches'); + reject(new ToolError/* ToolError */.v(`grep: rg failed: ${errOut || `exit ${code}`}`)); + }); + proc.on('error', (e) => { + if (signal?.aborted) + return reject(new ToolError/* ToolError */.v('grep: aborted')); + reject(new ToolError/* ToolError */.v(`grep: rg failed: ${e.message}`)); + }); + }); +} +async function runWalkGrep(pattern, root, signal) { + let re; + try { + re = new RegExp(pattern); + } + catch (e) { + throw new ToolError/* ToolError */.v(`grep: invalid regex: ${e instanceof Error ? e.message : String(e)}`); + } + const hits = []; + let budget = GREP_OUTPUT_LIMIT; + const push = (line) => { + budget -= line.length + 1; + if (budget < 0) { + hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); + return false; + } + hits.push(line); + return true; + }; + const stat = await promises_.stat(root).catch(() => null); + if (stat?.isFile()) { + await grepFile(root, re, push); + } + else { + await walk(root, '', (rel) => grepFile(external_node_path_.join(root, rel), re, push), signal); + } + if (signal?.aborted) + throw new ToolError/* ToolError */.v('grep: aborted'); + if (hits.length === 0) + return 'no matches'; + return hits.join('\n'); +} +async function grepFile(file, re, push) { + const stream = external_node_fs_.createReadStream(file, { encoding: 'utf8' }); + const rl = external_node_readline_.createInterface({ input: stream, crlfDelay: Infinity }); + let i = 0; + try { + for await (const line of rl) { + i++; + // Cap line length: `pattern` is model-supplied and JS regexes backtrack, + // so a pathological pattern against a very long line is a ReDoS. + if (line.length > GREP_MAX_LINE_LENGTH) + continue; + if (re.test(line) && !push(`${file}:${i}:${line}`)) + return false; + } + } + catch { + // unreadable / binary + } + finally { + stream.destroy(); + } + return true; +} +// ---- utils --------------------------------------------------------------- +/** True when `p` is `root` itself or lexically contained within it. */ +function isWithin(root, p) { + const rel = external_node_path_.relative(root, p); + return rel === '' || (!rel.startsWith('..' + external_node_path_.sep) && rel !== '..' && !external_node_path_.isAbsolute(rel)); +} +const WALK_MAX_DEPTH = 40; +const WALK_MAX_ENTRIES = 50000; +/** + * Bounded recursive walk. `fn` may return `false` to abort. Only real + * directories are descended into and only real files are handed to `fn` — + * symlinks (and devices/fifos/sockets) are skipped entirely so a symlink inside + * the root cannot be followed out of it. + */ +async function walk(root, rel, fn, signal) { + let remaining = WALK_MAX_ENTRIES; + async function inner(rel, depth) { + if (depth > WALK_MAX_DEPTH) + return true; + if (signal?.aborted) + return false; + let entries; + try { + entries = await promises_.readdir(external_node_path_.join(root, rel), { withFileTypes: true }); + } + catch { + return true; + } + for (const e of entries) { + if (e.name === '.git' || e.name === 'node_modules') + continue; + if (remaining-- <= 0) + return false; + if (signal?.aborted) + return false; + const childRel = rel ? external_node_path_.join(rel, e.name) : e.name; + if (e.isDirectory()) { + if (!(await inner(childRel, depth + 1))) + return false; + } + else if (e.isFile()) { + if ((await fn(childRel)) === false) + return false; + } + // Symlinks, devices, fifos and sockets are intentionally skipped. + } + return true; + } + await inner(rel, 0); +} +async function findRg() { + const dirs = (process.env['PATH'] ?? '').split(external_node_path_.delimiter); + for (const d of dirs) { + const candidate = external_node_path_.join(d, 'rg'); + try { + await promises_.access(candidate, external_node_fs_.constants.X_OK); + return candidate; + } + catch { + // not here + } + } + return null; +} +//# sourceMappingURL=node.mjs.map + +/***/ }) + +}; diff --git a/dist/action/663.index.js b/dist/action/663.index.js new file mode 100644 index 000000000..798416c55 --- /dev/null +++ b/dist/action/663.index.js @@ -0,0 +1,3912 @@ +export const id = 663; +export const ids = [663,834,453]; +export const modules = { + +/***/ 14420: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 14420; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 43502: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 43502; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 56834: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 56834; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 25353: +/***/ ((module) => { + +function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(() => { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = () => ([]); +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = 25353; +module.exports = webpackEmptyAsyncContext; + +/***/ }), + +/***/ 98229: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $d: () => (/* binding */ isRetryableError), +/* harmony export */ $w: () => (/* binding */ sanitizeErrorMessage), +/* harmony export */ Aq: () => (/* binding */ WardenAuthenticationError), +/* harmony export */ HD: () => (/* binding */ isAuthenticationError), +/* harmony export */ Ip: () => (/* binding */ isAuthenticationErrorMessage), +/* harmony export */ Ro: () => (/* binding */ humanizeProviderError), +/* harmony export */ bk: () => (/* binding */ mapExtractionErrorCode), +/* harmony export */ cy: () => (/* binding */ SkillRunnerError), +/* harmony export */ fe: () => (/* binding */ classifyError), +/* harmony export */ mu: () => (/* binding */ isSubprocessError) +/* harmony export */ }); +/* harmony import */ var _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(35035); +/* harmony import */ var _runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85286); + + +class SkillRunnerError extends Error { + /** Optional classification so callers skip message-sniffing. */ + code; + /** Sanitized provider diagnostics safe to attach to telemetry. */ + providerContext; + /** Per-hunk diagnostics safe to surface in execution failure reports. */ + hunkFailures; + constructor(message, options) { + super(message, options); + this.name = 'SkillRunnerError'; + if (options?.code) + this.code = options.code; + if (options?.providerContext) + this.providerContext = options.providerContext; + if (options?.hunkFailures) + this.hunkFailures = options.hunkFailures; + } +} +const SENSITIVE_VALUE = '[redacted]'; +/** + * Remove likely credential material before an error message is surfaced through + * logs, callbacks, reports, or telemetry. + */ +function sanitizeErrorMessage(message) { + return message + .replace(/\b(sk-ant-[A-Za-z0-9_-]+)/g, SENSITIVE_VALUE) + .replace(/\b(sk-[A-Za-z0-9_-]{16,})\b/g, SENSITIVE_VALUE) + .replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${SENSITIVE_VALUE}`) + .replace(/\b(authorization)(\s*[:=]\s*)(["']?)(Bearer\s+)?[^"',\s)]+/gi, (_match, key, separator, quote, bearer) => `${key}${separator}${quote}${bearer ?? ''}${SENSITIVE_VALUE}`) + .replace(/\b(api[_-]?key|x-api-key|auth[_-]?token|oauth[_-]?token|token)(\s*[:=]\s*)(["']?)[^"',\s)]+/gi, `$1$2$3${SENSITIVE_VALUE}`); +} +/** Patterns that indicate an authentication failure */ +const AUTH_ERROR_PATTERNS = [ + 'authentication', + 'unauthorized', + 'invalid.*api.*key', + 'invalid.*key', + 'not.*logged.*in', + 'login.*required', + 'api key', +]; +/** + * Check if an error message indicates an authentication failure. + */ +function isAuthenticationErrorMessage(message) { + return AUTH_ERROR_PATTERNS.some((pattern) => new RegExp(pattern, 'i').test(message)); +} +/** User-friendly error message for authentication failures (Claude runtime) */ +const CLAUDE_AUTH_GUIDANCE = ` + claude login # Use local Claude Code auth + export WARDEN_ANTHROPIC_API_KEY=sk-... # Or use API key + +https://console.anthropic.com/ for API keys`; +/** User-friendly error message for authentication failures (Pi runtime) */ +const PI_AUTH_GUIDANCE = ` + export WARDEN_MODEL=provider/model-id # e.g. openai/gpt-5.5 + export WARDEN_{PROVIDER}_API_KEY=... # WARDEN-prefixed key for that provider + +See https://warden.sentry.dev/config/models for provider selectors and credential names.`; +/** IPC/subprocess failure error codes (EPIPE, ECONNRESET, etc.) */ +const IPC_ERROR_CODES = ['EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ENOTCONN']; +/** + * Check if an error is an IPC/subprocess failure. + * These occur when the Claude Code subprocess can't communicate (e.g., sandbox restrictions). + */ +function isSubprocessError(error) { + if (!(error instanceof Error)) + return false; + // Check error.code property (Node.js ErrnoException) first + const errorCode = error.code; + if (errorCode && IPC_ERROR_CODES.includes(errorCode)) + return true; + // Fallback: check the original error message only, not appended stderr content. + // executeQuery appends "\nClaude Code stderr: ..." which could contain IPC codes + // from debug output, causing false positives. + const stderrIdx = error.message.indexOf('\nClaude Code stderr:'); + const message = stderrIdx >= 0 ? error.message.slice(0, stderrIdx) : error.message; + return IPC_ERROR_CODES.some((code) => message.includes(code)); +} +class WardenAuthenticationError extends Error { + constructor(sdkError, options) { + const { cause, runtime } = options ?? {}; + const guidance = runtime === 'pi' ? PI_AUTH_GUIDANCE : CLAUDE_AUTH_GUIDANCE; + const message = sdkError + ? `Authentication failed: ${sdkError}\n${guidance}` + : `Authentication required.${guidance}`; + super(message, { cause }); + this.name = 'WardenAuthenticationError'; + } +} +/** + * Check if an error is retryable. + * Retries on: rate limits (429), server errors (5xx), connection errors, timeouts. + */ +function isRetryableError(error) { + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .RateLimitError */ .OE) + return true; + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .InternalServerError */ .PO) + return true; + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .APIConnectionError */ .xX) + return true; + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .APIConnectionTimeoutError */ .qA) + return true; + // Check for generic APIError with retryable status codes + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .APIError */ .LG) { + const status = error.status; + if (status === 429) + return true; + if (status !== undefined && status >= 500 && status < 600) + return true; + } + return false; +} +/** + * Check if an error indicates an unavailable provider/runtime. + * These failures can recover later, but repeated failures should stop the run. + */ +function isProviderUnavailableError(error) { + if (isRetryableError(error)) + return true; + const message = error instanceof Error ? error.message : String(error); + return (/Claude Code process exited with code \d+/i.test(message) || + /Claude Code stderr:[\s\S]*\b(overloaded|rate limit|timed? out|timeout|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT)\b/i.test(message)); +} +/** + * Check if an error is an authentication failure. + * These require user action (login or API key) and should not be retried. + */ +function isAuthenticationError(error) { + if (error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .APIError */ .LG && error.status === 401) { + return true; + } + // Check error message for common auth failure patterns + const message = error instanceof Error ? error.message : String(error); + return isAuthenticationErrorMessage(message); +} +/** Classify an unknown error into a stable ErrorCode + message. */ +function classifyError(error) { + const message = error instanceof Error ? error.message : String(error ?? 'unknown error'); + if (error instanceof WardenAuthenticationError) { + return { code: 'auth_failed', message }; + } + if (error instanceof SkillRunnerError && error.code) { + return { code: error.code, message }; + } + if (error instanceof _runtimes_model_selectors_js__WEBPACK_IMPORTED_MODULE_1__/* .InvalidPiModelSelectorError */ .n1) { + return { code: 'invalid_model_selector', message }; + } + if (isSubprocessError(error)) { + return { code: 'subprocess_failure', message }; + } + if (isAuthenticationError(error)) { + return { code: 'auth_failed', message }; + } + if (isProviderUnavailableError(error)) { + return { code: 'provider_unavailable', message: humanizeProviderError(error) }; + } + if (error instanceof Error && error.name === 'AbortError') { + return { code: 'aborted', message }; + } + if (/\baborted\b/i.test(message)) { + return { code: 'aborted', message }; + } + return { code: 'unknown', message }; +} +/** Human-friendly messages for known Anthropic API error types. */ +const ANTHROPIC_ERROR_LABELS = { + overloaded_error: 'Anthropic is overloaded — try again later.', + rate_limit_error: 'Anthropic rate limit reached — try again later.', + api_error: 'Anthropic API error — try again later.', + authentication_error: 'Anthropic authentication error.', +}; +function humanizeProviderErrorPayload(payload) { + const body = payload && typeof payload === 'object' ? payload : undefined; + const rawError = body?.error ?? body; + const error = rawError && typeof rawError === 'object' ? rawError : undefined; + const type = typeof error?.type === 'string' ? error.type : undefined; + const message = typeof error?.message === 'string' ? error.message : undefined; + return type ? ANTHROPIC_ERROR_LABELS[type] ?? message : message; +} +/** + * Extract a human-readable summary from a raw provider error. + * + * Structured Anthropic error bodies are preferred so summaries are based on the + * provider error type. String errors fall back to parsing embedded JSON + * before returning the text prefix or original message. + */ +function humanizeProviderError(error) { + const payload = error instanceof _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* .APIError */ .LG + ? error.error + : error; + const structuredSummary = humanizeProviderErrorPayload(payload); + if (structuredSummary) + return structuredSummary; + const message = error instanceof Error ? error.message : String(error); + const jsonStart = message.indexOf('{'); + if (jsonStart < 0) + return message; + try { + const jsonSummary = humanizeProviderErrorPayload(JSON.parse(message.slice(jsonStart))); + if (jsonSummary) + return jsonSummary; + } + catch { + // Ignore malformed embedded JSON and fall back to the readable prefix. + } + return message.slice(0, jsonStart).replace(/[:\s]+$/, '').trim() || message; +} +/** Map an internal extract.ts error string to a stable public ErrorCode. */ +function mapExtractionErrorCode(raw) { + if (!raw) + return 'unknown'; + if (raw === 'invalid_json') + return 'extraction_invalid_json'; + if (raw === 'unbalanced_json') + return 'extraction_unbalanced_json'; + if (raw === 'no_findings_json' || raw === 'no_findings_to_extract') + return 'extraction_no_findings_json'; + if (raw === 'missing_findings_key') + return 'extraction_missing_findings_key'; + if (raw === 'findings_not_array') + return 'extraction_findings_not_array'; + if (raw === 'no_api_key_for_fallback') + return 'extraction_no_api_key'; + if (raw.startsWith('llm_extraction_failed')) { + if (/timeout|timed out/i.test(raw)) + return 'extraction_llm_timeout'; + return 'extraction_llm_failed'; + } + return 'unknown'; +} + + +/***/ }), + +/***/ 39026: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ eg: () => (/* binding */ extractJson), +/* harmony export */ tQ: () => (/* binding */ callHaiku), +/* harmony export */ u2: () => (/* binding */ callHaikuWithTools) +/* harmony export */ }); +/* unused harmony exports HAIKU_MODEL, DEFAULT_AUXILIARY_MAX_RETRIES, setGenAiResponseAttrs */ +/* harmony import */ var _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(35035); +/* harmony import */ var _sentry_trace_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(68016); +/* harmony import */ var _pricing_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(64602); +/* harmony import */ var _usage_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(44759); +/* harmony import */ var _otel_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(85884); + + + + + +const HAIKU_MODEL = 'claude-haiku-4-5'; +const DEFAULT_AUXILIARY_MAX_RETRIES = 5; +const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_TOKENS = 4096; +/** + * Set standard gen_ai response attributes on a Sentry span. + * + * Follows the same token accounting as analyze.ts: gen_ai.usage.input_tokens + * is the total (non-cached + cache_read + cache_creation), with cache fields + * as subsets. + */ +function setGenAiResponseAttrs(span, usage, stopReason, responseText) { + const cacheRead = usage.cache_read_input_tokens ?? 0; + const rawCacheWrite = usage.cache_creation_input_tokens ?? 0; + const tieredCacheWrite = (usage.cache_creation?.ephemeral_5m_input_tokens ?? 0) + + (usage.cache_creation?.ephemeral_1h_input_tokens ?? 0); + const cacheWrite = Math.max(rawCacheWrite, tieredCacheWrite); + (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .setGenAiUsageAttrs */ .qk)(span, { + inputTokens: usage.input_tokens + cacheRead + cacheWrite, + outputTokens: usage.output_tokens, + cacheReadInputTokens: cacheRead, + cacheCreationInputTokens: cacheWrite, + cacheCreation5mInputTokens: usage.cache_creation?.ephemeral_5m_input_tokens ?? cacheWrite, + cacheCreation1hInputTokens: usage.cache_creation?.ephemeral_1h_input_tokens ?? 0, + webSearchRequests: 0, + costUSD: 0, + }); + if (stopReason) { + span.setAttribute('gen_ai.response.finish_reasons', [stopReason]); + } + if (responseText !== undefined) { + (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .setGenAiOutputMessagesAttr */ .hX)(span, responseText, stopReason); + } +} +/** + * Extract the first JSON object or array from LLM text. + * Handles markdown code fences and prose before/after JSON. + */ +function extractJson(text) { + const stripped = text.trim(); + // Try parsing the whole thing first (common case: clean JSON output) + try { + JSON.parse(stripped); + return stripped; + } + catch { + // Fall through to extraction + } + // Try every object/array opener. This handles prose, fenced JSON, orphaned + // prefill, and markdown fences embedded inside JSON string values. + for (let start = 0; start < stripped.length; start++) { + const opener = stripped[start]; + if (opener !== '{' && opener !== '[') { + continue; + } + const stack = [opener === '{' ? '}' : ']']; + let inString = false; + let escape = false; + for (let i = start + 1; i < stripped.length; i++) { + const char = stripped[i]; + if (escape) { + escape = false; + continue; + } + if (char === '\\' && inString) { + escape = true; + continue; + } + if (char === '"') { + inString = !inString; + continue; + } + if (inString) { + continue; + } + if (char === '{') { + stack.push('}'); + continue; + } + if (char === '[') { + stack.push(']'); + continue; + } + const expectedCloser = stack[stack.length - 1]; + if (char === '}' || char === ']') { + if (char !== expectedCloser) { + break; + } + stack.pop(); + if (stack.length === 0) { + const candidate = stripped.slice(start, i + 1); + try { + JSON.parse(candidate); + return candidate; + } + catch { + break; + } + } + } + } + } + return null; +} +/** + * Infer prefill character from schema type to force JSON output. + */ +function inferPrefill(schema) { + // Check for ZodObject (name === 'ZodObject') + if ('_def' in schema && schema._def.typeName === 'ZodObject') + return '{'; + // Check for ZodArray + if ('_def' in schema && schema._def.typeName === 'ZodArray') + return '['; + return undefined; +} +/** + * Single-turn structured Haiku call. + * Auto-prefills based on Zod schema type, extracts JSON, validates with Zod. + */ +async function callHaiku(options) { + const { apiKey, prompt, schema, agentName, task, model = HAIKU_MODEL, maxTokens = DEFAULT_MAX_TOKENS, timeout = DEFAULT_TIMEOUT_MS, maxRetries = DEFAULT_AUXILIARY_MAX_RETRIES } = options; + return (0,_sentry_trace_js__WEBPACK_IMPORTED_MODULE_1__/* .startTracedSpan */ .wZ)({ + op: 'gen_ai.chat', + name: (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .genAiSpanName */ .kj)('chat', model), + attributes: { + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': 'anthropic', + ...(agentName ? { 'gen_ai.agent.name': agentName } : {}), + ...(task ? { 'warden.ai.task': task } : {}), + 'gen_ai.request.model': model, + 'gen_ai.request.max_tokens': maxTokens, + 'gen_ai.output.type': 'json', + }, + }, async (span) => { + const client = new _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay({ apiKey, timeout, maxRetries }); + const prefill = inferPrefill(schema); + const messages = [ + { role: 'user', content: prompt }, + ]; + if (prefill) { + messages.push({ role: 'assistant', content: prefill }); + } + (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .setGenAiInputMessagesAttr */ .uQ)(span, messages); + try { + const response = await client.messages.create({ + model, + max_tokens: maxTokens, + messages, + }); + const usage = (0,_pricing_js__WEBPACK_IMPORTED_MODULE_2__/* .apiUsageToStats */ .Y4)(model, response.usage); + const content = response.content[0]; + if (!content || content.type !== 'text') { + setGenAiResponseAttrs(span, response.usage, response.stop_reason); + span.setAttribute('error.type', 'empty_response'); + return { success: false, error: 'Empty response from model', usage }; + } + let fullText = content.text; + if (prefill) { + fullText = prefill + fullText; + } + setGenAiResponseAttrs(span, response.usage, response.stop_reason, fullText); + const jsonStr = extractJson(fullText); + if (!jsonStr) { + span.setAttribute('error.type', 'invalid_json'); + return { success: false, error: 'No JSON found in response', usage }; + } + const parsed = JSON.parse(jsonStr); + const validated = schema.safeParse(parsed); + if (!validated.success) { + span.setAttribute('error.type', 'validation_error'); + return { success: false, error: `Validation failed: ${validated.error.message}`, usage }; + } + return { success: true, data: validated.data, usage }; + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + span.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + return { success: false, error: message, usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .emptyUsage */ .ly)() }; + } + }); +} +/** + * Multi-turn Haiku call with tool use loop. + * Iterates tool calls until the model produces a final text response. + * Accumulates usage across all iterations. + * + * Telemetry mirrors an agent run: the outer span describes the local + * orchestration, each Anthropic API call gets its own `gen_ai.chat` span, and + * every application-executed tool call is recorded as `gen_ai.execute_tool`. + */ +async function callHaikuWithTools(options) { + const { apiKey, prompt, schema, tools, executeTool, agentName, task, model = HAIKU_MODEL, maxTokens = DEFAULT_MAX_TOKENS, maxIterations = 5, timeout = DEFAULT_TIMEOUT_MS, maxRetries = DEFAULT_AUXILIARY_MAX_RETRIES, } = options; + return (0,_sentry_trace_js__WEBPACK_IMPORTED_MODULE_1__/* .startTracedSpan */ .wZ)({ + op: 'gen_ai.invoke_agent', + name: (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .genAiSpanName */ .kj)('invoke_agent', agentName), + attributes: { + 'gen_ai.operation.name': 'invoke_agent', + 'gen_ai.provider.name': 'anthropic', + ...(agentName ? { 'gen_ai.agent.name': agentName } : {}), + ...(task ? { 'warden.ai.task': task } : {}), + 'gen_ai.request.model': model, + 'gen_ai.request.max_tokens': maxTokens, + 'gen_ai.output.type': 'json', + }, + }, async (span) => { + const client = new _anthropic_ai_sdk__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay({ apiKey, timeout, maxRetries }); + const toolDescriptions = new Map(tools + .map((tool) => [tool.name, tool.description]) + .filter((entry) => typeof entry[1] === 'string' && entry[1].length > 0)); + // No prefill for tool-use loops: prefill biases the model to output JSON + // immediately instead of calling tools to gather information first. + const messages = [ + { role: 'user', content: prompt }, + ]; + const usages = []; + // Accumulate raw API usage across iterations so setGenAiResponseAttrs + // can compute totals consistently (input_tokens + cache subsets). + const cumulativeUsage = { + input_tokens: 0, + output_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + cache_creation: { + ephemeral_5m_input_tokens: 0, + ephemeral_1h_input_tokens: 0, + }, + }; + function setFinalSpanAttrs(stopReason) { + setGenAiResponseAttrs(span, cumulativeUsage, stopReason); + } + function currentUsage() { + return usages.length > 0 ? (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) : (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .emptyUsage */ .ly)(); + } + async function runModelIteration() { + const inputMessages = [...messages]; + return (0,_sentry_trace_js__WEBPACK_IMPORTED_MODULE_1__/* .startTracedSpan */ .wZ)({ + op: 'gen_ai.chat', + name: (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .genAiSpanName */ .kj)('chat', model), + parentSpan: span, + attributes: { + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': 'anthropic', + ...(agentName ? { 'gen_ai.agent.name': agentName } : {}), + ...(task ? { 'warden.ai.task': task } : {}), + 'gen_ai.request.model': model, + 'gen_ai.request.max_tokens': maxTokens, + 'gen_ai.output.type': 'json', + }, + }, async (chatSpan) => { + (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .setGenAiInputMessagesAttr */ .uQ)(chatSpan, inputMessages); + try { + const response = await client.messages.create({ + model, + max_tokens: maxTokens, + messages: inputMessages, + tools, + }); + setGenAiResponseAttrs(chatSpan, response.usage, response.stop_reason); + (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .setGenAiOutputMessagesAttrFromMessages */ .L6)(chatSpan, [{ + role: response.role, + content: response.content, + finishReason: response.stop_reason, + }]); + return response; + } + catch (error) { + chatSpan.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + throw error; + } + }); + } + for (let iteration = 0; iteration < maxIterations; iteration++) { + let response; + try { + response = await runModelIteration(); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + span.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + return { success: false, error: message, usage: currentUsage() }; + } + usages.push((0,_pricing_js__WEBPACK_IMPORTED_MODULE_2__/* .apiUsageToStats */ .Y4)(model, response.usage)); + cumulativeUsage.input_tokens += response.usage.input_tokens; + cumulativeUsage.output_tokens += response.usage.output_tokens; + cumulativeUsage.cache_read_input_tokens += response.usage.cache_read_input_tokens ?? 0; + cumulativeUsage.cache_creation_input_tokens += response.usage.cache_creation_input_tokens ?? 0; + cumulativeUsage.cache_creation.ephemeral_5m_input_tokens += + response.usage.cache_creation?.ephemeral_5m_input_tokens ?? 0; + cumulativeUsage.cache_creation.ephemeral_1h_input_tokens += + response.usage.cache_creation?.ephemeral_1h_input_tokens ?? 0; + // Handle tool use + if (response.stop_reason === 'tool_use') { + const toolUseBlocks = response.content.filter((b) => b.type === 'tool_use'); + if (toolUseBlocks.length === 0) { + span.setAttribute('error.type', 'missing_tool_call'); + return { success: false, error: 'Tool use indicated but no tool calls found', usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + const toolResults = []; + for (const block of toolUseBlocks) { + await (0,_sentry_trace_js__WEBPACK_IMPORTED_MODULE_1__/* .startTracedSpan */ .wZ)({ + op: 'gen_ai.execute_tool', + name: `execute_tool ${block.name}`, + parentSpan: span, + attributes: (0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .genAiToolCallAttributes */ .Mf)({ + agentName, + task, + toolName: block.name, + toolDescription: toolDescriptions.get(block.name), + toolCallId: block.id, + toolType: 'function', + arguments: block.input, + }), + }, async (toolSpan) => { + try { + const result = await executeTool(block.name, block.input); + for (const [key, value] of Object.entries((0,_otel_js__WEBPACK_IMPORTED_MODULE_3__/* .genAiToolCallAttributes */ .Mf)({ + toolName: block.name, + result, + }))) { + toolSpan.setAttribute(key, value); + } + toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: result }); + } + catch (error) { + const errMsg = error instanceof Error ? error.message : String(error); + toolSpan.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: errMsg, is_error: true }); + } + }); + } + messages.push({ role: 'assistant', content: response.content }); + messages.push({ role: 'user', content: toolResults }); + continue; + } + // Final response - extract text and set span attributes + if (response.stop_reason !== 'end_turn' && response.stop_reason !== 'max_tokens') { + setFinalSpanAttrs(response.stop_reason); + span.setAttribute('error.type', 'unexpected_stop_reason'); + return { success: false, error: `Unexpected stop reason: ${response.stop_reason}`, usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + const textBlock = response.content.find((b) => b.type === 'text'); + if (!textBlock) { + setFinalSpanAttrs(response.stop_reason); + span.setAttribute('error.type', 'empty_response'); + return { success: false, error: 'No text in final response', usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + setFinalSpanAttrs(response.stop_reason); + const jsonStr = extractJson(textBlock.text); + if (!jsonStr) { + span.setAttribute('error.type', 'invalid_json'); + return { success: false, error: 'No JSON found in response', usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + const parsed = JSON.parse(jsonStr); + const validated = schema.safeParse(parsed); + if (!validated.success) { + span.setAttribute('error.type', 'validation_error'); + return { success: false, error: `Validation failed: ${validated.error.message}`, usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + return { success: true, data: validated.data, usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + } + // Max iterations exceeded - still record usage on span + setFinalSpanAttrs(); + span.setAttribute('error.type', 'max_tool_iterations'); + return { success: false, error: 'Max tool iterations exceeded', usage: (0,_usage_js__WEBPACK_IMPORTED_MODULE_4__/* .aggregateUsage */ .Z$)(usages) }; + }); +} + + +/***/ }), + +/***/ 8695: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XK: () => (/* binding */ isWardenOffline), +/* harmony export */ zV: () => (/* binding */ configureWardenOffline) +/* harmony export */ }); +/* unused harmony export resetWardenOfflineForTests */ +/** + * Offline policy for Warden network side effects. + * + * `defaults.offline`, CLI `--offline`, and `WARDEN_OFFLINE` block remote skill + * loading and Pi model-catalog refresh. + */ +let configuredOffline = false; +/** Record offline intent from warden.toml / CLI for this process. */ +function configureWardenOffline(offline) { + // Explicit false clears sticky offline so reused processes can go back online. + configuredOffline = Boolean(offline); +} +/** Reset process offline state. Intended for tests. */ +function resetWardenOfflineForTests() { + configuredOffline = false; +} +/** Whether Warden-wide offline mode is active. */ +function isWardenOffline() { + const envValue = process.env['WARDEN_OFFLINE']?.trim().toLowerCase(); + return configuredOffline || envValue === 'true' || envValue === '1'; +} + + +/***/ }), + +/***/ 85884: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Jo: () => (/* binding */ genAiProviderName), +/* harmony export */ L6: () => (/* binding */ setGenAiOutputMessagesAttrFromMessages), +/* harmony export */ Mf: () => (/* binding */ genAiToolCallAttributes), +/* harmony export */ bO: () => (/* binding */ genAiUsageAttributes), +/* harmony export */ hX: () => (/* binding */ setGenAiOutputMessagesAttr), +/* harmony export */ kj: () => (/* binding */ genAiSpanName), +/* harmony export */ kq: () => (/* binding */ setGenAiSystemInstructionsAttr), +/* harmony export */ qk: () => (/* binding */ setGenAiUsageAttrs), +/* harmony export */ uQ: () => (/* binding */ setGenAiInputMessagesAttr) +/* harmony export */ }); +const PROVIDER_NAME_ALIASES = { + mistral: 'mistral_ai', + xai: 'x_ai', +}; +function providerFromModel(model) { + if (!model) { + return undefined; + } + const slashIndex = model.indexOf('/'); + if (slashIndex > 0) { + const provider = model.slice(0, slashIndex); + return PROVIDER_NAME_ALIASES[provider] ?? provider; + } + return undefined; +} +/** Resolve the OpenTelemetry GenAI provider name, preferring the observed provider over selector fallbacks. */ +function genAiProviderName(runtime, model, provider) { + const resolvedProvider = provider ?? providerFromModel(model); + return resolvedProvider + ? (PROVIDER_NAME_ALIASES[resolvedProvider] ?? resolvedProvider) + : (runtime === 'pi' ? 'pi' : 'anthropic'); +} +/** Build OTel GenAI span names as ` `, when known. */ +function genAiSpanName(operationName, targetName) { + const trimmedTarget = targetName?.trim(); + return trimmedTarget ? `${operationName} ${trimmedTarget}` : operationName; +} +/** Build current OpenTelemetry GenAI usage attributes from normalized usage. */ +function genAiUsageAttributes(usage) { + return { + 'gen_ai.usage.input_tokens': usage.inputTokens, + 'gen_ai.usage.output_tokens': usage.outputTokens, + 'gen_ai.usage.cache_read.input_tokens': usage.cacheReadInputTokens ?? 0, + 'gen_ai.usage.cache_creation.input_tokens': usage.cacheCreationInputTokens ?? 0, + }; +} +function stringifyGenAiAttribute(value) { + if (value === undefined) { + return undefined; + } + try { + const json = JSON.stringify(value); + return json === undefined ? String(value) : json; + } + catch { + return String(value); + } +} +/** + * Build OpenTelemetry GenAI attributes for an executed tool call span. + * + * Tool arguments and results are opt-in content attributes in OTel. Sentry span + * data and Warden's local trace schema only preserve primitive attributes, so + * structured values are JSON-encoded at this boundary. + */ +function genAiToolCallAttributes(args) { + const attributes = { + 'gen_ai.operation.name': 'execute_tool', + ...(args.agentName ? { 'gen_ai.agent.name': args.agentName } : {}), + ...(args.task ? { 'warden.ai.task': args.task } : {}), + 'gen_ai.tool.name': args.toolName, + ...(args.toolDescription ? { 'gen_ai.tool.description': args.toolDescription } : {}), + ...(args.toolCallId ? { 'gen_ai.tool.call.id': args.toolCallId } : {}), + ...(args.toolType ? { 'gen_ai.tool.type': args.toolType } : {}), + }; + const serializedArguments = stringifyGenAiAttribute(args.arguments); + if (serializedArguments !== undefined) { + attributes['gen_ai.tool.call.arguments'] = serializedArguments; + } + const serializedResult = args.isError ? undefined : stringifyGenAiAttribute(args.result); + if (serializedResult !== undefined) { + attributes['gen_ai.tool.call.result'] = serializedResult; + } + return attributes; +} +/** Set GenAI token usage attributes expected by Sentry AI monitoring. */ +function setGenAiUsageAttrs(span, usage) { + for (const [key, value] of Object.entries(genAiUsageAttributes(usage))) { + span.setAttribute(key, value); + } +} +/** Set OpenTelemetry GenAI system-instruction attributes for prompt spans. */ +function setGenAiSystemInstructionsAttr(span, systemPrompt) { + span.setAttribute('gen_ai.system_instructions', JSON.stringify([ + { type: 'text', content: systemPrompt }, + ])); +} +function normalizeContentPart(part) { + if (!part || typeof part !== 'object') { + return { type: 'text', content: String(part ?? '') }; + } + const block = part; + if (block['type'] === 'text' && typeof block['text'] === 'string') { + return { type: 'text', content: block['text'] }; + } + if (block['type'] === 'tool_use') { + return { + type: 'tool_call', + id: block['id'], + name: block['name'], + arguments: block['input'], + }; + } + if (block['type'] === 'toolCall') { + return { + type: 'tool_call', + id: block['id'], + name: block['name'], + arguments: block['arguments'], + }; + } + if (block['type'] === 'tool_result') { + return { + type: 'tool_call_response', + id: block['tool_use_id'], + result: normalizeToolResultContent(block['content']), + }; + } + return { ...block }; +} +function normalizeToolResultContent(content) { + if (Array.isArray(content)) { + const normalized = content.map(normalizeContentPart); + if (normalized.length === 1 + && normalized[0]?.['type'] === 'text' + && typeof normalized[0]?.['content'] === 'string') { + return normalized[0]['content']; + } + return normalized; + } + return content; +} +function finishReasonAttrs(message) { + return message.finishReason ? { finish_reason: message.finishReason } : {}; +} +function normalizeMessage(message) { + const { role, content } = message; + if ((role === 'tool' || role === 'toolResult') && message.toolCallId) { + return { + role: 'tool', + parts: [{ + type: 'tool_call_response', + id: message.toolCallId, + result: normalizeToolResultContent(content), + }], + }; + } + const contentParts = Array.isArray(content) ? content : undefined; + // Anthropic tool results arrive as user messages; OTel records them as tool + // messages so trace readers can reconstruct the request/result pairing. + const normalizedRole = role === 'toolResult' + || (role === 'user' + && contentParts?.length + && contentParts.every((part) => Boolean(part && typeof part === 'object' && part['type'] === 'tool_result'))) + ? 'tool' + : role; + if (typeof content === 'string') { + return { + role: normalizedRole, + parts: [{ type: 'text', content }], + ...finishReasonAttrs(message), + }; + } + if (Array.isArray(content)) { + return { + role: normalizedRole, + parts: content.map(normalizeContentPart), + ...finishReasonAttrs(message), + }; + } + return { + role: normalizedRole, + parts: [normalizeContentPart(content)], + ...finishReasonAttrs(message), + }; +} +/** Set OTel GenAI input messages from raw runtime transcript messages. */ +function setGenAiInputMessagesAttr(span, messages) { + span.setAttribute('gen_ai.input.messages', JSON.stringify(messages.map(normalizeMessage))); +} +/** Set OTel GenAI output messages from raw runtime response messages. */ +function setGenAiOutputMessagesAttrFromMessages(span, messages) { + span.setAttribute('gen_ai.output.messages', JSON.stringify(messages.map(normalizeMessage))); +} +/** Set OpenTelemetry GenAI output message attributes for text responses. */ +function setGenAiOutputMessagesAttr(span, responseText, finishReason) { + span.setAttribute('gen_ai.output.messages', JSON.stringify([ + { + role: 'assistant', + parts: [{ type: 'text', content: responseText }], + ...(finishReason ? { finish_reason: finishReason } : {}), + }, + ])); +} + + +/***/ }), + +/***/ 64602: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ MG: () => (/* binding */ estimateUsageCostBreakdown), +/* harmony export */ Y4: () => (/* binding */ apiUsageToStats) +/* harmony export */ }); +/* unused harmony export anthropicUsageToStats */ +/* harmony import */ var _earendil_works_pi_ai__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(25941); +/* harmony import */ var _earendil_works_pi_ai_providers_anthropic__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13074); + + +const WEB_SEARCH_PER_REQUEST_USD = 0.01; +const ANTHROPIC_MODELS = new Map((0,_earendil_works_pi_ai_providers_anthropic__WEBPACK_IMPORTED_MODULE_0__/* .anthropicProvider */ .K)().getModels().map((model) => [model.id, model])); +/** Resolve exact Pi IDs or dated API response IDs whose base model Pi owns. */ +function findAnthropicModel(model) { + return ANTHROPIC_MODELS.get(model) + ?? ANTHROPIC_MODELS.get(model.replace(/-\d{8}$/, '')); +} +function createPiUsage(input, output, cacheRead, cacheWrite, cacheWrite1h) { + return { + input, + output, + cacheRead, + cacheWrite, + cacheWrite1h, + totalTokens: input + output + cacheRead + cacheWrite, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; +} +/** Return categorized costs when the Anthropic model resolves to Pi's catalog. */ +function estimateUsageCostBreakdown(model, usage) { + if (!model) + return undefined; + const cacheReadInputTokens = usage.cacheReadInputTokens ?? 0; + const cacheCreation5mInputTokens = usage.cacheCreation5mInputTokens ?? 0; + const cacheCreation1hInputTokens = usage.cacheCreation1hInputTokens ?? 0; + const cacheCreationInputTokens = Math.max(usage.cacheCreationInputTokens ?? 0, cacheCreation5mInputTokens + cacheCreation1hInputTokens); + const cacheCreationInputTokensByTier = cacheCreation5mInputTokens + cacheCreation1hInputTokens; + const uncategorizedCacheCreationInputTokens = Math.max(0, cacheCreationInputTokens - cacheCreationInputTokensByTier); + const freshInputTokens = Math.max(0, usage.inputTokens - cacheReadInputTokens - cacheCreationInputTokens); + const webSearchRequests = usage.webSearchRequests ?? 0; + const piModel = findAnthropicModel(model); + if (!piModel) + return undefined; + const piUsage = createPiUsage(freshInputTokens, usage.outputTokens, cacheReadInputTokens, cacheCreationInputTokens, cacheCreation1hInputTokens); + const piCost = (0,_earendil_works_pi_ai__WEBPACK_IMPORTED_MODULE_1__/* .calculateCost */ .yN)(piModel, piUsage); + const shortCacheCreationInputTokens = uncategorizedCacheCreationInputTokens + cacheCreation5mInputTokens; + let cacheCreation1hUSD = 0; + if (cacheCreation1hInputTokens > 0) { + // Keep total input constant so Pi selects the same pricing tier while isolating 1h writes. + const longWriteUsage = createPiUsage(freshInputTokens + shortCacheCreationInputTokens, 0, cacheReadInputTokens, cacheCreation1hInputTokens, cacheCreation1hInputTokens); + cacheCreation1hUSD = (0,_earendil_works_pi_ai__WEBPACK_IMPORTED_MODULE_1__/* .calculateCost */ .yN)(piModel, longWriteUsage).cacheWrite; + } + const shortCacheCreationUSD = piCost.cacheWrite - cacheCreation1hUSD; + const cacheCreationUSD = shortCacheCreationInputTokens > 0 + ? shortCacheCreationUSD * uncategorizedCacheCreationInputTokens / shortCacheCreationInputTokens + : 0; + const cacheCreation5mUSD = shortCacheCreationUSD - cacheCreationUSD; + // Pi calculates token costs; Anthropic's server-side web search charge is separate. + const webSearchUSD = webSearchRequests * WEB_SEARCH_PER_REQUEST_USD; + return { + freshInputUSD: piCost.input, + outputUSD: piCost.output, + cacheReadUSD: piCost.cacheRead, + cacheCreationUSD, + cacheCreation5mUSD, + cacheCreation1hUSD, + webSearchUSD, + totalUSD: piCost.total + webSearchUSD, + }; +} +/** + * Convert Anthropic API usage to our UsageStats format. + * Calculates cost from token counts using model pricing. + * + * The Anthropic API reports `input_tokens` as only the non-cached portion. + * We normalize so that `inputTokens` is the *total* input tokens + * (non-cached + cache_read + cache_creation), with the cache fields + * being subsets of that total. + */ +function anthropicUsageToStats(model, usage) { + const outputTokens = usage.output_tokens; + const cacheReadInputTokens = usage.cache_read_input_tokens ?? 0; + const rawCacheCreationInputTokens = usage.cache_creation_input_tokens ?? 0; + const tieredCacheCreation5mInputTokens = usage.cache_creation?.ephemeral_5m_input_tokens ?? 0; + const cacheCreation1hInputTokens = usage.cache_creation?.ephemeral_1h_input_tokens ?? 0; + const hasTieredCacheCreation = usage.cache_creation !== undefined && usage.cache_creation !== null; + const tieredCacheCreationInputTokens = tieredCacheCreation5mInputTokens + cacheCreation1hInputTokens; + const cacheCreationInputTokens = Math.max(rawCacheCreationInputTokens, tieredCacheCreationInputTokens); + const cacheCreation5mInputTokens = hasTieredCacheCreation + ? tieredCacheCreation5mInputTokens + : rawCacheCreationInputTokens; + const uncategorizedCacheCreationInputTokens = Math.max(0, cacheCreationInputTokens - cacheCreation5mInputTokens - cacheCreation1hInputTokens); + const webSearchRequests = usage.server_tool_use?.web_search_requests ?? 0; + // inputTokens is the total: raw API input_tokens + cache subsets. + const inputTokens = usage.input_tokens + cacheReadInputTokens + cacheCreationInputTokens; + const stats = { + inputTokens, + outputTokens, + cacheReadInputTokens, + cacheCreationInputTokens, + cacheCreation5mInputTokens: cacheCreation5mInputTokens + uncategorizedCacheCreationInputTokens, + cacheCreation1hInputTokens, + webSearchRequests, + costUSD: 0, + }; + const breakdown = estimateUsageCostBreakdown(model, stats); + stats.costUSD = breakdown?.totalUSD ?? 0; + return stats; +} +/** @deprecated Use anthropicUsageToStats. */ +const apiUsageToStats = anthropicUsageToStats; + + +/***/ }), + +/***/ 85286: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ E_: () => (/* binding */ isPiModelSelector), +/* harmony export */ lG: () => (/* binding */ assertValidPiModelSelectors), +/* harmony export */ n1: () => (/* binding */ InvalidPiModelSelectorError) +/* harmony export */ }); +/* unused harmony exports invalidPiModelSelectorMessage, findInvalidPiModelSelector */ +/** + * Return true when a Pi model selector uses provider/model-id syntax. + */ +function isPiModelSelector(model) { + const slashIndex = model.indexOf('/'); + return slashIndex > 0 && slashIndex < model.length - 1; +} +/** + * Format the user-facing error for an invalid Pi model selector. + */ +function invalidPiModelSelectorMessage(invalid) { + const target = invalid.specName ? ` for ${invalid.specName}` : ''; + return `Pi runtime ${invalid.option}${target} must use provider/model format: ${invalid.model}`; +} +/** + * Preserve invalid Pi selector details through shared error classification. + */ +class InvalidPiModelSelectorError extends Error { + invalid; + constructor(invalid) { + super(invalidPiModelSelectorMessage(invalid)); + this.name = 'InvalidPiModelSelectorError'; + this.invalid = invalid; + } +} +/** + * Find the first Pi runner option using a model ID that is not provider/model. + */ +function findInvalidPiModelSelector(targets) { + for (const target of targets) { + const runtimeName = target.runtime ?? 'pi'; + if (runtimeName !== 'pi') { + continue; + } + for (const option of ['model', 'auxiliaryModel', 'synthesisModel']) { + const model = target[option]; + if (model && !isPiModelSelector(model)) { + return { specName: target.name, option, model }; + } + } + } + return undefined; +} +/** + * Throw when any Pi runner option is not a provider/model selector. + */ +function assertValidPiModelSelectors(targets) { + const invalid = findInvalidPiModelSelector(targets); + if (invalid) { + throw new InvalidPiModelSelectorError(invalid); + } +} + + +/***/ }), + +/***/ 60522: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + piRuntime: () => (/* binding */ piRuntime) +}); + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-coding-agent@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-coding-agent/dist/index.js + 221 modules +var dist = __webpack_require__(53406); +// EXTERNAL MODULE: ../../node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/index.mjs + 1 modules +var build = __webpack_require__(91862); +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js + 7 modules +var schemas = __webpack_require__(51737); +// EXTERNAL MODULE: ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js +var json_schema_processors = __webpack_require__(9214); +// EXTERNAL MODULE: ./src/sentry.ts +var sentry = __webpack_require__(30340); +// EXTERNAL MODULE: ./src/sentry-trace.ts +var sentry_trace = __webpack_require__(68016); +// EXTERNAL MODULE: ./src/utils/index.ts + 1 modules +var utils = __webpack_require__(82272); +// EXTERNAL MODULE: ./src/sdk/haiku.ts +var haiku = __webpack_require__(39026); +// EXTERNAL MODULE: ./src/sdk/errors.ts +var errors = __webpack_require__(98229); +// EXTERNAL MODULE: ./src/sdk/otel.ts +var otel = __webpack_require__(85884); +// EXTERNAL MODULE: ./src/sdk/usage.ts +var usage = __webpack_require__(44759); +// EXTERNAL MODULE: ./src/sdk/runtimes/model-selectors.ts +var model_selectors = __webpack_require__(85286); +// EXTERNAL MODULE: ./src/sdk/offline.ts +var offline = __webpack_require__(8695); +// EXTERNAL MODULE: external "node:fs/promises" +var promises_ = __webpack_require__(51455); +// EXTERNAL MODULE: external "node:path" +var external_node_path_ = __webpack_require__(76760); +// EXTERNAL MODULE: external "node:url" +var external_node_url_ = __webpack_require__(73136); +// EXTERNAL MODULE: ./src/skills/resources.ts +var resources = __webpack_require__(18771); +;// CONCATENATED MODULE: ./src/sdk/runtimes/pi-file-tools.ts + + + + + +const CHECKOUT_GUIDANCE = 'Stay inside the current checkout. Use repository-relative paths.'; +function isMissingPathError(error) { + return error instanceof Error + && 'code' in error + && (error.code === 'ENOENT' || error.code === 'ENOTDIR'); +} +function isWithinPath(root, target) { + const relativePath = (0,external_node_path_.relative)(root, target); + return relativePath === '' + || (relativePath !== '..' + && !relativePath.startsWith(`..${external_node_path_.sep}`) + && !(0,external_node_path_.isAbsolute)(relativePath)); +} +async function resolveThroughExistingAncestor(target) { + let candidate = target; + const missingSegments = []; + while (true) { + try { + const existingPath = await (0,promises_.realpath)(candidate); + return (0,external_node_path_.resolve)(existingPath, ...missingSegments.reverse()); + } + catch (error) { + if (!isMissingPathError(error)) { + throw error; + } + const parent = (0,external_node_path_.dirname)(candidate); + if (parent === candidate) { + throw error; + } + missingSegments.push((0,external_node_path_.basename)(candidate)); + candidate = parent; + } + } +} +function checkoutPathError(requestedPath, checkoutPath) { + return new Error(`Path "${requestedPath}" is outside the checkout at "${checkoutPath}". ${CHECKOUT_GUIDANCE}`); +} +async function resolveAllowedPath(checkoutPath, requestedPath, skillRoot) { + const checkout = (0,external_node_path_.resolve)(checkoutPath); + const target = (0,external_node_path_.resolve)(checkout, requestedPath); + const resourceRoot = skillRoot ? resources/* SKILL_RESOURCE_DIRECTORIES */.j + .map((dir) => (0,external_node_path_.resolve)(skillRoot, dir)) + .find((root) => isWithinPath(root, target)) : undefined; + const withinCheckout = isWithinPath(checkout, target); + if (!withinCheckout && !resourceRoot) { + throw checkoutPathError(requestedPath, checkout); + } + const [canonicalCheckout, canonicalTarget] = await Promise.all([ + resolveThroughExistingAncestor(checkout), + resolveThroughExistingAncestor(target), + ]); + if (withinCheckout && isWithinPath(canonicalCheckout, canonicalTarget)) { + return canonicalTarget; + } + if (resourceRoot && skillRoot) { + // Anchor the extra access to the skill itself, so resource symlinks cannot + // grant access to unrelated files outside the checkout. + const canonicalSkillRoot = await resolveThroughExistingAncestor(skillRoot); + const allowedRoot = (0,external_node_path_.resolve)(canonicalSkillRoot, (0,external_node_path_.relative)((0,external_node_path_.resolve)(skillRoot), resourceRoot)); + if (isWithinPath(allowedRoot, canonicalTarget)) { + return canonicalTarget; + } + } + throw checkoutPathError(requestedPath, checkout); +} +function confineTool(tool, checkoutPath, skillRoot) { + const guidance = skillRoot + ? `${CHECKOUT_GUIDANCE} Read may also access scripts/, references/, and assets/ under the resolved skill at ${skillRoot}.` + : CHECKOUT_GUIDANCE; + return (0,dist.defineTool)({ + ...tool, + description: `${tool.description} ${guidance}`, + promptGuidelines: [ + ...(tool.promptGuidelines ?? []), + guidance, + ], + async execute(toolCallId, params, signal, onUpdate, context) { + const input = params; + const requestedPath = typeof input.path === 'string' ? input.path : '.'; + const confinedPath = await resolveAllowedPath(checkoutPath, requestedPath, skillRoot); + const confinedParams = { + ...params, + path: (0,external_node_url_.pathToFileURL)(confinedPath).href, + }; + return tool.execute(toolCallId, confinedParams, signal, onUpdate, context); + }, + }); +} +/** Confine Pi tools to the checkout, with read-only access to resolved skill resources. */ +function createCheckoutFileTools(checkoutPath, toolNames, skillRoot) { + const requestedTools = new Set(toolNames); + const tools = []; + if (requestedTools.has('read')) { + tools.push(confineTool((0,dist.createReadToolDefinition)(checkoutPath), checkoutPath, skillRoot)); + } + if (requestedTools.has('grep')) { + tools.push(confineTool((0,dist.createGrepToolDefinition)(checkoutPath), checkoutPath)); + } + if (requestedTools.has('find')) { + tools.push(confineTool((0,dist.createFindToolDefinition)(checkoutPath), checkoutPath)); + } + if (requestedTools.has('ls')) { + tools.push(confineTool((0,dist.createLsToolDefinition)(checkoutPath), checkoutPath)); + } + return tools; +} + +;// CONCATENATED MODULE: ./src/sdk/runtimes/pi.ts +/** + * Pi runtime adapter. + * + * This keeps Pi-specific session setup, model selection, tool mapping, auth + * handling, telemetry, and usage normalization behind Warden's runtime + * contract. Warden still owns prompt construction, finding extraction, + * verification, deduplication, and reporting. + */ + + + + + + + + + + + + + +const READ_ONLY_TOOLS = ['Read', 'Grep', 'Glob']; +const MUTATING_TOOLS = ['Write', 'Edit', 'Bash']; +const UNSUPPORTED_TOOLS = ['WebFetch', 'WebSearch']; +const DEFAULT_PI_PROVIDER_MAX_RETRIES = 2; +const PI_SKILL_PROVIDER_MAX_RETRIES = 0; +const PI_MODEL_REFRESH_TIMEOUT_MS = 15_000; +const activeProviderCatalogRefreshes = new Map(); +const PI_TOOL_NAMES = { + Read: ['read'], + Write: ['write'], + Edit: ['edit'], + Bash: ['bash'], + Glob: ['find', 'ls'], + Grep: ['grep'], +}; +function errorMessage(error) { + return (0,errors/* sanitizeErrorMessage */.$w)(error instanceof Error ? error.message : String(error)); +} +function parseModelSelector(model) { + if (!(0,model_selectors/* isPiModelSelector */.E_)(model)) { + throw new model_selectors/* InvalidPiModelSelectorError */.n1({ option: 'model', model }); + } + const slashIndex = model.indexOf('/'); + return { + provider: model.slice(0, slashIndex), + modelId: model.slice(slashIndex + 1), + }; +} +function legacyApiKeyProvider(model) { + if (!model) { + return 'anthropic'; + } + const selector = parseModelSelector(model); + return selector.provider === 'anthropic' ? 'anthropic' : undefined; +} +/** + * Combine abort signals without AbortSignal.any (Node < 20.3). + * Warden's engines field allows Node >= 20.0.0. + */ +function anyAbortSignal(...signals) { + if (typeof AbortSignal.any === 'function') { + return AbortSignal.any(signals); + } + const controller = new AbortController(); + const onAbort = () => { + controller.abort(); + for (const signal of signals) { + signal.removeEventListener('abort', onAbort); + } + }; + for (const signal of signals) { + if (signal.aborted) { + onAbort(); + break; + } + signal.addEventListener('abort', onAbort, { once: true }); + } + return controller.signal; +} +/** + * Build a timeout signal without AbortSignal.timeout (Node < 20.3). + * Same engines window as anyAbortSignal above. + */ +function timeoutAbortSignal(ms) { + if (typeof AbortSignal.timeout === 'function') { + return AbortSignal.timeout(ms); + } + const controller = new AbortController(); + const timer = setTimeout(() => { + controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError')); + }, ms); + // Match Node's AbortSignal.timeout: do not keep the process alive for the deadline alone. + timer.unref?.(); + return controller.signal; +} +function refreshSignal(abortSignal) { + const timeoutSignal = timeoutAbortSignal(PI_MODEL_REFRESH_TIMEOUT_MS); + return abortSignal ? anyAbortSignal(abortSignal, timeoutSignal) : timeoutSignal; +} +function waitForSharedRefresh(shared, abortSignal) { + if (!abortSignal) { + return shared; + } + if (abortSignal.aborted) { + return Promise.reject(abortSignal.reason ?? new DOMException('This operation was aborted', 'AbortError')); + } + return new Promise((resolve, reject) => { + const onAbort = () => { + cleanup(); + reject(abortSignal.reason ?? new DOMException('This operation was aborted', 'AbortError')); + }; + const cleanup = () => { + abortSignal.removeEventListener('abort', onAbort); + }; + abortSignal.addEventListener('abort', onAbort, { once: true }); + shared.then(() => { + cleanup(); + resolve(); + }, (error) => { + cleanup(); + reject(error); + }); + }); +} +/** + * Refresh one provider catalog through Pi, with a deadline and optional caller abort. + * Concurrent prompts for the same provider share one in-flight network refresh so a + * cold models-store does not stampede pi.dev. After the shared phase settles, each + * runtime does a local restore/refresh so its own ModelRuntime overlay is updated. + * Offline mode (warden.toml defaults.offline, CLI --offline, or WARDEN_OFFLINE) + * skips the shared network phase and only restores from local cache/builtins. + */ +async function refreshSelectedProviderCatalog(modelRuntime, providerId, abortSignal) { + if (abortSignal?.aborted) { + throw abortSignal.reason ?? new DOMException('This operation was aborted', 'AbortError'); + } + if ((0,offline/* isWardenOffline */.XK)()) { + await modelRuntime.refresh({ + providers: [providerId], + allowNetwork: false, + signal: refreshSignal(abortSignal), + }); + return; + } + let active = activeProviderCatalogRefreshes.get(providerId); + if (!active) { + const controller = new AbortController(); + const created = { + controller, + promise: undefined, + waiters: 0, + }; + // Explicit allowNetwork so Warden offline policy owns network access, not Pi env vars. + // Keep the map entry until the last waiter finishes local restore so late joiners + // reuse this shared phase instead of starting a redundant network refresh. + created.promise = modelRuntime.refresh({ + providers: [providerId], + allowNetwork: true, + signal: refreshSignal(controller.signal), + }).then(() => undefined); + active = created; + activeProviderCatalogRefreshes.set(providerId, active); + } + active.waiters += 1; + try { + try { + await waitForSharedRefresh(active.promise, abortSignal); + } + catch (error) { + // Shared network failure must not strand this runtime; local restore/refresh + // below can still recover from models-store or built-ins. Caller aborts exit now. + if (abortSignal?.aborted) { + throw error; + } + } + // Shared work (if it succeeded) warmed models-store. Restore into this runtime + // without another network attempt so failed shared refreshes cannot stampede. + await modelRuntime.refresh({ + providers: [providerId], + allowNetwork: false, + signal: refreshSignal(abortSignal), + }); + } + finally { + active.waiters -= 1; + if (active.waiters === 0 && activeProviderCatalogRefreshes.get(providerId) === active) { + active.controller.abort(); + activeProviderCatalogRefreshes.delete(providerId); + } + } +} +async function createModelRuntime(model, legacyAnthropicApiKey, abortSignal) { + const modelRuntime = await dist.ModelRuntime.create(); + const selectedProvider = model ? parseModelSelector(model).provider : undefined; + const legacyProvider = legacyApiKeyProvider(model); + if (legacyAnthropicApiKey && legacyProvider) { + await modelRuntime.setRuntimeApiKey(legacyProvider, legacyAnthropicApiKey); + } + if (selectedProvider) { + await refreshSelectedProviderCatalog(modelRuntime, selectedProvider, abortSignal); + } + return modelRuntime; +} +/** + * Optional base-URL override for a provider, from `WARDEN__BASE_URL`. + * + * Mirrors the existing `WARDEN__API_KEY` convention, so pointing a provider at + * an OpenAI-compatible gateway (LiteLLM, a corporate proxy, a self-hosted endpoint) is the + * same shape of configuration as giving it a key. Unset means the provider's own default, + * exactly as today. + */ +function providerBaseUrlOverride(provider) { + const value = process.env[`WARDEN_${provider.toUpperCase()}_BASE_URL`]; + return value && value.length > 0 ? value : undefined; +} +function providerHeadersOverride(provider) { + const envName = `WARDEN_${provider.toUpperCase()}_HEADERS`; + const value = process.env[envName]; + if (!value) { + return undefined; + } + try { + return schemas/* record */.g1P(schemas/* string */.YjP(), schemas/* string */.YjP()).parse(JSON.parse(value)); + } + catch { + throw new Error(`${envName} must be a JSON object with string values`); + } +} +function resolvePiModel(model, modelRuntime) { + if (!model) { + return undefined; + } + const { provider, modelId } = parseModelSelector(model); + const resolved = modelRuntime.getModel(provider, modelId); + if (!resolved) { + throw new Error(`Pi model not found: ${model}. Use provider/model, for example openai/gpt-5.5.`); + } + const baseUrl = providerBaseUrlOverride(provider); + const headers = providerHeadersOverride(provider); + if (!baseUrl && !headers) { + return resolved; + } + return { + ...resolved, + ...(baseUrl ? { baseUrl } : {}), + ...(headers ? { headers: { ...resolved.headers, ...headers } } : {}), + }; +} +function resolvePiSkillTools(tools, allowMutatingTools = false) { + const denied = new Set(tools?.denied ?? []); + const requested = tools?.allowed ?? READ_ONLY_TOOLS; + const availableTools = allowMutatingTools + ? [...READ_ONLY_TOOLS, ...MUTATING_TOOLS] + : READ_ONLY_TOOLS; + const toolNames = []; + const warnings = []; + for (const tool of requested) { + if (denied.has(tool)) { + continue; + } + if (UNSUPPORTED_TOOLS.includes(tool)) { + warnings.push(`Pi runtime ignored unsupported tool: ${tool}`); + continue; + } + if (!allowMutatingTools && MUTATING_TOOLS.includes(tool)) { + warnings.push(`Pi runtime ignored mutating tool without allowMutatingTools: ${tool}`); + continue; + } + if (!availableTools.includes(tool)) { + continue; + } + for (const name of PI_TOOL_NAMES[tool]) { + if (!toolNames.includes(name)) { + toolNames.push(name); + } + } + } + return { toolNames, warnings }; +} +function isAssistantMessage(message) { + return Boolean(message + && typeof message === 'object' + && message.role === 'assistant'); +} +function textFromAssistant(message) { + return message.content + .filter((content) => content.type === 'text') + .map((content) => content.text) + .join(''); +} +function piUsageToStats(usage) { + const cacheRead = usage.cacheRead; + const cacheWrite = usage.cacheWrite; + return { + inputTokens: usage.input + cacheRead + cacheWrite, + outputTokens: usage.output, + cacheReadInputTokens: cacheRead, + cacheCreationInputTokens: cacheWrite, + cacheCreation5mInputTokens: cacheWrite, + cacheCreation1hInputTokens: 0, + webSearchRequests: 0, + costUSD: usage.cost.total, + }; +} +function aggregatePiUsage(messages) { + return (0,usage/* aggregateUsage */.Z$)(messages.map((message) => piUsageToStats(message.usage))); +} +function statusFromPiMessage(message, hitMaxTurns) { + if (hitMaxTurns) { + return 'turn_limit'; + } + switch (message.stopReason) { + case 'stop': + return 'success'; + case 'length': + return 'output_limit'; + case 'toolUse': + return 'provider_error'; + case 'error': + return message.errorMessage && (0,errors/* isAuthenticationErrorMessage */.Ip)(message.errorMessage) + ? 'auth_error' + : 'provider_error'; + case 'aborted': + return 'aborted'; + default: + return 'provider_error'; + } +} +function normalizePiResult(run, maxTokens) { + const message = run.lastAssistant; + if (!message) { + return undefined; + } + const errors = message.errorMessage ? [message.errorMessage] : []; + const status = statusFromPiMessage(message, run.hitMaxTurns); + if (status === 'output_limit') { + const details = [ + 'finish_reason=length', + `model=${message.responseModel ?? message.model}`, + ...(maxTokens !== undefined ? [`max_tokens=${maxTokens}`] : []), + `output_tokens=${message.usage.output}`, + ]; + errors.unshift(`Pi response reached the output token limit (${details.join(', ')}). Increase the budget to allow reasoning and a complete answer.`); + } + return { + status, + text: textFromAssistant(message), + errors, + usage: run.usage, + responseProvider: message.provider, + responseId: message.responseId, + responseModel: message.responseModel ?? message.model, + sessionId: run.sessionId, + durationMs: run.durationMs, + numTurns: run.numTurns, + }; +} +function buildSettingsManager(timeout, maxRetries) { + const providerMaxRetries = maxRetries ?? DEFAULT_PI_PROVIDER_MAX_RETRIES; + return dist.SettingsManager.inMemory({ + compaction: { enabled: false }, + retry: { + // Provider retries are independent from Pi's agent-level transient retry loop. + enabled: true, + provider: { + ...(timeout !== undefined ? { timeoutMs: timeout } : {}), + maxRetries: providerMaxRetries, + }, + }, + }); +} +function setSpanAttributes(span, attributes) { + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) { + span.setAttribute(key, value); + } + } +} +async function promptWithTimeout(session, userPrompt, timeout) { + const prompt = session.prompt(userPrompt, { expandPromptTemplates: false }); + if (timeout === undefined) { + await prompt; + return; + } + let timeoutId; + let timedOut = false; + const timeoutPromise = new Promise((_resolve, reject) => { + timeoutId = setTimeout(() => { + timedOut = true; + reject(new Error(`Pi runtime timed out after ${timeout}ms`)); + }, timeout); + }); + try { + await Promise.race([prompt, timeoutPromise]); + } + catch (error) { + if (timedOut) { + await session.abort(); + } + throw error; + } + finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + } +} +async function runPiPrompt(options) { + const warnings = []; + (0,utils/* bridgeWardenProviderApiKeyEnv */.cw)(); + const modelRuntime = await createModelRuntime(options.model, options.legacyAnthropicApiKey, options.abortController?.signal); + const model = resolvePiModel(options.model, modelRuntime); + const settingsManager = buildSettingsManager(options.timeout, options.maxRetries); + const agentDir = (0,dist.getAgentDir)(); + const resourceLoader = new dist.DefaultResourceLoader({ + cwd: options.cwd, + agentDir, + settingsManager, + noExtensions: true, + noSkills: true, + noPromptTemplates: true, + noThemes: true, + noContextFiles: true, + systemPrompt: options.systemPrompt, + }); + await resourceLoader.reload(); + let session; + const assistantMessages = []; + let agentEndMessages; + let lastAssistant; + let numTurns = 0; + let hitMaxTurns = false; + const startedAt = Date.now(); + const activeToolSpans = new Map(); + const conversationMessages = [{ role: 'user', content: options.userPrompt }]; + // Pi uses cwd for path resolution but does not treat it as a filesystem boundary. + // Same-name custom tools override its built-ins, so file access stays in the checkout. + const customTools = options.customTools ?? []; + const customToolNames = new Set(customTools.map((tool) => tool.name)); + const checkoutFileTools = createCheckoutFileTools(options.cwd, options.toolNames.filter((toolName) => !customToolNames.has(toolName)), options.skillRoot); + const sessionCustomTools = [...customTools, ...checkoutFileTools]; + const buildToolAttributes = (args) => (0,otel/* genAiToolCallAttributes */.Mf)({ + agentName: options.agentName, + toolName: args.toolName, + toolDescription: options.toolDescriptions?.[args.toolName], + toolCallId: args.toolCallId, + toolType: 'function', + arguments: args.input, + result: args.result, + isError: args.isError, + }); + function startToolSpan(event) { + try { + const parentSpan = options.parentSpan ?? sentry/* Sentry.getActiveSpan */.sQ.getActiveSpan(); + const span = (0,sentry_trace/* startInactiveTracedSpan */.By)({ + op: 'gen_ai.execute_tool', + name: `execute_tool ${event.toolName}`, + ...(parentSpan && { parentSpan }), + attributes: buildToolAttributes({ + toolName: event.toolName, + toolCallId: event.toolCallId, + input: event.args, + }), + }); + activeToolSpans.set(event.toolCallId, span); + } + catch { + // Telemetry should never break the workflow. + } + } + function finishToolSpan(event) { + try { + const parentSpan = options.parentSpan ?? sentry/* Sentry.getActiveSpan */.sQ.getActiveSpan(); + const span = activeToolSpans.get(event.toolCallId) ?? (0,sentry_trace/* startInactiveTracedSpan */.By)({ + op: 'gen_ai.execute_tool', + name: `execute_tool ${event.toolName}`, + ...(parentSpan && { parentSpan }), + }); + activeToolSpans.delete(event.toolCallId); + setSpanAttributes(span, buildToolAttributes({ + toolName: event.toolName, + toolCallId: event.toolCallId, + result: event.result, + isError: event.isError, + })); + if (event.isError) { + span.setAttribute('error.type', 'tool_error'); + } + span.end(); + (0,sentry_trace/* recordTracedSpan */.hb)(span, options.traceRecorder); + } + catch { + // Telemetry should never break the workflow. + } + } + function finishOpenToolSpans(errorType) { + for (const span of activeToolSpans.values()) { + try { + span.setAttribute('error.type', errorType); + span.end(); + (0,sentry_trace/* recordTracedSpan */.hb)(span, options.traceRecorder); + } + catch { + // Telemetry should never break the workflow. + } + } + activeToolSpans.clear(); + } + function recordTurnSpan(message, toolResults) { + const outputMessage = { + role: message.role, + content: message.content, + finishReason: message.stopReason, + }; + const followUpMessages = toolResults ?? []; + const requestModel = options.model ?? message.model ?? message.responseModel; + try { + const usageAttrs = (0,otel/* genAiUsageAttributes */.bO)(piUsageToStats(message.usage)); + (0,sentry_trace/* startTracedSpan */.wZ)({ + op: 'gen_ai.chat', + name: (0,otel/* genAiSpanName */.kj)('chat', requestModel), + ...(options.parentSpan ? { parentSpan: options.parentSpan } : {}), + attributes: { + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': message.provider ?? (0,otel/* genAiProviderName */.Jo)('pi', options.model), + ...(options.agentName ? { 'gen_ai.agent.name': options.agentName } : {}), + ...(requestModel ? { 'gen_ai.request.model': requestModel } : {}), + 'gen_ai.response.model': message.responseModel ?? message.model, + ...usageAttrs, + }, + }, (span) => { + (0,otel/* setGenAiInputMessagesAttr */.uQ)(span, conversationMessages); + (0,otel/* setGenAiOutputMessagesAttrFromMessages */.L6)(span, [outputMessage]); + }, options.traceRecorder); + } + catch { + // Telemetry should never break the workflow. + } + conversationMessages.push(outputMessage, ...followUpMessages); + } + try { + const result = await (0,dist.createAgentSession)({ + cwd: options.cwd, + agentDir, + modelRuntime, + model, + thinkingLevel: options.effort, + tools: options.toolNames, + noTools: options.toolNames.length === 0 ? 'all' : undefined, + customTools: sessionCustomTools.length > 0 ? sessionCustomTools : undefined, + resourceLoader, + sessionManager: dist.SessionManager.inMemory(options.cwd), + settingsManager, + }); + session = result.session; + if (options.maxTokens !== undefined) { + // Preserve Pi's provider/auth wrapper while forwarding the caller's cap. + // Otherwise structured calls silently use the model's full output limit. + const stream = session.agent.streamFunction.bind(session.agent); + session.agent.streamFunction = (model, context, streamOptions) => stream(model, context, { + ...streamOptions, + maxTokens: options.maxTokens, + }); + } + if (result.modelFallbackMessage) { + warnings.push(result.modelFallbackMessage); + } + const unsubscribe = session.subscribe((event) => { + if (event.type === 'message_end' && isAssistantMessage(event.message)) { + if (hitMaxTurns + && lastAssistant?.stopReason === 'toolUse' + && event.message.stopReason === 'aborted') { + return; + } + assistantMessages.push(event.message); + lastAssistant = event.message; + } + else if (event.type === 'agent_end') { + agentEndMessages = [...event.messages]; + } + else if (event.type === 'tool_execution_start') { + startToolSpan(event); + } + else if (event.type === 'tool_execution_end') { + finishToolSpan(event); + } + else if (event.type === 'turn_end') { + if (isAssistantMessage(event.message)) { + recordTurnSpan(event.message, event.toolResults); + } + numTurns++; + if (options.maxTurns !== undefined + && numTurns >= options.maxTurns + && isAssistantMessage(event.message) + && event.message.stopReason === 'toolUse') { + hitMaxTurns = true; + lastAssistant = event.message; + void session?.abort(); + } + } + }); + const abortSignal = options.abortController?.signal; + const onAbort = () => { + void session?.abort(); + }; + abortSignal?.addEventListener('abort', onAbort, { once: true }); + try { + if (abortSignal?.aborted) { + await session.abort(); + } + else { + await promptWithTimeout(session, options.userPrompt, options.timeout); + } + } + finally { + abortSignal?.removeEventListener('abort', onAbort); + unsubscribe(); + } + } + finally { + finishOpenToolSpans('aborted'); + session?.dispose(); + } + if (!lastAssistant && agentEndMessages) { + for (const message of agentEndMessages) { + if (isAssistantMessage(message)) { + assistantMessages.push(message); + lastAssistant = message; + } + } + } + return { + lastAssistant, + assistantMessages, + usage: aggregatePiUsage(assistantMessages), + sessionId: session?.sessionId, + durationMs: Date.now() - startedAt, + numTurns, + hitMaxTurns, + warnings, + }; +} +function toStructuredPrompt(kind, task, schema) { + const jsonSchema = json_schema_processors/* toJSONSchema */.bl(schema); + return [ + `You are Warden's ${kind} structured-output runtime.`, + task ? `Task: ${task}` : undefined, + 'Return only valid JSON. Do not include markdown fences, commentary, or surrounding prose.', + 'The JSON must match this schema:', + JSON.stringify(jsonSchema, null, 2), + ].filter((line) => line !== undefined).join('\n\n'); +} +function toPiCustomTools(tools, executeTool) { + if (!tools || tools.length === 0) { + return undefined; + } + return tools.map((tool) => (0,dist.defineTool)({ + name: tool.name, + label: tool.name, + description: tool.description ?? '', + promptSnippet: `${tool.name}: ${tool.description ?? 'custom tool'}`, + parameters: build.Type.Unsafe(tool.inputSchema), + async execute(_toolCallId, params) { + const result = await (executeTool ?? (async () => ''))(tool.name, params); + return { + content: [{ type: 'text', text: result }], + details: { tool: tool.name }, + }; + }, + })); +} +function toolDescriptionsByName(tools) { + const descriptions = Object.fromEntries((tools ?? []) + .filter((tool) => typeof tool.description === 'string' && tool.description.length > 0) + .map((tool) => [tool.name, tool.description])); + return Object.keys(descriptions).length > 0 ? descriptions : undefined; +} +async function runStructured(request) { + const customTools = toPiCustomTools(request.tools, request.executeTool); + const systemPrompt = toStructuredPrompt(request.kind, request.task, request.schema); + const toolNames = customTools?.map((tool) => tool.name) ?? []; + const toolDescriptions = toolDescriptionsByName(request.tools); + return (0,sentry_trace/* startTracedSpan */.wZ)({ + op: 'gen_ai.invoke_agent', + name: (0,otel/* genAiSpanName */.kj)('invoke_agent', request.agentName), + attributes: { + 'gen_ai.operation.name': 'invoke_agent', + 'gen_ai.provider.name': (0,otel/* genAiProviderName */.Jo)('pi', request.model), + ...(request.agentName ? { 'gen_ai.agent.name': request.agentName } : {}), + ...(request.task ? { 'warden.ai.task': request.task } : {}), + ...(request.model ? { 'gen_ai.request.model': request.model } : {}), + ...(request.maxTokens !== undefined ? { 'gen_ai.request.max_tokens': request.maxTokens } : {}), + 'gen_ai.output.type': 'json', + }, + }, async (span) => { + (0,otel/* setGenAiSystemInstructionsAttr */.kq)(span, systemPrompt); + (0,otel/* setGenAiInputMessagesAttr */.uQ)(span, [{ role: 'user', content: request.prompt }]); + try { + const run = await runPiPrompt({ + cwd: process.cwd(), + systemPrompt, + userPrompt: request.prompt, + agentName: request.agentName, + model: request.model, + effort: request.effort, + legacyAnthropicApiKey: request.apiKey, + toolNames, + customTools, + toolDescriptions, + maxTurns: request.maxIterations, + maxTokens: request.maxTokens, + maxRetries: request.maxRetries, + timeout: request.timeout, + parentSpan: span, + }); + const result = normalizePiResult(run, request.maxTokens); + if (!result) { + span.setAttribute('error.type', 'missing_response'); + return { success: false, error: 'Pi runtime returned no response', usage: run.usage }; + } + if (run.lastAssistant?.provider) { + span.setAttribute('gen_ai.provider.name', run.lastAssistant.provider); + } + (0,otel/* setGenAiUsageAttrs */.qk)(span, result.usage); + if (result.responseId) { + span.setAttribute('gen_ai.response.id', result.responseId); + } + if (result.responseModel) { + span.setAttribute('gen_ai.response.model', result.responseModel); + } + span.setAttribute('gen_ai.response.finish_reasons', [run.lastAssistant?.stopReason ?? result.status]); + (0,otel/* setGenAiOutputMessagesAttr */.hX)(span, result.text, run.lastAssistant?.stopReason ?? result.status); + if (result.status !== 'success') { + span.setAttribute('error.type', result.status); + return { + success: false, + error: result.errors.join('; ') || `Pi runtime execution failed: ${result.status}`, + usage: result.usage, + }; + } + const json = (0,haiku/* extractJson */.eg)(result.text); + if (!json) { + span.setAttribute('error.type', 'invalid_json'); + return { success: false, error: 'No JSON found in response', usage: result.usage }; + } + const parsed = JSON.parse(json); + const validated = request.schema.safeParse(parsed); + if (!validated.success) { + span.setAttribute('error.type', 'validation_error'); + return { success: false, error: `Validation failed: ${validated.error.message}`, usage: result.usage }; + } + return { success: true, data: validated.data, usage: result.usage }; + } + catch (error) { + span.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + return { success: false, error: errorMessage(error), usage: (0,usage/* emptyUsage */.ly)() }; + } + }); +} +const piRuntime = { + name: 'pi', + async runSkill(request) { + const { systemPrompt, userPrompt, repoPath, apiKey, options, skillName, tools, allowMutatingTools, } = request; + const { maxTurns = 50, model, effort, abortController } = options; + const skillTools = resolvePiSkillTools(tools, allowMutatingTools); + return (0,sentry_trace/* startTracedSpan */.wZ)({ + op: 'gen_ai.invoke_agent', + name: (0,otel/* genAiSpanName */.kj)('invoke_agent', skillName), + ...(request.parentSpan ? { parentSpan: request.parentSpan } : {}), + attributes: { + 'gen_ai.operation.name': 'invoke_agent', + 'gen_ai.provider.name': (0,otel/* genAiProviderName */.Jo)('pi', model), + 'gen_ai.agent.name': skillName, + ...(model ? { 'gen_ai.request.model': model } : {}), + 'warden.request.max_turns': maxTurns, + }, + }, async (span) => { + (0,otel/* setGenAiSystemInstructionsAttr */.kq)(span, systemPrompt); + (0,otel/* setGenAiInputMessagesAttr */.uQ)(span, [{ role: 'user', content: userPrompt }]); + try { + const run = await runPiPrompt({ + cwd: repoPath, + skillRoot: request.skillRoot, + systemPrompt, + userPrompt, + agentName: skillName, + model, + legacyAnthropicApiKey: apiKey, + toolNames: skillTools.toolNames, + maxTurns, + effort, + maxRetries: PI_SKILL_PROVIDER_MAX_RETRIES, + abortController, + parentSpan: span, + traceRecorder: request.traceRecorder, + }); + run.warnings.unshift(...skillTools.warnings); + const result = normalizePiResult(run); + if (result) { + if (run.lastAssistant?.provider) { + span.setAttribute('gen_ai.provider.name', run.lastAssistant.provider); + } + (0,otel/* setGenAiUsageAttrs */.qk)(span, result.usage); + if (result.responseId) { + span.setAttribute('gen_ai.response.id', result.responseId); + } + if (result.responseModel) { + span.setAttribute('gen_ai.response.model', result.responseModel); + } + span.setAttribute('gen_ai.response.finish_reasons', [run.lastAssistant?.stopReason ?? result.status]); + if (result.text) { + (0,otel/* setGenAiOutputMessagesAttr */.hX)(span, result.text, run.lastAssistant?.stopReason ?? result.status); + } + if (result.status !== 'success') { + span.setAttribute('error.type', result.status); + } + if (result.sessionId) { + span.setAttribute('gen_ai.conversation.id', result.sessionId); + } + if (result.durationMs !== undefined) { + span.setAttribute('warden.sdk.duration_ms', result.durationMs); + } + if (result.numTurns !== undefined) { + span.setAttribute('warden.sdk.num_turns', result.numTurns); + } + } + return { + result, + stderr: run.warnings.join('\n') || undefined, + }; + } + catch (error) { + const message = errorMessage(error); + if ((0,errors/* isAuthenticationErrorMessage */.Ip)(message)) { + span.setAttribute('error.type', 'auth_error'); + return { authError: message }; + } + span.setAttribute('error.type', error instanceof Error ? error.name : '_OTHER'); + throw error; + } + }, request.traceRecorder); + }, + async runAuxiliary(request) { + return runStructured({ kind: 'auxiliary', ...request }); + }, + async runSynthesis(request) { + return runStructured({ kind: 'synthesis', ...request }); + }, +}; + + +/***/ }), + +/***/ 44759: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ RL: () => (/* binding */ aggregateAuxiliaryUsage), +/* harmony export */ UN: () => (/* binding */ aggregateAuxiliaryUsageAttribution), +/* harmony export */ X5: () => (/* binding */ resolveResponseModel), +/* harmony export */ Z$: () => (/* binding */ aggregateUsage), +/* harmony export */ bP: () => (/* binding */ estimateTokens), +/* harmony export */ f5: () => (/* binding */ extractUsage), +/* harmony export */ ly: () => (/* binding */ emptyUsage), +/* harmony export */ vd: () => (/* binding */ mergeAuxiliaryUsageAttribution), +/* harmony export */ wV: () => (/* binding */ mergeAuxiliaryUsage) +/* harmony export */ }); +/** + * Extract usage stats from a runtime result message. + * + * The Anthropic API reports `input_tokens` as only the non-cached portion. + * We normalize so that `inputTokens` is the total input token count + * (non-cached + cache_read + cache_creation), with cache fields reported + * separately as subsets of that total. + */ +function extractUsage(result) { + const usage = result.usage; + const rawInput = usage?.input_tokens ?? 0; + const cacheRead = usage?.cache_read_input_tokens ?? 0; + const rawCacheCreation = usage?.cache_creation_input_tokens ?? 0; + const cacheCreation1h = usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0; + const tieredCacheCreation5m = usage?.cache_creation?.ephemeral_5m_input_tokens ?? 0; + const hasTieredCacheCreation = usage?.cache_creation !== undefined && usage.cache_creation !== null; + const tieredCacheCreation = tieredCacheCreation5m + cacheCreation1h; + const cacheCreation = Math.max(rawCacheCreation, tieredCacheCreation); + const cacheCreation5m = hasTieredCacheCreation ? tieredCacheCreation5m : rawCacheCreation; + return { + inputTokens: rawInput + cacheRead + cacheCreation, + outputTokens: usage?.output_tokens ?? 0, + cacheReadInputTokens: cacheRead, + cacheCreationInputTokens: cacheCreation, + cacheCreation5mInputTokens: cacheCreation5m, + cacheCreation1hInputTokens: cacheCreation1h, + webSearchRequests: usage?.server_tool_use?.web_search_requests ?? 0, + costUSD: result.total_cost_usd ?? 0, + }; +} +/** + * Create empty usage stats. + */ +function emptyUsage() { + return { + inputTokens: 0, + outputTokens: 0, + cacheReadInputTokens: 0, + cacheCreationInputTokens: 0, + cacheCreation5mInputTokens: 0, + cacheCreation1hInputTokens: 0, + webSearchRequests: 0, + costUSD: 0, + }; +} +function addUsage(a, b) { + return { + inputTokens: a.inputTokens + b.inputTokens, + outputTokens: a.outputTokens + b.outputTokens, + cacheReadInputTokens: (a.cacheReadInputTokens ?? 0) + (b.cacheReadInputTokens ?? 0), + cacheCreationInputTokens: (a.cacheCreationInputTokens ?? 0) + (b.cacheCreationInputTokens ?? 0), + cacheCreation5mInputTokens: (a.cacheCreation5mInputTokens ?? 0) + (b.cacheCreation5mInputTokens ?? 0), + cacheCreation1hInputTokens: (a.cacheCreation1hInputTokens ?? 0) + (b.cacheCreation1hInputTokens ?? 0), + webSearchRequests: (a.webSearchRequests ?? 0) + (b.webSearchRequests ?? 0), + costUSD: a.costUSD + b.costUSD, + }; +} +/** + * Aggregate multiple usage stats into one. + */ +function aggregateUsage(usages) { + return usages.reduce(addUsage, emptyUsage()); +} +/** + * Aggregate auxiliary usage entries by agent name. + * Merges multiple entries for the same agent into a single UsageStats. + * Returns undefined if no entries are provided. + */ +function aggregateAuxiliaryUsage(entries) { + if (entries.length === 0) + return undefined; + const map = {}; + for (const { agent, usage } of entries) { + const existing = map[agent]; + if (existing) { + map[agent] = addUsage(existing, usage); + } + else { + map[agent] = { ...usage }; + } + } + return map; +} +function uniqueSorted(values) { + const unique = [...new Set(values.filter((value) => Boolean(value)))].sort(); + return unique.length > 0 ? unique : undefined; +} +/** Collapses a run's observed response models to a single value when they agree, or falls back. */ +function resolveResponseModel(models, fallback) { + const unique = [...new Set(models)]; + return unique.length === 1 ? unique[0] : fallback; +} +function attributionFromEntries(entries) { + const models = uniqueSorted(entries.map((entry) => entry.model)); + const runtimes = uniqueSorted(entries.map((entry) => entry.runtime)); + if (!models && !runtimes) + return undefined; + return { + model: models?.length === 1 ? models[0] : undefined, + models: models && models.length > 1 ? models : undefined, + runtime: runtimes?.length === 1 ? runtimes[0] : undefined, + runtimes: runtimes && runtimes.length > 1 ? runtimes : undefined, + }; +} +function attributionValues(attribution) { + return { + models: [ + ...(attribution?.model ? [attribution.model] : []), + ...(attribution?.models ?? []), + ], + runtimes: [ + ...(attribution?.runtime ? [attribution.runtime] : []), + ...(attribution?.runtimes ?? []), + ], + }; +} +function mergeAttribution(a, b) { + const aValues = attributionValues(a); + const bValues = attributionValues(b); + const models = uniqueSorted([...aValues.models, ...bValues.models]); + const runtimes = uniqueSorted([...aValues.runtimes, ...bValues.runtimes]); + if (!models && !runtimes) + return undefined; + return { + model: models?.length === 1 ? models[0] : undefined, + models: models && models.length > 1 ? models : undefined, + runtime: runtimes?.length === 1 ? runtimes[0] : undefined, + runtimes: runtimes && runtimes.length > 1 ? runtimes : undefined, + }; +} +function normalizeAttributionMap(map) { + if (!map) + return undefined; + const normalized = {}; + for (const [agent, attribution] of Object.entries(map)) { + const next = mergeAttribution(undefined, attribution); + if (next) { + normalized[agent] = next; + } + } + return Object.keys(normalized).length > 0 ? normalized : undefined; +} +/** + * Aggregate auxiliary usage model/runtime attribution by agent name. + */ +function aggregateAuxiliaryUsageAttribution(entries) { + const byAgent = new Map(); + for (const entry of entries) { + const agentEntries = byAgent.get(entry.agent) ?? []; + agentEntries.push(entry); + byAgent.set(entry.agent, agentEntries); + } + const map = {}; + for (const [agent, agentEntries] of byAgent) { + const attribution = attributionFromEntries(agentEntries); + if (attribution) { + map[agent] = attribution; + } + } + return Object.keys(map).length > 0 ? map : undefined; +} +/** + * Merge two auxiliary usage attribution maps. + */ +function mergeAuxiliaryUsageAttribution(a, b) { + const left = normalizeAttributionMap(a); + const right = normalizeAttributionMap(b); + if (!left && !right) + return undefined; + if (!left) + return right; + if (!right) + return left; + const merged = { ...left }; + for (const [agent, attribution] of Object.entries(right)) { + const next = mergeAttribution(merged[agent], attribution); + if (next) { + merged[agent] = next; + } + } + return Object.keys(merged).length > 0 ? merged : undefined; +} +/** + * Merge two AuxiliaryUsageMaps together. + * Entries for the same agent are summed. + */ +function mergeAuxiliaryUsage(a, b) { + if (!a && !b) + return undefined; + if (!a) + return b; + if (!b) + return a; + const entries = []; + for (const [agent, usage] of Object.entries(a)) { + entries.push({ agent, usage }); + } + for (const [agent, usage] of Object.entries(b)) { + entries.push({ agent, usage }); + } + return aggregateAuxiliaryUsage(entries); +} +/** + * Estimate token count from character count. + * Uses chars/4 as a rough approximation for English text. + */ +function estimateTokens(chars) { + return Math.ceil(chars / 4); +} + + +/***/ }), + +/***/ 68016: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ By: () => (/* binding */ startInactiveTracedSpan), +/* harmony export */ gP: () => (/* binding */ withTraceRecorder), +/* harmony export */ hb: () => (/* binding */ recordTracedSpan), +/* harmony export */ qr: () => (/* binding */ startTraceRecorder), +/* harmony export */ w8: () => (/* binding */ getSpanContext), +/* harmony export */ wZ: () => (/* binding */ startTracedSpan) +/* harmony export */ }); +/* harmony import */ var node_async_hooks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16698); +/* harmony import */ var node_async_hooks__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_async_hooks__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _sentry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(30340); + + +const traceRecorderStore = new node_async_hooks__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorage(); +/** Run a callback with a hunk-scoped trace recorder for Warden-created spans. */ +function withTraceRecorder(recorder, callback) { + if (!recorder) + return callback(); + return traceRecorderStore.run(recorder, callback); +} +/** Return the Sentry span context when available. */ +function getSpanContext(span) { + try { + return span?.spanContext?.(); + } + catch { + return undefined; + } +} +function isTraceSpanAttributeValue(value) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return true; + } + return Array.isArray(value) && value.every((item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean'); +} +function compactAttributes(attributes) { + if (!attributes) + return undefined; + const compact = {}; + for (const [key, value] of Object.entries(attributes)) { + if (isTraceSpanAttributeValue(value)) { + compact[key] = value; + } + } + return Object.keys(compact).length > 0 ? compact : undefined; +} +function timestampMs(value) { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 + ? Math.round(value * 1000) + : undefined; +} +function stringValue(value) { + return typeof value === 'string' && value.length > 0 ? value : undefined; +} +function snapshotSpan(span) { + if (!span) + return undefined; + let spanJson; + try { + spanJson = _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.spanToJSON */ .sQ.spanToJSON(span); + } + catch { + return undefined; + } + const traceId = stringValue(spanJson?.trace_id); + const spanId = stringValue(spanJson?.span_id); + if (!traceId || !spanId) + return undefined; + const startTimeUnixMs = timestampMs(spanJson?.start_timestamp); + const endTimeUnixMs = timestampMs(spanJson?.timestamp); + return { + traceId, + spanId, + parentSpanId: stringValue(spanJson?.parent_span_id), + op: stringValue(spanJson?.op), + name: stringValue(spanJson?.description), + startTimeUnixMs, + endTimeUnixMs, + durationMs: startTimeUnixMs !== undefined && endTimeUnixMs !== undefined + ? Math.max(0, endTimeUnixMs - startTimeUnixMs) + : undefined, + status: stringValue(spanJson?.status), + origin: stringValue(spanJson?.origin), + attributes: compactAttributes(spanJson?.data), + }; +} +function descendantsForParent(spans, parentSpanId) { + if (!parentSpanId) + return spans; + const byId = new Map(spans.map((span) => [span.spanId, span])); + return spans.filter((span) => { + let currentParentId = span.parentSpanId; + while (currentParentId) { + if (currentParentId === parentSpanId) + return true; + currentParentId = byId.get(currentParentId)?.parentSpanId; + } + return false; + }); +} +function activeTraceRecorder() { + return traceRecorderStore.getStore(); +} +function hasFinally(value) { + return Boolean(value && typeof value === 'object' && typeof value.finally === 'function'); +} +/** + * Start a real Sentry span and record it in Warden's active hunk trace buffer. + * + * The span still participates in Sentry's distributed trace. The buffer is + * Warden-owned, though, so structured run output only depends on spans we + * explicitly create through this helper. + */ +function startTracedSpan(options, callback, traceRecorder) { + const recorder = traceRecorder ?? activeTraceRecorder(); + let spanRef; + const recordSpan = () => recorder?.record(spanRef); + try { + const result = _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.startSpan */ .sQ.startSpan(options, (span) => { + spanRef = span; + return callback(span); + }); + if (hasFinally(result)) { + return result.finally(recordSpan); + } + recordSpan(); + return result; + } + catch (error) { + recordSpan(); + throw error; + } +} +/** Start an inactive Sentry span that can be ended and recorded manually. */ +function startInactiveTracedSpan(options) { + return _sentry_js__WEBPACK_IMPORTED_MODULE_1__/* .Sentry.startInactiveSpan */ .sQ.startInactiveSpan(options); +} +/** Record a manually-ended span in Warden's active or explicit trace buffer. */ +function recordTracedSpan(span, traceRecorder) { + (traceRecorder ?? activeTraceRecorder())?.record(span); +} +/** Create a hunk-scoped recorder for Warden-owned spans under a Sentry parent span. */ +function startTraceRecorder(parentSpan) { + if (!parentSpan) + return undefined; + const parentContext = getSpanContext(parentSpan); + const buffer = new Map(); + return { + record(span) { + const snapshot = snapshotSpan(span); + if (!snapshot) + return; + if (parentContext?.traceId && snapshot.traceId !== parentContext.traceId) + return; + if (snapshot.spanId === parentContext?.spanId) + return; + buffer.set(snapshot.spanId, snapshot); + }, + snapshot() { + const spans = descendantsForParent([...buffer.values()], parentContext?.spanId); + return spans.length > 0 ? spans : undefined; + }, + }; +} + + +/***/ }), + +/***/ 30340: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ B4: () => (/* binding */ emitActionRunMetric), +/* harmony export */ E1: () => (/* binding */ emitFixEvalVerdictMetric), +/* harmony export */ G_: () => (/* binding */ ensureLocalTracing), +/* harmony export */ KR: () => (/* binding */ flushSentry), +/* harmony export */ LW: () => (/* binding */ emitRunMetric), +/* harmony export */ Zn: () => (/* binding */ emitDedupMetrics), +/* harmony export */ fL: () => (/* binding */ emitStaleResolutionMetric), +/* harmony export */ gs: () => (/* binding */ setGitHubActionScope), +/* harmony export */ ig: () => (/* binding */ initSentry), +/* harmony export */ ii: () => (/* binding */ emitFixEvalMetrics), +/* harmony export */ m0: () => (/* binding */ emitRetryMetric), +/* harmony export */ s7: () => (/* binding */ emitSkillMetrics), +/* harmony export */ sQ: () => (/* reexport module object */ _sentry_node__WEBPACK_IMPORTED_MODULE_10__), +/* harmony export */ vF: () => (/* binding */ logger), +/* harmony export */ vx: () => (/* binding */ setRepositoryScope), +/* harmony export */ yI: () => (/* binding */ emitExtractionMetrics) +/* harmony export */ }); +/* unused harmony exports setGlobalAttributes, getTraceId */ +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11825); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9604); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(49042); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(15082); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(78471); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(68724); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(15414); +/* harmony import */ var _sentry_node__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(96048); +/* harmony import */ var _types_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78481); +/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(82272); +/* harmony import */ var _sdk_otel_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(85884); +/* harmony import */ var _sdk_pricing_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(64602); + + + + + +let initialized = false; +function getGitHubServerUrl() { + const serverUrl = process.env['GITHUB_SERVER_URL'] || 'https://github.com'; + return serverUrl.replace(/\/+$/, ''); +} +function repositoryAttributes(repository) { + const [owner, name] = repository.split('/'); + const attrs = name + ? { + 'vcs.owner.name': owner ?? '', + 'vcs.repository.name': name, + } + : { + 'vcs.repository.name': repository, + }; + if (owner && name && owner !== 'local') { + attrs['vcs.provider.name'] = 'github'; + attrs['vcs.repository.url.full'] = `${getGitHubServerUrl()}/${owner}/${name}`; + } + return attrs; +} +/** Initialize production telemetry, with optional SDK hooks for local observation. */ +function initSentry(context, options = {}) { + const dsn = process.env['WARDEN_SENTRY_DSN']; + if (!dsn || initialized) + return; + initialized = true; + _sentry_node__WEBPACK_IMPORTED_MODULE_4__/* .init */ .Ts({ + dsn, + release: `warden@${(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getVersion */ .HF)()}`, + environment: context === 'action' ? 'github-action' : 'cli', + tracesSampleRate: 1.0, + enableLogs: true, + ...options, + integrations: [ + _sentry_node__WEBPACK_IMPORTED_MODULE_5__/* .consoleLoggingIntegration */ .d({ levels: ['warn', 'error'] }), + _sentry_node__WEBPACK_IMPORTED_MODULE_6__/* .anthropicAIIntegration */ .v({ recordInputs: true, recordOutputs: true }), + _sentry_node__WEBPACK_IMPORTED_MODULE_7__/* .httpIntegration */ .X(), + ], + }); + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('service.version', (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__/* .getVersion */ .HF)()); + _sentry_node__WEBPACK_IMPORTED_MODULE_9__/* .getGlobalScope */ .m6().setAttributes({ + 'warden.source': context === 'action' ? 'github-action' : 'cli', + }); +} +/** Ensure local span objects are materialized for structured trace output. */ +function ensureLocalTracing() { + if (_sentry_node__WEBPACK_IMPORTED_MODULE_9__/* .getClient */ .KU()) + return; + _sentry_node__WEBPACK_IMPORTED_MODULE_4__/* .init */ .Ts({ + tracesSampleRate: 1.0, + transport: () => ({ + send: async () => ({}), + flush: async () => true, + }), + }); +} + +const { logger } = _sentry_node__WEBPACK_IMPORTED_MODULE_10__; +/** + * Set attributes on the global Sentry scope. + * These apply to logs and metrics. Pass them explicitly when starting spans. + */ +function setGlobalAttributes(attrs) { + if (!initialized) + return; + try { + _sentry_node__WEBPACK_IMPORTED_MODULE_9__/* .getGlobalScope */ .m6().setAttributes(attrs); + } + catch { + // Never break the workflow + } +} +/** + * Set repository metadata on the global Sentry scope. + */ +function setRepositoryScope(repository) { + if (!repository || !initialized) + return; + const attrs = repositoryAttributes(repository); + try { + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('repository', repository); + } + catch { + // Never break the workflow + } + setGlobalAttributes(attrs); +} +/** + * Set GitHub Actions metadata on the global Sentry scope and return the + * attributes that must be passed explicitly to the action's root span. + */ +function setGitHubActionScope(eventName) { + const repository = process.env['GITHUB_REPOSITORY']; + const runId = process.env['GITHUB_RUN_ID']; + const serverUrl = getGitHubServerUrl(); + const attrs = {}; + if (repository) + Object.assign(attrs, repositoryAttributes(repository)); + if (eventName) { + attrs['github.event.name'] = eventName; + } + if (process.env['GITHUB_WORKFLOW']) { + attrs['cicd.pipeline.name'] = process.env['GITHUB_WORKFLOW']; + } + if (runId) { + attrs['cicd.pipeline.run.id'] = runId; + } + if (repository && runId) { + attrs['cicd.pipeline.run.url.full'] = `${serverUrl}/${repository}/actions/runs/${runId}`; + } + if (process.env['GITHUB_JOB']) { + attrs['cicd.pipeline.task.name'] = process.env['GITHUB_JOB']; + } + if (!initialized) + return attrs; + setGlobalAttributes(attrs); + try { + if (repository) + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('repository', repository); + if (eventName) + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('github.event.name', eventName); + if (process.env['GITHUB_WORKFLOW']) { + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('cicd.pipeline.name', process.env['GITHUB_WORKFLOW']); + } + if (runId) + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('cicd.pipeline.run.id', runId); + if (process.env['GITHUB_JOB']) { + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setTag */ .NA('cicd.pipeline.task.name', process.env['GITHUB_JOB']); + } + _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .setContext */ .o('github_actions', { + repository, + event: eventName, + workflow: process.env['GITHUB_WORKFLOW'], + job: process.env['GITHUB_JOB'], + run_id: runId, + run_attempt: process.env['GITHUB_RUN_ATTEMPT'], + run_url: repository && runId ? `${serverUrl}/${repository}/actions/runs/${runId}` : undefined, + ref: process.env['GITHUB_REF'], + sha: process.env['GITHUB_SHA'], + }); + } + catch { + // Never break the workflow + } + return attrs; +} +/** + * Get the trace ID from the active span, if available. + * Useful for correlating runs to Sentry traces in logs and output. + */ +function getTraceId() { + if (!initialized) + return undefined; + try { + return Sentry.getActiveSpan()?.spanContext().traceId; + } + catch { + return undefined; + } +} +/** + * Run a metrics callback only when Sentry is initialized. + * Swallows errors so metrics never break the main workflow. + */ +function safeEmit(fn) { + if (!initialized) + return; + try { + fn(); + } + catch { + // Metrics emission should never break the main workflow + } +} +/** + * Build agent-scoped metric attributes that match span attribute names. + */ +function agentMetricAttributes(skill, model, runtime) { + const attrs = { 'gen_ai.agent.name': skill }; + if (model) { + attrs['gen_ai.request.model'] = model; + } + if (runtime) { + attrs['warden.runtime.name'] = runtime; + } + return attrs; +} +function usageTokenComponents(usage) { + if (!usage) + return []; + const cacheReadInputTokens = usage.cacheReadInputTokens ?? 0; + const cacheCreation5mInputTokens = usage.cacheCreation5mInputTokens ?? 0; + const cacheCreation1hInputTokens = usage.cacheCreation1hInputTokens ?? 0; + const cacheCreationInputTokens = Math.max(usage.cacheCreationInputTokens ?? 0, cacheCreation5mInputTokens + cacheCreation1hInputTokens); + const categorizedCacheCreationInputTokens = cacheCreation5mInputTokens + cacheCreation1hInputTokens; + const uncategorizedCacheCreationInputTokens = Math.max(0, cacheCreationInputTokens - categorizedCacheCreationInputTokens); + const standardInputTokens = Math.max(0, usage.inputTokens - cacheReadInputTokens - cacheCreationInputTokens); + return [ + { category: 'standard_input', tokens: standardInputTokens }, + { category: 'cache_read_input', tokens: cacheReadInputTokens }, + { + category: 'cache_creation_5m_input', + tokens: cacheCreation5mInputTokens + uncategorizedCacheCreationInputTokens, + }, + { category: 'cache_creation_1h_input', tokens: cacheCreation1hInputTokens }, + { category: 'output', tokens: usage.outputTokens }, + ]; +} +function emitUsageComponentMetrics(attrs, usage) { + for (const { category, tokens } of usageTokenComponents(usage)) { + if (tokens <= 0) + continue; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.gen_ai.token.usage', tokens, { + unit: '{token}', + attributes: { ...attrs, 'warden.gen_ai.token.category': category }, + }); + } +} +function emitCostComponentMetrics(attrs, model, usage) { + if (!usage) + return; + const breakdown = (0,_sdk_pricing_js__WEBPACK_IMPORTED_MODULE_3__/* .estimateUsageCostBreakdown */ .MG)(model, usage); + if (!breakdown) + return; + const components = [ + { component: 'standard_input', costUSD: breakdown.freshInputUSD }, + { component: 'cache_read_input', costUSD: breakdown.cacheReadUSD }, + { component: 'cache_creation_5m_input', costUSD: breakdown.cacheCreationUSD + breakdown.cacheCreation5mUSD }, + { component: 'cache_creation_1h_input', costUSD: breakdown.cacheCreation1hUSD }, + { component: 'output', costUSD: breakdown.outputUSD }, + { component: 'web_search', costUSD: breakdown.webSearchUSD }, + ]; + for (const { component, costUSD } of components) { + if (costUSD <= 0) + continue; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.gen_ai.cost.component.usd', costUSD, { + attributes: { ...attrs, 'warden.gen_ai.cost.component': component }, + }); + } +} +/** + * Emit a single run count. Call once per analysis workflow execution. + * Inherits warden.source, repository, and GitHub Actions attributes from global scope. + */ +function emitRunMetric() { + safeEmit(() => { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.workflow.runs', 1); + }); +} +/** Emit the final outcome of a GitHub Action invocation, including startup failures. */ +function emitActionRunMetric(outcome, stage, errorCode) { + safeEmit(() => { + const attrs = { + 'warden.action.outcome': outcome, + 'warden.action.stage': stage, + }; + if (errorCode) + attrs['warden.error.code'] = errorCode; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.action.runs', 1, { attributes: attrs }); + }); +} +function emitSkillMetrics(report) { + safeEmit(() => { + const attrs = agentMetricAttributes(report.skill, report.model, report.runtime); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.skill.duration', report.durationMs ?? 0, { + unit: 'millisecond', + attributes: attrs, + }); + if (report.usage) { + const tokenAttrs = { + ...attrs, + 'gen_ai.operation.name': 'invoke_agent', + 'gen_ai.provider.name': (0,_sdk_otel_js__WEBPACK_IMPORTED_MODULE_2__/* .genAiProviderName */ .Jo)(report.runtime, report.model), + }; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('gen_ai.client.token.usage', report.usage.inputTokens, { + unit: '{token}', + attributes: { ...tokenAttrs, 'gen_ai.token.type': 'input' }, + }); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('gen_ai.client.token.usage', report.usage.outputTokens, { + unit: '{token}', + attributes: { ...tokenAttrs, 'gen_ai.token.type': 'output' }, + }); + emitUsageComponentMetrics(tokenAttrs, report.usage); + emitCostComponentMetrics(attrs, report.model, report.usage); + if (report.usage.costUSD) { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.gen_ai.cost.usd', report.usage.costUSD, { attributes: attrs }); + } + } + for (const severity of Object.keys(_types_index_js__WEBPACK_IMPORTED_MODULE_0__/* .SEVERITY_ORDER */ .B)) { + const count = report.findings.filter((f) => f.severity === severity).length; + if (count > 0) { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.findings', count, { + attributes: { ...attrs, 'warden.finding.severity': severity }, + }); + } + } + }); +} +function emitExtractionMetrics(skill, method, count) { + safeEmit(() => { + const attrs = { ...agentMetricAttributes(skill), 'warden.extraction.method': method }; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.extraction.attempts', 1, { attributes: attrs }); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.extraction.findings', count, { attributes: attrs }); + }); +} +function emitFixEvalMetrics(evaluated, resolved, failed, skipped, uniqueFindingsEvaluated, uniqueFindingsCodeChanged, uniqueFindingsResolved) { + safeEmit(() => { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.evaluated', evaluated); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.resolved', resolved); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.failed', failed); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.skipped', skipped); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.unique_findings.evaluated', uniqueFindingsEvaluated); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.unique_findings.code_changed', uniqueFindingsCodeChanged); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.unique_findings.resolved', uniqueFindingsResolved); + }); +} +function emitRetryMetric(skill, attempt) { + safeEmit(() => { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.skill.retries', 1, { + attributes: { ...agentMetricAttributes(skill), 'warden.retry.attempt': attempt }, + }); + }); +} +function emitDedupMetrics(skill, total, unique) { + safeEmit(() => { + const attrs = agentMetricAttributes(skill); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.dedup.total', total, { attributes: attrs }); + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.dedup.unique', unique, { attributes: attrs }); + if (total > 0) { + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.distribution('warden.dedup.removed', total - unique, { attributes: attrs }); + } + }); +} +/** + * Emit the final fix-evaluation outcome for one comment. + */ +function emitFixEvalVerdictMetric(verdict, skill, options = {}) { + safeEmit(() => { + const attrs = { 'warden.fix_eval.verdict': verdict }; + if (options.usedFallback !== undefined) { + attrs['warden.fix_eval.used_fallback'] = options.usedFallback; + } + if (skill) { + Object.assign(attrs, agentMetricAttributes(skill)); + } + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.fix_eval.verdict', 1, { attributes: attrs }); + }); +} +function emitStaleResolutionMetric(count, skill) { + safeEmit(() => { + const attrs = skill ? agentMetricAttributes(skill) : undefined; + _sentry_node__WEBPACK_IMPORTED_MODULE_11__.count('warden.stale.resolved', count, attrs ? { attributes: attrs } : undefined); + }); +} +/** + * Flush pending Sentry events. Safe to call even if Sentry is not initialized. + */ +async function flushSentry(timeoutMs = 30_000) { + if (!initialized) + return true; + try { + return await _sentry_node__WEBPACK_IMPORTED_MODULE_8__/* .flush */ .bX(timeoutMs); + } + catch { + // Sentry flush failure should not prevent normal operation + return false; + } +} + + +/***/ }), + +/***/ 18771: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ SKILL_RESOURCE_DIRECTORIES) +/* harmony export */ }); +/** Resource directories exposed by a resolved skill, excluding neighboring files. */ +const SKILL_RESOURCE_DIRECTORIES = ['scripts', 'references', 'assets']; + + +/***/ }), + +/***/ 78481: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $3: () => (/* binding */ FixStatusSchema), +/* harmony export */ AU: () => (/* binding */ SkippedFileSchema), +/* harmony export */ B: () => (/* binding */ SEVERITY_ORDER), +/* harmony export */ HA: () => (/* binding */ ConfidenceThresholdSchema), +/* harmony export */ IH: () => (/* binding */ VerifierRejectionsSchema), +/* harmony export */ J1: () => (/* binding */ SkillErrorSchema), +/* harmony export */ Lx: () => (/* binding */ compareFindingPriority), +/* harmony export */ Ne: () => (/* binding */ HunkTraceSchema), +/* harmony export */ Ni: () => (/* binding */ filterFindings), +/* harmony export */ Ot: () => (/* binding */ SourceSnippetSchema), +/* harmony export */ Rc: () => (/* binding */ SeveritySchema), +/* harmony export */ TH: () => (/* binding */ LocationSchema), +/* harmony export */ Ur: () => (/* binding */ UsageStatsSchema), +/* harmony export */ Xp: () => (/* binding */ HunkGateSchema), +/* harmony export */ _0: () => (/* binding */ AuxiliaryUsageAttributionMapSchema), +/* harmony export */ bN: () => (/* binding */ GitHubEventTypeSchema), +/* harmony export */ gD: () => (/* binding */ IncrementalReviewSchema), +/* harmony export */ hA: () => (/* binding */ EventContextSchema), +/* harmony export */ kV: () => (/* binding */ countPatchChunks), +/* harmony export */ m3: () => (/* binding */ ConfidenceSchema), +/* harmony export */ mC: () => (/* binding */ findingLine), +/* harmony export */ nE: () => (/* binding */ isExtractionErrorCode), +/* harmony export */ o2: () => (/* binding */ UsageAttributionSchema), +/* harmony export */ p_: () => (/* binding */ FindingSchema), +/* harmony export */ q$: () => (/* binding */ SeverityThresholdSchema), +/* harmony export */ r6: () => (/* binding */ SkillReportSchema), +/* harmony export */ se: () => (/* binding */ HunkFailureSchema), +/* harmony export */ xb: () => (/* binding */ AuxiliaryUsageMapSchema) +/* harmony export */ }); +/* unused harmony exports normalizeSeverity, CONFIDENCE_ORDER, filterFindingsBySeverity, filterFindingsByConfidence, SourceSnippetLineSchema, FileReportSchema, ErrorCodeSchema, TraceSpanSchema, CarriedHunkRangeSchema, PullRequestActionSchema, FileChangeSchema, DiffContextSourceSchema, PullRequestContextSchema, RepositoryContextSchema, RetryConfigSchema */ +/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51737); + +/** + * Normalize legacy severity values to the 3-level scale. + * Maps 'critical' → 'high' and 'info' → 'low' for backwards compatibility + * with old JSONL logs and LLM responses. + */ +function normalizeSeverity(val) { + if (val === 'critical') + return 'high'; + if (val === 'info') + return 'low'; + return val; +} +// Severity levels for findings +const SeveritySchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .preprocess */ .vkY(normalizeSeverity, zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['high', 'medium', 'low'])); +// Confidence levels for findings +const ConfidenceSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['high', 'medium', 'low']); +/** + * Confidence order for comparison (lower = more confident). + * Single source of truth for confidence ordering across the codebase. + */ +const CONFIDENCE_ORDER = { + high: 0, + medium: 1, + low: 2, +}; +// Severity threshold for config options (includes 'off' to disable) +const SeverityThresholdSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .preprocess */ .vkY(normalizeSeverity, zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['off', 'high', 'medium', 'low'])); +// Confidence threshold for config options (includes 'off' to disable filtering) +const ConfidenceThresholdSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['off', 'high', 'medium', 'low']); +/** + * Severity order for comparison (lower = more severe). + * Single source of truth for severity ordering across the codebase. + */ +const SEVERITY_ORDER = { + high: 0, + medium: 1, + low: 2, +}; +/** + * Filter findings to only include those at or above the given severity threshold. + * If no threshold is provided, returns all findings unchanged. + * If threshold is 'off', returns empty array (disabled). + */ +function filterFindingsBySeverity(findings, threshold) { + if (!threshold) + return findings; + if (threshold === 'off') + return []; + const thresholdOrder = SEVERITY_ORDER[threshold]; + return findings.filter((f) => SEVERITY_ORDER[f.severity] <= thresholdOrder); +} +/** + * Filter findings to only include those at or above the given confidence threshold. + * If no threshold is provided or threshold is 'off', returns all findings unchanged. + * Findings without a confidence field are always included (backwards compat). + */ +function filterFindingsByConfidence(findings, threshold) { + if (!threshold || threshold === 'off') + return findings; + const thresholdOrder = CONFIDENCE_ORDER[threshold]; + return findings.filter((f) => { + if (!f.confidence) + return true; + return CONFIDENCE_ORDER[f.confidence] <= thresholdOrder; + }); +} +/** + * Filter findings by both severity and confidence thresholds. + * Applies severity filtering first, then confidence filtering. + * Either threshold can be omitted to skip that filter. + */ +function filterFindings(findings, reportOn, minConfidence) { + return filterFindingsByConfidence(filterFindingsBySeverity(findings, reportOn), minConfidence); +} +// Location within a file +const LocationSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + path: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + startLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + endLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive().optional(), +}); +const SourceSnippetLineSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + line: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + content: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + highlighted: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY().optional(), +}); +const SourceSnippetSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + path: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + language: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + startLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + endLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + targetStartLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + targetEndLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + lines: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(SourceSnippetLineSchema), +}); +// Individual finding from a skill +const FindingSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + id: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + severity: SeveritySchema, + confidence: ConfidenceSchema.optional(), + title: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + description: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + verification: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + location: LocationSchema.optional(), + additionalLocations: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(LocationSchema).optional(), + sourceSnippet: SourceSnippetSchema.optional(), + elapsedMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), +}); +/** + * Get the effective line number for a finding (endLine if present, otherwise startLine). + */ +function findingLine(f) { + return f.location?.endLine ?? f.location?.startLine ?? 0; +} +/** + * Compare two findings by priority for winner selection. + * Lower return value = higher priority (more severe, more confident, earlier path/line). + */ +function compareFindingPriority(a, b) { + const sevDiff = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]; + if (sevDiff !== 0) + return sevDiff; + const confA = CONFIDENCE_ORDER[a.confidence ?? 'low']; + const confB = CONFIDENCE_ORDER[b.confidence ?? 'low']; + const confDiff = confA - confB; + if (confDiff !== 0) + return confDiff; + const pathCmp = (a.location?.path ?? '').localeCompare(b.location?.path ?? ''); + if (pathCmp !== 0) + return pathCmp; + return findingLine(a) - findingLine(b); +} +// Usage statistics normalized from runtime/provider responses. +// inputTokens is total input, including cache-read and cache-created subsets. +const UsageStatsSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + inputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + outputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + cacheReadInputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + cacheCreationInputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + cacheCreation5mInputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + cacheCreation1hInputTokens: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + webSearchRequests: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + costUSD: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative(), +}); +const UsageAttributionSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + model: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + models: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP()).optional(), + runtime: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + runtimes: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP()).optional(), +}); +// Auxiliary usage from non-SDK LLM calls (extraction repair, semantic dedup, etc.) +const AuxiliaryUsageMapSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .record */ .g1P(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), UsageStatsSchema); +const AuxiliaryUsageAttributionMapSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .record */ .g1P(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), UsageAttributionSchema); +// Skipped file info for scan policy, ignore policy, and chunking. +const SkippedFileSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + filename: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + reason: zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n([ + 'pattern', + 'builtin', + 'ignored:builtin', + 'ignored:user', + 'ignored:generated', + 'limit:file_size', + 'limit:file_lines', + 'limit:file_read', + 'limit:file_count', + 'limit:changed_lines', + 'limit:missing_patch', + ]), + pattern: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), +}); +// Per-file report within a skill. `findings` is a count; the per-skill +// record uses the same name for the findings array. This matches the +// JSONL contract (see specs/jsonl-examples.jsonl). +// +// IMPORTANT: breaking on-disk JSONL log formats is NEVER ALLOWED. Old +// `.warden/logs/*.jsonl` files must always parse. The schema may evolve +// (add fields, normalize values) but readers must accept all historical +// shapes — convert legacy fields via preprocess/transform here, never by +// asking users to delete old logs. The preprocess below maps the legacy +// `findingCount` field (used pre-rename) into `findings`. +const FileReportSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .preprocess */ .vkY((val) => { + if (val && typeof val === 'object' && !Array.isArray(val)) { + const obj = val; + if ('findingCount' in obj && !('findings' in obj)) { + const { findingCount, ...rest } = obj; + return { ...rest, findings: findingCount }; + } + } + return val; +}, zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + filename: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + findings: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + durationMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + usage: UsageStatsSchema.optional(), +})); +// Stable codes for run failures. Public contract: add new codes, do not rename. +const ErrorCodeSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n([ + 'auth_failed', + 'provider_unavailable', + 'sdk_error', + 'subprocess_failure', + 'max_turns', + 'aborted', + 'all_hunks_failed', + 'invalid_model_selector', + 'skill_resolution_failed', + 'extraction_invalid_json', + 'extraction_unbalanced_json', + 'extraction_no_findings_json', + 'extraction_missing_findings_key', + 'extraction_findings_not_array', + 'extraction_llm_failed', + 'extraction_llm_timeout', + 'extraction_no_api_key', + 'unknown', +]); +const EXTRACTION_ERROR_CODES = new Set([ + 'extraction_invalid_json', + 'extraction_unbalanced_json', + 'extraction_no_findings_json', + 'extraction_missing_findings_key', + 'extraction_findings_not_array', + 'extraction_llm_failed', + 'extraction_llm_timeout', + 'extraction_no_api_key', +]); +function isExtractionErrorCode(code) { + return EXTRACTION_ERROR_CODES.has(code); +} +const SkillErrorSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + code: ErrorCodeSchema, + message: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + timestamp: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().datetime().optional(), +}); +const VerifierRejectionsSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + count: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + reasons: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP()), +}); +// 'analysis' = SDK/auth/abort failure, 'extraction' = parse-tier failure. +const HunkFailureSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + type: zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['analysis', 'extraction']), + filename: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + lineRange: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + code: ErrorCodeSchema, + message: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + preview: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + attempts: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), +}); +const TraceSpanAttributeValueSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .union */ .KCZ([ + zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig(), + zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY(), + zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(zod__WEBPACK_IMPORTED_MODULE_0__/* .union */ .KCZ([zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig(), zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY()])), +]); +const TraceSpanSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + traceId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + spanId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + parentSpanId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + op: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + name: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + startTimeUnixMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + endTimeUnixMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + durationMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + status: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + origin: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + attributes: zod__WEBPACK_IMPORTED_MODULE_0__/* .record */ .g1P(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), TraceSpanAttributeValueSchema).optional(), +}); +// Optional per-hunk runtime trace captured in structured run output. +const HunkTraceSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + filename: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + lineRange: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + runtime: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + status: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + traceId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + spanId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + responseId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + responseModel: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + sessionId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + durationMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + durationApiMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + numTurns: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + spans: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(TraceSpanSchema).optional(), +}); +// Skill report output +/** Hunks a skill's deterministic gate kept from the model. */ +const HunkGateSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + /** Hunks dropped because no gate signal matched. */ + skippedHunks: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + /** True when only the hunks touched by the triggering push were eligible. */ + pushScoped: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY(), +}); +/** New-side line range of a hunk that incremental review carried forward unchanged. */ +const CarriedHunkRangeSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + path: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + startLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int(), + endLine: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int(), +}); +/** Incremental review state for one skill run on a pull request. */ +const IncrementalReviewSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + /** Check run external_id that marks this run as a reusable baseline. */ + externalId: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + /** Head SHA of the earlier run whose reviewed hunks were reused, if any. */ + baselineSha: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + /** Hunks skipped because the baseline already reviewed identical content. */ + carriedRanges: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(CarriedHunkRangeSchema), + /** Whether every hunk given to the skill was reviewed, so this run can serve as a baseline. */ + complete: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY(), +}); +const SkillReportSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + skill: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + summary: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + findings: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(FindingSchema), + metadata: zod__WEBPACK_IMPORTED_MODULE_0__/* .record */ .g1P(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), zod__WEBPACK_IMPORTED_MODULE_0__/* .unknown */ .L5J()).optional(), + durationMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().nonnegative().optional(), + usage: UsageStatsSchema.optional(), + /** Files that were skipped due to chunking patterns */ + skippedFiles: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(SkippedFileSchema).optional(), + /** Hunks a skill's deterministic gate kept from the model. */ + hunkGate: HunkGateSchema.optional(), + /** Number of hunks that failed to analyze (SDK errors, API errors, etc.) */ + failedHunks: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + /** Number of hunks where findings extraction failed (JSON parse errors) */ + failedExtractions: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), + /** Per-hunk failure details, in execution order. */ + hunkFailures: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(HunkFailureSchema).optional(), + /** Optional per-hunk runtime traces, only captured when explicitly requested. */ + traces: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(HunkTraceSchema).optional(), + /** Set when the run cannot complete normally. */ + error: SkillErrorSchema.optional(), + /** Findings the verification pass rejected, if any ran. */ + verifierRejections: VerifierRejectionsSchema.optional(), + /** Usage from auxiliary LLM calls (extraction repair, semantic dedup, etc.) */ + auxiliaryUsage: AuxiliaryUsageMapSchema.optional(), + /** Model/runtime attribution for auxiliary LLM usage, keyed like auxiliaryUsage */ + auxiliaryUsageAttribution: AuxiliaryUsageAttributionMapSchema.optional(), + /** Per-file breakdown of findings, timing, and usage */ + files: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(FileReportSchema).optional(), + /** Model used for this skill's analysis */ + model: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + /** Runtime backend used for this skill's analysis. */ + runtime: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + /** Present when the action ran with incremental review enabled. */ + incremental: IncrementalReviewSchema.optional(), +}); +// GitHub event types +const GitHubEventTypeSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n([ + 'pull_request', + 'issues', + 'issue_comment', + 'pull_request_review', + 'pull_request_review_comment', + 'schedule', +]); +// Pull request actions +const PullRequestActionSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n([ + 'opened', + 'synchronize', + 'ready_for_review', + 'reopened', + 'closed', + 'labeled', +]); +// File change info +const FileChangeSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + filename: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + status: zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['added', 'removed', 'modified', 'renamed', 'copied', 'changed', 'unchanged']), + additions: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + deletions: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative(), + patch: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + chunks: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().optional(), +}); +// Source used to read surrounding file context for diff hunks. +const DiffContextSourceSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .discriminatedUnion */ .gMt('type', [ + zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ type: zod__WEBPACK_IMPORTED_MODULE_0__/* .literal */ .euz('working-tree') }), + zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ type: zod__WEBPACK_IMPORTED_MODULE_0__/* .literal */ .euz('git-index') }), + zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ type: zod__WEBPACK_IMPORTED_MODULE_0__/* .literal */ .euz('git-ref'), ref: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP() }), +]); +/** + * Count the number of chunks/hunks in a patch string. + * Each chunk starts with @@ -X,Y +A,B @@ + */ +function countPatchChunks(patch) { + if (!patch) + return 0; + const matches = patch.match(/^@@\s/gm); + return matches?.length ?? 0; +} +// Pull request context +const PullRequestContextSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + number: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive(), + title: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + body: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().nullable(), + author: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + draft: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY().optional(), + labels: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP()).optional(), + baseBranch: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + headBranch: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + headSha: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + baseSha: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + files: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(FileChangeSchema), + /** Changes in the push behind a `synchronize` event, when GitHub could compare it. */ + push: zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + beforeSha: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + files: zod__WEBPACK_IMPORTED_MODULE_0__/* .array */ .YOg(FileChangeSchema), + }).optional(), +}); +// Repository context +const RepositoryContextSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + owner: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + name: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + fullName: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + defaultBranch: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), +}); +// Full event context +const EventContextSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + eventType: GitHubEventTypeSchema, + action: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + label: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP().optional(), + repository: RepositoryContextSchema, + pullRequest: PullRequestContextSchema.optional(), + repoPath: zod__WEBPACK_IMPORTED_MODULE_0__/* .string */ .YjP(), + diffContextSource: DiffContextSourceSchema.optional(), + explicitFileTargets: zod__WEBPACK_IMPORTED_MODULE_0__/* .boolean */ .zMY().optional(), +}); +// Fix evaluation status +const FixStatusSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* ["enum"] */ .k5n(['not_attempted', 'attempted_failed', 'resolved']); +// Retry configuration for SDK calls +const RetryConfigSchema = zod__WEBPACK_IMPORTED_MODULE_0__/* .object */ .Ikc({ + /** Maximum number of retry attempts (default: 3) */ + maxRetries: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().nonnegative().default(3), + /** Initial delay in milliseconds before first retry (default: 1000) */ + initialDelayMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive().default(1000), + /** Multiplier for exponential backoff (default: 2) */ + backoffMultiplier: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().positive().default(2), + /** Maximum delay in milliseconds between retries (default: 30000) */ + maxDelayMs: zod__WEBPACK_IMPORTED_MODULE_0__/* .number */ .aig().int().positive().default(30000), +}); + + +/***/ }), + +/***/ 82224: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ FR: () => (/* binding */ execFileNonInteractive), +/* harmony export */ OO: () => (/* binding */ GIT_NON_INTERACTIVE_ENV), +/* harmony export */ rd: () => (/* binding */ execGitNonInteractive), +/* harmony export */ zt: () => (/* binding */ execNonInteractive) +/* harmony export */ }); +/* unused harmony export ExecError */ +/* harmony import */ var node_child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31421); +/* harmony import */ var node_child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_child_process__WEBPACK_IMPORTED_MODULE_0__); + +/** + * Error thrown when a command fails. + */ +class ExecError extends Error { + command; + exitCode; + stderr; + signal; + code; + constructor(command, exitCode, stderr, signal, code, options) { + const details = stderr || (signal ? `Killed by signal ${signal}` : 'Unknown error'); + super(`Command failed: ${command}\n${details}`, options); + this.command = command; + this.exitCode = exitCode; + this.stderr = stderr; + this.signal = signal; + this.code = code; + this.name = 'ExecError'; + } +} +/** + * Git environment variables that disable interactive prompts. + * - GIT_TERMINAL_PROMPT=0: Disables git's internal prompts + * - GIT_SSH_COMMAND with BatchMode=yes: Makes SSH fail instead of prompting for passphrase + */ +const GIT_NON_INTERACTIVE_ENV = { + GIT_TERMINAL_PROMPT: '0', + GIT_SSH_COMMAND: 'ssh -o BatchMode=yes', +}; +/** + * Build spawn options for non-interactive execution. + * - stdin: 'ignore' maps to /dev/null, ensuring immediate EOF on read (no hangs) + * - stdout/stderr: 'pipe' to capture output + */ +function buildSpawnOptions(options) { + return { + encoding: 'utf-8', + cwd: options?.cwd, + env: options?.env ? { ...process.env, ...options.env } : process.env, + timeout: options?.timeout, + stdio: ['ignore', 'pipe', 'pipe'], + }; +} +/** + * Execute a shell command in non-interactive mode. + * Uses piped stdio to avoid passing terminal to child process. + * + * @param command - The shell command to execute + * @param options - Execution options (cwd, env, timeout) + * @returns The trimmed stdout output + * @throws ExecError if the command fails + */ +function execNonInteractive(command, options) { + const spawnOptions = buildSpawnOptions(options); + // Use shell to execute the command string + const result = (0,node_child_process__WEBPACK_IMPORTED_MODULE_0__.spawnSync)(command, { + ...spawnOptions, + shell: true, + }); + if (result.error) { + throw new ExecError(command, null, result.error.message, null, result.error.code, { cause: result.error }); + } + if (result.status !== 0) { + const stderr = typeof result.stderr === 'string' ? result.stderr.trim() : ''; + throw new ExecError(command, result.status, stderr, result.signal?.toString() ?? null); + } + const stdout = typeof result.stdout === 'string' ? result.stdout : ''; + return stdout.trim(); +} +/** + * Execute a file with arguments in non-interactive mode. + * Uses execFile semantics (no shell), avoiding shell injection vulnerabilities. + * Uses piped stdio to avoid passing terminal to child process. + * + * @param file - The executable to run + * @param args - Arguments to pass to the executable + * @param options - Execution options (cwd, env, timeout) + * @returns The trimmed stdout output + * @throws ExecError if the command fails + */ +function execFileNonInteractive(file, args, options) { + const spawnOptions = buildSpawnOptions(options); + const command = `${file} ${args.join(' ')}`; + const result = (0,node_child_process__WEBPACK_IMPORTED_MODULE_0__.spawnSync)(file, args, spawnOptions); + if (result.error) { + throw new ExecError(command, null, result.error.message, null, result.error.code, { cause: result.error }); + } + if (result.status !== 0) { + const stderr = typeof result.stderr === 'string' ? result.stderr.trim() : ''; + throw new ExecError(command, result.status, stderr, result.signal?.toString() ?? null); + } + const stdout = typeof result.stdout === 'string' ? result.stdout : ''; + return stdout.trim(); +} +/** + * Execute a git command in non-interactive mode. + * Combines execFileNonInteractive with GIT_NON_INTERACTIVE_ENV for + * defense-in-depth against SSH prompts. + * + * @param args - Arguments to pass to git + * @param options - Execution options (cwd, env, timeout) + * @returns The trimmed stdout output + * @throws ExecError if the command fails + */ +function execGitNonInteractive(args, options) { + const env = { + ...options?.env, + ...GIT_NON_INTERACTIVE_ENV, // Always override to ensure non-interactive + }; + return execFileNonInteractive('git', args, { ...options, env }); +} + + +/***/ }), + +/***/ 82272: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Z_: () => (/* reexport */ AsyncWorkQueue), + WH: () => (/* binding */ DEFAULT_CONCURRENCY), + cw: () => (/* binding */ bridgeWardenProviderApiKeyEnv), + ZD: () => (/* binding */ escapeHtml), + HF: () => (/* reexport */ version/* getVersion */.H), + kD: () => (/* reexport */ runPool) +}); + +// UNUSED EXPORTS: ExecError, GIT_NON_INTERACTIVE_ENV, execFileNonInteractive, execGitNonInteractive, execNonInteractive, getAnthropicApiKey, getMajorVersion, isPathLike, processInBatches + +;// CONCATENATED MODULE: ./src/utils/async.ts +/** + * A FIFO queue for dynamically submitted asynchronous work. + * + * The queue owns concurrency bookkeeping so callers cannot leak permits or + * accidentally bypass the shared limit. Work starts as capacity becomes + * available, and each returned promise settles with its submitted task. + */ +class AsyncWorkQueue { + pending = []; + active = 0; + started = 0; + concurrency; + constructor(concurrency) { + if (!Number.isInteger(concurrency) || concurrency < 1) { + throw new RangeError('Queue concurrency must be a positive integer'); + } + this.concurrency = concurrency; + } + /** Enqueue work under the queue's shared concurrency and delayed-dispatch limits. */ + run(work, options = {}) { + return new Promise((resolve, reject) => { + this.pending.push({ + work, + delayMs: options.delayMs ?? 0, + signal: options.signal, + resolve: resolve, + reject, + }); + this.dispatch(); + }); + } + dispatch() { + while (this.active < this.concurrency) { + const item = this.pending.shift(); + if (!item) + return; + const delayMs = this.started >= this.concurrency ? item.delayMs : 0; + this.started++; + this.active++; + void this.execute(item, delayMs).finally(() => { + this.active--; + this.dispatch(); + }); + } + } + async execute(item, delayMs) { + try { + if (delayMs > 0) { + await waitForDelay(delayMs, item.signal); + } + item.resolve(await item.work()); + } + catch (error) { + item.reject(error); + } + } +} +function waitForDelay(delayMs, signal) { + return new Promise((resolve) => { + if (signal?.aborted) { + resolve(); + return; + } + const finish = () => { + clearTimeout(timeout); + signal?.removeEventListener('abort', finish); + resolve(); + }; + const timeout = setTimeout(finish, delayMs); + signal?.addEventListener('abort', finish, { once: true }); + }); +} +/** + * Run async work items with a sliding-window concurrency pool. + * Spawns up to `concurrency` workers that each grab the next + * queued item as soon as they finish, keeping all slots busy. + * + * Results are returned in input order regardless of completion order. + * When `shouldAbort` is provided and returns true, workers stop + * picking up new items; already-started items run to completion. + * Only completed items appear in the returned array. + */ +async function runPool(items, concurrency, fn, options) { + const results = []; + let nextIndex = 0; + async function worker() { + while (nextIndex < items.length) { + if (options?.shouldAbort?.()) + break; + const index = nextIndex++; + const item = items[index]; + results.push({ index, value: await fn(item, index) }); + } + } + const workerCount = Math.min(concurrency, items.length); + await Promise.all(Array.from({ length: workerCount }, () => worker())); + // Return results in input order + results.sort((a, b) => a.index - b.index); + return results.map((r) => r.value); +} +/** + * Process items with limited concurrency using a sliding-window pool. + */ +async function processInBatches(items, fn, batchSize) { + return runPool(items, batchSize, fn); +} + +// EXTERNAL MODULE: ./src/utils/version.ts +var version = __webpack_require__(56317); +// EXTERNAL MODULE: ./src/utils/exec.ts +var exec = __webpack_require__(82224); +// EXTERNAL MODULE: ./src/utils/path.ts +var path = __webpack_require__(60702); +;// CONCATENATED MODULE: ./src/utils/index.ts + + + + +/** Default concurrency for parallel trigger/skill execution */ +const DEFAULT_CONCURRENCY = 4; +/** + * Escape HTML special characters to prevent them from being interpreted as HTML. + * Preserves content inside markdown code blocks (```) and inline code (`). + * Used when rendering finding titles/descriptions in GitHub comments. + */ +function escapeHtml(text) { + // Extract code blocks and inline code, escape HTML in the rest + const codeBlocks = []; + // Replace code blocks (``` ... ```) and inline code (` ... `) with indexed placeholders + // Process triple backticks first (they may contain single backticks) + let processed = text.replace(/```[\s\S]*?```/g, (match) => { + const idx = codeBlocks.length; + codeBlocks.push(match); + return `\0CODE${idx}\0`; + }); + // Then process inline code (single backticks) + processed = processed.replace(/`[^`]+`/g, (match) => { + const idx = codeBlocks.length; + codeBlocks.push(match); + return `\0CODE${idx}\0`; + }); + // Escape HTML in the non-code portions + processed = processed + .replace(/&/g, '&') + .replace(//g, '>'); + // Restore code blocks by index + codeBlocks.forEach((block, i) => { + processed = processed.replace(`\0CODE${i}\0`, block); + }); + return processed; +} +/** + * Get the Anthropic API key from environment variables. + * Checks WARDEN_ANTHROPIC_API_KEY first, then falls back to ANTHROPIC_API_KEY. + */ +function getAnthropicApiKey() { + return process.env['WARDEN_ANTHROPIC_API_KEY'] ?? process.env['ANTHROPIC_API_KEY']; +} +/** + * Mirrors WARDEN-prefixed provider API keys to the env names expected by SDKs. + */ +function bridgeWardenProviderApiKeyEnv(env = process.env) { + for (const [key, value] of Object.entries(env)) { + if (!value || !key.startsWith('WARDEN_') || !key.endsWith('_API_KEY')) { + continue; + } + const providerKey = key.slice('WARDEN_'.length); + if (!env[providerKey]) { + env[providerKey] = value; + } + } +} + + +/***/ }), + +/***/ 60702: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ BI: () => (/* binding */ resolvePathTarget), +/* harmony export */ Fd: () => (/* binding */ normalizePath), +/* harmony export */ Ms: () => (/* binding */ isRepoRelativePath), +/* harmony export */ RA: () => (/* binding */ isPathLike) +/* harmony export */ }); +/* unused harmony export resolveConfigInput */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48161); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_os__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_2__); + + + +/** + * Normalize path separators to forward slashes for cross-platform consistency. + */ +function normalizePath(path) { + return path.replace(/\\/g, '/'); +} +/** + * Check whether a normalized path stays within a repository-relative boundary. + */ +function isRepoRelativePath(path) { + return path !== '' && path !== '..' && !path.startsWith('../') && !(0,node_path__WEBPACK_IMPORTED_MODULE_2__.isAbsolute)(path); +} +/** + * Check whether a target string should be treated as a filesystem path. + */ +function isPathLike(value) { + return value === '~' || value.startsWith('.') || value.includes('/') || value.includes('\\'); +} +/** + * Resolve a user-supplied config input to the absolute path of a warden.toml + * file. If the resolved path is a directory, appends 'warden.toml'; otherwise + * treats the input as a direct file path. + */ +function resolveConfigInput(input) { + const p = resolve(process.cwd(), input); + try { + if (statSync(p).isDirectory()) + return join(p, 'warden.toml'); + } + catch { + // Path doesn't exist or isn't accessible — treat as direct file path + } + return p; +} +/** + * Resolve a CLI path target against a base directory. + */ +function resolvePathTarget(path, baseDir) { + if (path.startsWith('~/')) { + return (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)((0,node_os__WEBPACK_IMPORTED_MODULE_1__.homedir)(), path.slice(2)); + } + if (path === '~') { + return (0,node_os__WEBPACK_IMPORTED_MODULE_1__.homedir)(); + } + if ((0,node_path__WEBPACK_IMPORTED_MODULE_2__.isAbsolute)(path)) { + return path; + } + return baseDir ? (0,node_path__WEBPACK_IMPORTED_MODULE_2__.join)(baseDir, path) : path; +} + + +/***/ }), + +/***/ 56317: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ H: () => (/* binding */ getVersion) +/* harmony export */ }); +/* unused harmony export getMajorVersion */ +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73024); +/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76760); +/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var node_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(73136); +/* harmony import */ var node_url__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(node_url__WEBPACK_IMPORTED_MODULE_2__); + + + +let cachedVersion; +function readPackageVersion(packageJsonPath) { + try { + const pkg = JSON.parse((0,node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(packageJsonPath, 'utf-8')); + return pkg.version; + } + catch { + return undefined; + } +} +function getVersion() { + if (cachedVersion) + return cachedVersion; + // GITHUB_ACTION_PATH (set by GitHub Actions for every action) is this + // repo's own checked-out root, independent of how the running code is laid + // out — unlike an import.meta.url-relative path, which is only two levels + // above packages/warden/package.json when running from TypeScript source. + // ncc bundling flattens dist/action/index.js, so that same relative depth + // lands on the monorepo root's package.json instead, which has no version + // field (it's `private: true`) — silently returning undefined here would + // break any real Action run the moment a schema requires this as a string. + const actionPath = process.env['GITHUB_ACTION_PATH']; + const versionFromActionPath = actionPath && readPackageVersion((0,node_path__WEBPACK_IMPORTED_MODULE_1__.join)(actionPath, 'packages/warden/package.json')); + if (versionFromActionPath) { + cachedVersion = versionFromActionPath; + return cachedVersion; + } + const __dirname = (0,node_path__WEBPACK_IMPORTED_MODULE_1__.dirname)((0,node_url__WEBPACK_IMPORTED_MODULE_2__.fileURLToPath)(import.meta.url)); + cachedVersion = readPackageVersion((0,node_path__WEBPACK_IMPORTED_MODULE_1__.join)(__dirname, '..', '..', 'package.json')) ?? '0.0.0-unknown'; + return cachedVersion; +} +function getMajorVersion() { + return getVersion().split('.')[0] ?? '0'; +} + + +/***/ }) + +}; diff --git a/dist/action/666.index.js b/dist/action/666.index.js new file mode 100644 index 000000000..991e6f55b --- /dev/null +++ b/dist/action/666.index.js @@ -0,0 +1,1387 @@ +export const id = 666; +export const ids = [666]; +export const modules = { + +/***/ 40471: +/***/ ((module, exports, __webpack_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', + '#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' +]; + +/** + * 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; + } + + let m; + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + // eslint-disable-next-line no-return-assign + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * 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') || 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 = __webpack_require__(71210)(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; + } +}; + + +/***/ }), + +/***/ 71210: +/***/ ((module, __unused_webpack_exports, __webpack_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 = __webpack_require__(96987); + 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 = []; + + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(/\s+/g, ',') + .split(',') + .filter(Boolean); + + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { + // Match character or proceed with wildcard + if (template[templateIndex] === '*') { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; // Skip the '*' + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition + // Backtrack to the last '*' and try to match more characters + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; // No match + } + } + + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } + + return templateIndex === template.length; + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.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) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + + return false; + } + + /** + * 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; + + +/***/ }), + +/***/ 26675: +/***/ ((module, __unused_webpack_exports, __webpack_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 = __webpack_require__(40471); +} else { + module.exports = __webpack_require__(47443); +} + + +/***/ }), + +/***/ 47443: +/***/ ((module, exports, __webpack_require__) => { + +/** + * Module dependencies. + */ + +const tty = __webpack_require__(52018); +const util = __webpack_require__(39023); + +/** + * 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 = __webpack_require__(56480); + + 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.formatWithOptions()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...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 = __webpack_require__(71210)(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); +}; + + +/***/ }), + +/***/ 64167: +/***/ ((module) => { + + + +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); +}; + + +/***/ }), + +/***/ 96987: +/***/ ((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' : ''); +} + + +/***/ }), + +/***/ 56480: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +const os = __webpack_require__(70857); +const tty = __webpack_require__(52018); +const hasFlag = __webpack_require__(64167); + +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; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + 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; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; + + +/***/ }), + +/***/ 78932: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ lazyApi), +/* harmony export */ n: () => (/* binding */ lazyStream) +/* harmony export */ }); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45174); + +function createSetupErrorMessage(model, error) { + return { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "error", + errorMessage: error instanceof Error ? error.message : String(error), + timestamp: Date.now(), + }; +} +function hasResult(source) { + return typeof source.result === "function"; +} +async function forwardStream(target, source) { + for await (const event of source) { + target.push(event); + } + target.end(hasResult(source) ? await source.result() : undefined); +} +/** + * Returns a stream synchronously while running async setup (auth resolution, + * lazy module loading) behind it. Setup failures terminate the stream with an + * error event. + */ +function lazyStream(model, setup) { + const outer = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_0__/* .AssistantMessageEventStream */ .Q2(); + setup() + .then((inner) => forwardStream(outer, inner)) + .catch((error) => { + const message = createSetupErrorMessage(model, error); + outer.push({ type: "error", reason: "error", error: message }); + outer.end(message); + }); + return outer; +} +function lazyApi(load, capabilities) { + const api = { + stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)), + streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options)), + }; + if (capabilities?.fetchDeferred) { + api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => { + const implementation = await load(); + if (!implementation.fetchDeferred) + throw new Error("API does not support deferred responses"); + return implementation.fetchDeferred(model, handle, options); + }); + } + if (capabilities?.cancelDeferred) { + api.cancelDeferred = async (model, handle, options) => { + const implementation = await load(); + if (!implementation.cancelDeferred) + throw new Error("API cannot cancel deferred responses"); + await implementation.cancelDeferred(model, handle, options); + }; + } + return api; +} +//# sourceMappingURL=lazy.js.map + +/***/ }), + +/***/ 45174: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Q2: () => (/* binding */ AssistantMessageEventStream), +/* harmony export */ sM: () => (/* binding */ createAssistantMessageEventStream), +/* harmony export */ vC: () => (/* binding */ EventStream) +/* harmony export */ }); +class FifoQueue { + incoming = []; + outgoing = []; + get length() { + return this.incoming.length + this.outgoing.length; + } + enqueue(value) { + this.incoming.push(value); + } + dequeue() { + if (this.outgoing.length === 0) { + while (this.incoming.length > 0) { + this.outgoing.push(this.incoming.pop()); + } + } + return this.outgoing.pop(); + } +} +// Generic event stream class for async iteration +class EventStream { + queue = new FifoQueue(); + waiting = new FifoQueue(); + done = false; + finalResultPromise; + resolveFinalResult; + isComplete; + extractResult; + constructor(isComplete, extractResult) { + this.isComplete = isComplete; + this.extractResult = extractResult; + this.finalResultPromise = new Promise((resolve) => { + this.resolveFinalResult = resolve; + }); + } + push(event) { + if (this.done) + return; + if (this.isComplete(event)) { + this.done = true; + this.resolveFinalResult(this.extractResult(event)); + } + // Deliver to waiting consumer or queue it + const waiter = this.waiting.dequeue(); + if (waiter) { + waiter({ value: event, done: false }); + } + else { + this.queue.enqueue(event); + } + } + end(result) { + this.done = true; + if (result !== undefined) { + this.resolveFinalResult(result); + } + // Notify all waiting consumers that we're done + while (this.waiting.length > 0) { + const waiter = this.waiting.dequeue(); + waiter({ value: undefined, done: true }); + } + } + async *[Symbol.asyncIterator]() { + while (true) { + if (this.queue.length > 0) { + yield this.queue.dequeue(); + } + else if (this.done) { + return; + } + else { + const result = await new Promise((resolve) => this.waiting.enqueue(resolve)); + if (result.done) + return; + yield result.value; + } + } + } + result() { + return this.finalResultPromise; + } +} +class AssistantMessageEventStream extends EventStream { + constructor() { + super((event) => event.type === "done" || event.type === "error", (event) => { + if (event.type === "done") { + return event.message; + } + else if (event.type === "error") { + return event.error; + } + throw new Error("Unexpected event type for final result"); + }); + } +} +/** Factory function for AssistantMessageEventStream (for use in extensions) */ +function createAssistantMessageEventStream() { + return new AssistantMessageEventStream(); +} +//# sourceMappingURL=event-stream.js.map + +/***/ }) + +}; diff --git a/dist/action/702.index.js b/dist/action/702.index.js new file mode 100644 index 000000000..426aaa77f --- /dev/null +++ b/dist/action/702.index.js @@ -0,0 +1,4533 @@ +export const id = 702; +export const ids = [702]; +export const modules = { + +/***/ 11702: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +let imports = {}; +imports['__wbindgen_placeholder__'] = module.exports; +let wasm; +const { TextEncoder, TextDecoder } = __webpack_require__(39023); + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +let WASM_VECTOR_LEN = 0; + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +let cachedTextEncoder = new TextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedDataViewMemory0 = null; + +function getDataViewMemory0() { + if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +function _assertClass(instance, klass) { + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } + return instance.ptr; +} +/** + * Alter a select channel by incrementing or decrementing its value by a constant. + * + * # Arguments + * * `img` - A PhotonImage. + * * `channel` - The channel you wish to alter, it should be either 0, 1 or 2, + * representing R, G, or B respectively. (O=Red, 1=Green, 2=Blue) + * * `amount` - The amount to increment/decrement the channel's value by for that pixel. + * A positive value will increment/decrement the channel's value, a negative value will decrement the channel's value. + * + * ## Example + * + * ```no_run + * // For example, to increase the Red channel for all pixels by 10: + * use photon_rs::channels::alter_channel; + * use photon_rs::native::{open_image}; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_channel(&mut img, 0_usize, 10_i16); + * ``` + * + * Adds a constant to a select R, G, or B channel's value. + * + * ### Decrease a channel's value + * // For example, to decrease the Green channel for all pixels by 20: + * ```no_run + * use photon_rs::channels::alter_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_channel(&mut img, 1_usize, -20_i16); + * ``` + * **Note**: Note the use of a minus symbol when decreasing the channel. + * @param {PhotonImage} img + * @param {number} channel + * @param {number} amt + */ +module.exports.alter_channel = function(img, channel, amt) { + _assertClass(img, PhotonImage); + wasm.alter_channel(img.__wbg_ptr, channel, amt); +}; + +/** + * Increment or decrement every pixel's Red channel by a constant. + * + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `amt` - The amount to increment or decrement the channel's value by for that pixel. + * + * # Example + * + * ```no_run + * // For example, to increase the Red channel for all pixels by 10: + * use photon_rs::channels::alter_red_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_red_channel(&mut img, 10_i16); + * ``` + * @param {PhotonImage} photon_image + * @param {number} amt + */ +module.exports.alter_red_channel = function(photon_image, amt) { + _assertClass(photon_image, PhotonImage); + wasm.alter_red_channel(photon_image.__wbg_ptr, amt); +}; + +/** + * Increment or decrement every pixel's Green channel by a constant. + * + * # Arguments + * * `img` - A PhotonImage. + * * `amt` - The amount to increment/decrement the channel's value by for that pixel. + * + * # Example + * + * ```no_run + * // For example, to increase the Green channel for all pixels by 20: + * use photon_rs::channels::alter_green_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_green_channel(&mut img, 20_i16); + * ``` + * @param {PhotonImage} img + * @param {number} amt + */ +module.exports.alter_green_channel = function(img, amt) { + _assertClass(img, PhotonImage); + wasm.alter_green_channel(img.__wbg_ptr, amt); +}; + +/** + * Increment or decrement every pixel's Blue channel by a constant. + * + * # Arguments + * * `img` - A PhotonImage. + * * `amt` - The amount to increment or decrement the channel's value by for that pixel. + * + * # Example + * + * ```no_run + * // For example, to increase the Blue channel for all pixels by 10: + * use photon_rs::channels::alter_blue_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_blue_channel(&mut img, 10_i16); + * ``` + * @param {PhotonImage} img + * @param {number} amt + */ +module.exports.alter_blue_channel = function(img, amt) { + _assertClass(img, PhotonImage); + wasm.alter_blue_channel(img.__wbg_ptr, amt); +}; + +/** + * Increment/decrement two channels' values simultaneously by adding an amt to each channel per pixel. + * + * # Arguments + * * `img` - A PhotonImage. + * * `channel1` - A usize from 0 to 2 that represents either the R, G or B channels. + * * `amt1` - The amount to increment/decrement the channel's value by for that pixel. + * * `channel2` -A usize from 0 to 2 that represents either the R, G or B channels. + * * `amt2` - The amount to increment/decrement the channel's value by for that pixel. + * + * # Example + * + * ```no_run + * // For example, to increase the values of the Red and Blue channels per pixel: + * use photon_rs::channels::alter_two_channels; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_two_channels(&mut img, 0_usize, 10_i16, 2_usize, 20_i16); + * ``` + * @param {PhotonImage} img + * @param {number} channel1 + * @param {number} amt1 + * @param {number} channel2 + * @param {number} amt2 + */ +module.exports.alter_two_channels = function(img, channel1, amt1, channel2, amt2) { + _assertClass(img, PhotonImage); + wasm.alter_two_channels(img.__wbg_ptr, channel1, amt1, channel2, amt2); +}; + +/** + * Increment all 3 channels' values by adding an amt to each channel per pixel. + * + * # Arguments + * * `img` - A PhotonImage. + * * `r_amt` - The amount to increment/decrement the Red channel by. + * * `g_amt` - The amount to increment/decrement the Green channel by. + * * `b_amt` - The amount to increment/decrement the Blue channel by. + * + * # Example + * + * ```no_run + * // For example, to increase the values of the Red channel by 10, the Green channel by 20, + * // and the Blue channel by 50: + * use photon_rs::channels::alter_channels; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * alter_channels(&mut img, 10_i16, 20_i16, 50_i16); + * ``` + * @param {PhotonImage} img + * @param {number} r_amt + * @param {number} g_amt + * @param {number} b_amt + */ +module.exports.alter_channels = function(img, r_amt, g_amt, b_amt) { + _assertClass(img, PhotonImage); + wasm.alter_channels(img.__wbg_ptr, r_amt, g_amt, b_amt); +}; + +/** + * Set a certain channel to zero, thus removing the channel's influence in the pixels' final rendered colour. + * + * # Arguments + * * `img` - A PhotonImage. + * * `channel` - The channel to be removed; must be a usize from 0 to 2, with 0 representing Red, 1 representing Green, and 2 representing Blue. + * * `min_filter` - Minimum filter. Value between 0 and 255. Only remove the channel if the current pixel's channel value is less than this minimum filter. To completely + * remove the channel, set this value to 255, to leave the channel as is, set to 0, and to set a channel to zero for a pixel whose red value is greater than 50, + * then channel would be 0 and min_filter would be 50. + * + * # Example + * + * ```no_run + * // For example, to remove the Red channel with a min_filter of 100: + * use photon_rs::channels::remove_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * remove_channel(&mut img, 0_usize, 100_u8); + * ``` + * @param {PhotonImage} img + * @param {number} channel + * @param {number} min_filter + */ +module.exports.remove_channel = function(img, channel, min_filter) { + _assertClass(img, PhotonImage); + wasm.remove_channel(img.__wbg_ptr, channel, min_filter); +}; + +/** + * Remove the Red channel's influence in an image. + * + * # Arguments + * * `img` - A PhotonImage. + * * `min_filter` - Only remove the channel if the current pixel's channel value is less than this minimum filter. + * + * # Example + * + * ```no_run + * // For example, to remove the red channel for red channel pixel values less than 50: + * use photon_rs::channels::remove_red_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * remove_red_channel(&mut img, 50_u8); + * ``` + * @param {PhotonImage} img + * @param {number} min_filter + */ +module.exports.remove_red_channel = function(img, min_filter) { + _assertClass(img, PhotonImage); + wasm.remove_red_channel(img.__wbg_ptr, min_filter); +}; + +/** + * Remove the Green channel's influence in an image. + * + * # Arguments + * * `img` - A PhotonImage. + * * `min_filter` - Only remove the channel if the current pixel's channel value is less than this minimum filter. + * + * # Example + * + * ```no_run + * // For example, to remove the green channel for green channel pixel values less than 50: + * use photon_rs::channels::remove_green_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * remove_green_channel(&mut img, 50_u8); + * ``` + * @param {PhotonImage} img + * @param {number} min_filter + */ +module.exports.remove_green_channel = function(img, min_filter) { + _assertClass(img, PhotonImage); + wasm.remove_green_channel(img.__wbg_ptr, min_filter); +}; + +/** + * Remove the Blue channel's influence in an image. + * + * # Arguments + * * `img` - A PhotonImage. + * * `min_filter` - Only remove the channel if the current pixel's channel value is less than this minimum filter. + * + * # Example + * + * ```no_run + * // For example, to remove the blue channel for blue channel pixel values less than 50: + * use photon_rs::channels::remove_blue_channel; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * remove_blue_channel(&mut img, 50_u8); + * ``` + * @param {PhotonImage} img + * @param {number} min_filter + */ +module.exports.remove_blue_channel = function(img, min_filter) { + _assertClass(img, PhotonImage); + wasm.remove_blue_channel(img.__wbg_ptr, min_filter); +}; + +/** + * Swap two channels. + * + * # Arguments + * * `img` - A PhotonImage. + * * `channel1` - An index from 0 to 2, representing the Red, Green or Blue channels respectively. Red would be represented by 0, Green by 1, and Blue by 2. + * * `channel2` - An index from 0 to 2, representing the Red, Green or Blue channels respectively. Same as above. + * + * # Example + * + * ```no_run + * // For example, to swap the values of the Red channel with the values of the Blue channel: + * use photon_rs::channels::swap_channels; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * swap_channels(&mut img, 0_usize, 2_usize); + * ``` + * @param {PhotonImage} img + * @param {number} channel1 + * @param {number} channel2 + */ +module.exports.swap_channels = function(img, channel1, channel2) { + _assertClass(img, PhotonImage); + wasm.swap_channels(img.__wbg_ptr, channel1, channel2); +}; + +/** + * Invert RGB value of an image. + * + * # Arguments + * * `photon_image` - A DynamicImage that contains a view into the image. + * # Example + * + * ```no_run + * use photon_rs::channels::invert; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * invert(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.invert = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.invert(photon_image.__wbg_ptr); +}; + +/** + * Selective hue rotation. + * + * Only rotate the hue of a pixel if its RGB values are within a specified range. + * This function only rotates a pixel's hue to another if it is visually similar to the colour specified. + * For example, if a user wishes all pixels that are blue to be changed to red, they can selectively specify only the blue pixels to be changed. + * # Arguments + * * `img` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * * `degrees` - The amount of degrees to hue rotate by. + * + * # Example + * + * ```no_run + * // For example, to only rotate the pixels that are of RGB value RGB{20, 40, 60}: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_hue_rotate; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(20_u8, 40_u8, 60_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_hue_rotate(&mut img, ref_color, 180_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {Rgb} ref_color + * @param {number} degrees + */ +module.exports.selective_hue_rotate = function(photon_image, ref_color, degrees) { + _assertClass(photon_image, PhotonImage); + _assertClass(ref_color, Rgb); + var ptr0 = ref_color.__destroy_into_raw(); + wasm.selective_hue_rotate(photon_image.__wbg_ptr, ptr0, degrees); +}; + +/** + * Selectively change pixel colours which are similar to the reference colour provided. + * + * Similarity between two colours is calculated via the CIE76 formula. + * Only changes the color of a pixel if its similarity to the reference colour is within the range in the algorithm. + * For example, with this function, a user can change the color of all blue pixels by mixing them with red by 10%. + * # Arguments + * * `photon_image` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * * `new_color` - The `RGB` value of the new color (to be mixed with the matched pixels) + * * `fraction` - The amount of mixing the new colour with the matched pixels + * + * # Example + * + * ```no_run + * // For example, to only change the color of pixels that are similar to the RGB value RGB{200, 120, 30} by mixing RGB{30, 120, 200} with 25%: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_color_convert; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(200, 120, 30); + * let new_color = Rgb::new(30, 120, 200); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_color_convert(&mut img, ref_color, new_color, 0.25); + * ``` + * @param {PhotonImage} photon_image + * @param {Rgb} ref_color + * @param {Rgb} new_color + * @param {number} fraction + */ +module.exports.selective_color_convert = function(photon_image, ref_color, new_color, fraction) { + _assertClass(photon_image, PhotonImage); + _assertClass(ref_color, Rgb); + var ptr0 = ref_color.__destroy_into_raw(); + _assertClass(new_color, Rgb); + var ptr1 = new_color.__destroy_into_raw(); + wasm.selective_color_convert(photon_image.__wbg_ptr, ptr0, ptr1, fraction); +}; + +/** + * Selectively lighten an image. + * + * Only lighten the hue of a pixel if its colour matches or is similar to the RGB colour specified. + * For example, if a user wishes all pixels that are blue to be lightened, they can selectively specify only the blue pixels to be changed. + * # Arguments + * * `img` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * * `amt` - The level from 0 to 1 to lighten the hue by. Increasing by 10% would have an `amt` of 0.1 + * + * # Example + * + * ```no_run + * // For example, to only lighten the pixels that are of or similar to RGB value RGB{20, 40, 60}: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_lighten; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(20_u8, 40_u8, 60_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_lighten(&mut img, ref_color, 0.2_f32); + * ``` + * @param {PhotonImage} img + * @param {Rgb} ref_color + * @param {number} amt + */ +module.exports.selective_lighten = function(img, ref_color, amt) { + _assertClass(img, PhotonImage); + _assertClass(ref_color, Rgb); + var ptr0 = ref_color.__destroy_into_raw(); + wasm.selective_lighten(img.__wbg_ptr, ptr0, amt); +}; + +/** + * Selectively desaturate pixel colours which are similar to the reference colour provided. + * + * Similarity between two colours is calculated via the CIE76 formula. + * Only desaturates the hue of a pixel if its similarity to the reference colour is within the range in the algorithm. + * For example, if a user wishes all pixels that are blue to be desaturated by 0.1, they can selectively specify only the blue pixels to be changed. + * # Arguments + * * `img` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * * `amt` - The amount of desaturate the colour by. + * + * # Example + * + * ```no_run + * // For example, to only desaturate the pixels that are similar to the RGB value RGB{20, 40, 60}: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_desaturate; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(20_u8, 40_u8, 60_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_desaturate(&mut img, ref_color, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {Rgb} ref_color + * @param {number} amt + */ +module.exports.selective_desaturate = function(img, ref_color, amt) { + _assertClass(img, PhotonImage); + _assertClass(ref_color, Rgb); + var ptr0 = ref_color.__destroy_into_raw(); + wasm.selective_desaturate(img.__wbg_ptr, ptr0, amt); +}; + +/** + * Selectively saturate pixel colours which are similar to the reference colour provided. + * + * Similarity between two colours is calculated via the CIE76 formula. + * Only saturates the hue of a pixel if its similarity to the reference colour is within the range in the algorithm. + * For example, if a user wishes all pixels that are blue to have an increase in saturation by 10%, they can selectively specify only the blue pixels to be changed. + * # Arguments + * * `img` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * * `amt` - The amount of saturate the colour by. + * + * # Example + * + * ```no_run + * // For example, to only increase the saturation of pixels that are similar to the RGB value RGB{20, 40, 60}: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_saturate; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(20_u8, 40_u8, 60_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_saturate(&mut img, ref_color, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {Rgb} ref_color + * @param {number} amt + */ +module.exports.selective_saturate = function(img, ref_color, amt) { + _assertClass(img, PhotonImage); + _assertClass(ref_color, Rgb); + var ptr0 = ref_color.__destroy_into_raw(); + wasm.selective_saturate(img.__wbg_ptr, ptr0, amt); +}; + +/** + * Selectively changes a pixel to greyscale if it is *not* visually similar or close to the colour specified. + * Only changes the colour of a pixel if its RGB values are within a specified range. + * + * (Similarity between two colours is calculated via the CIE76 formula.) + * For example, if a user wishes all pixels that are *NOT* blue to be displayed in greyscale, they can selectively specify only the blue pixels to be + * kept in the photo. + * # Arguments + * * `img` - A PhotonImage. + * * `ref_color` - The `RGB` value of the reference color (to be compared to) + * + * # Example + * + * ```no_run + * // For example, to greyscale all pixels that are *not* visually similar to the RGB colour RGB{20, 40, 60}: + * use photon_rs::Rgb; + * use photon_rs::channels::selective_greyscale; + * use photon_rs::native::open_image; + * + * let ref_color = Rgb::new(20_u8, 40_u8, 60_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * selective_greyscale(img, ref_color); + * ``` + * @param {PhotonImage} photon_image + * @param {Rgb} ref_color + */ +module.exports.selective_greyscale = function(photon_image, ref_color) { + _assertClass(photon_image, PhotonImage); + var ptr0 = photon_image.__destroy_into_raw(); + _assertClass(ref_color, Rgb); + var ptr1 = ref_color.__destroy_into_raw(); + wasm.selective_greyscale(ptr0, ptr1); +}; + +/** + * Apply a monochrome effect of a certain colour. + * + * It does so by averaging the R, G, and B values of a pixel, and then adding a + * separate value to that averaged value for each channel to produce a tint. + * # Arguments + * * `photon_image` - A PhotonImage. + * * `r_offset` - The value to add to the Red channel per pixel. + * * `g_offset` - The value to add to the Green channel per pixel. + * * `b_offset` - The value to add to the Blue channel per pixel. + * + * # Example + * + * ```no_run + * // For example, to apply a monochrome effect to an image: + * use photon_rs::monochrome::monochrome; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * monochrome(&mut img, 40_u32, 50_u32, 100_u32); + * ``` + * @param {PhotonImage} img + * @param {number} r_offset + * @param {number} g_offset + * @param {number} b_offset + */ +module.exports.monochrome = function(img, r_offset, g_offset, b_offset) { + _assertClass(img, PhotonImage); + wasm.monochrome(img.__wbg_ptr, r_offset, g_offset, b_offset); +}; + +/** + * Convert an image to sepia. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * # Example + * + * ```no_run + * // For example, to sepia an image of type `PhotonImage`: + * use photon_rs::monochrome::sepia; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * sepia(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.sepia = function(img) { + _assertClass(img, PhotonImage); + wasm.sepia(img.__wbg_ptr); +}; + +/** + * Convert an image to grayscale using the conventional averaging algorithm. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * # Example + * + * ```no_run + * // For example, to convert an image of type `PhotonImage` to grayscale: + * use photon_rs::monochrome::grayscale; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * grayscale(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.grayscale = function(img) { + _assertClass(img, PhotonImage); + wasm.grayscale(img.__wbg_ptr); +}; + +/** + * Convert an image to grayscale with a human corrected factor, to account for human vision. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * # Example + * + * ```no_run + * // For example, to convert an image of type `PhotonImage` to grayscale with a human corrected factor: + * use photon_rs::monochrome::grayscale_human_corrected; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * grayscale_human_corrected(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.grayscale_human_corrected = function(img) { + _assertClass(img, PhotonImage); + wasm.grayscale_human_corrected(img.__wbg_ptr); +}; + +/** + * Desaturate an image by getting the min/max of each pixel's RGB values. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * # Example + * + * ```no_run + * // For example, to desaturate an image: + * use photon_rs::monochrome::desaturate; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * desaturate(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.desaturate = function(img) { + _assertClass(img, PhotonImage); + wasm.desaturate(img.__wbg_ptr); +}; + +/** + * Uses a min. decomposition algorithm to convert an image to greyscale. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to decompose an image with min decomposition: + * use photon_rs::monochrome::decompose_min; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * decompose_min(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.decompose_min = function(img) { + _assertClass(img, PhotonImage); + wasm.decompose_min(img.__wbg_ptr); +}; + +/** + * Uses a max. decomposition algorithm to convert an image to greyscale. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to decompose an image with max decomposition: + * use photon_rs::monochrome::decompose_max; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * decompose_max(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.decompose_max = function(img) { + _assertClass(img, PhotonImage); + wasm.decompose_max(img.__wbg_ptr); +}; + +/** + * Employ only a limited number of gray shades in an image. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `num_shades` - The number of grayscale shades to be displayed in the image. + * + * # Example + * + * ```no_run + * // For example, to limit an image to four shades of gray only: + * use photon_rs::monochrome::grayscale_shades; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * grayscale_shades(&mut img, 4_u8); + * ``` + * @param {PhotonImage} photon_image + * @param {number} num_shades + */ +module.exports.grayscale_shades = function(photon_image, num_shades) { + _assertClass(photon_image, PhotonImage); + wasm.grayscale_shades(photon_image.__wbg_ptr, num_shades); +}; + +/** + * Convert an image to grayscale by setting a pixel's 3 RGB values to the Red channel's value. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * + * # Example + * + * ```no_run + * use photon_rs::monochrome::r_grayscale; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * r_grayscale(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.r_grayscale = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.r_grayscale(photon_image.__wbg_ptr); +}; + +/** + * Convert an image to grayscale by setting a pixel's 3 RGB values to the Green channel's value. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * + * # Example + * + * ```no_run + * use photon_rs::monochrome::g_grayscale; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * g_grayscale(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.g_grayscale = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.g_grayscale(photon_image.__wbg_ptr); +}; + +/** + * Convert an image to grayscale by setting a pixel's 3 RGB values to the Blue channel's value. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * + * # Example + * + * ```no_run + * use photon_rs::monochrome::b_grayscale; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * b_grayscale(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.b_grayscale = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.b_grayscale(photon_image.__wbg_ptr); +}; + +/** + * Convert an image to grayscale by setting a pixel's 3 RGB values to a chosen channel's value. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `channel` - A usize representing the channel from 0 to 2. O represents the Red channel, 1 the Green channel, and 2 the Blue channel. + * + * # Example + * To grayscale using only values from the Red channel: + * ```no_run + * use photon_rs::monochrome::single_channel_grayscale; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * single_channel_grayscale(&mut img, 0_usize); + * ``` + * @param {PhotonImage} photon_image + * @param {number} channel + */ +module.exports.single_channel_grayscale = function(photon_image, channel) { + _assertClass(photon_image, PhotonImage); + wasm.single_channel_grayscale(photon_image.__wbg_ptr, channel); +}; + +/** + * Threshold an image using a standard thresholding algorithm. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `threshold` - The amount the image should be thresholded by from 0 to 255. + * # Example + * + * ```no_run + * // For example, to threshold an image of type `PhotonImage`: + * use photon_rs::monochrome::threshold; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * threshold(&mut img, 30_u32); + * ``` + * @param {PhotonImage} img + * @param {number} threshold + */ +module.exports.threshold = function(img, threshold) { + _assertClass(img, PhotonImage); + wasm.threshold(img.__wbg_ptr, threshold); +}; + +/** + * Applies gamma correction to an image. + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * * `red` - Gamma value for red channel. + * * `green` - Gamma value for green channel. + * * `blue` - Gamma value for blue channel. + * # Example + * + * ```no_run + * // For example, to turn an image of type `PhotonImage` into a gamma corrected image: + * use photon_rs::colour_spaces::gamma_correction; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * gamma_correction(&mut img, 2.2, 2.2, 2.2); + * ``` + * @param {PhotonImage} photon_image + * @param {number} red + * @param {number} green + * @param {number} blue + */ +module.exports.gamma_correction = function(photon_image, red, green, blue) { + _assertClass(photon_image, PhotonImage); + wasm.gamma_correction(photon_image.__wbg_ptr, red, green, blue); +}; + +/** + * Image manipulation effects in the HSLuv colour space + * + * Effects include: + * * **saturate** - Saturation increase. + * * **desaturate** - Desaturate the image. + * * **shift_hue** - Hue rotation by a specified number of degrees. + * * **darken** - Decrease the brightness. + * * **lighten** - Increase the brightness. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `mode` - The effect desired to be applied. Choose from: `saturate`, `desaturate`, `shift_hue`, `darken`, `lighten` + * * `amt` - A float value from 0 to 1 which represents the amount the effect should be increased by. + * # Example + * ```no_run + * // For example to increase the saturation by 10%: + * use photon_rs::colour_spaces::hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hsluv(&mut img, "saturate", 0.1_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {string} mode + * @param {number} amt + */ +module.exports.hsluv = function(photon_image, mode, amt) { + _assertClass(photon_image, PhotonImage); + const ptr0 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.hsluv(photon_image.__wbg_ptr, ptr0, len0, amt); +}; + +/** + * Image manipulation effects in the LCh colour space + * + * Effects include: + * * **saturate** - Saturation increase. + * * **desaturate** - Desaturate the image. + * * **shift_hue** - Hue rotation by a specified number of degrees. + * * **darken** - Decrease the brightness. + * * **lighten** - Increase the brightness. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `mode` - The effect desired to be applied. Choose from: `saturate`, `desaturate`, `shift_hue`, `darken`, `lighten` + * * `amt` - A float value from 0 to 1 which represents the amount the effect should be increased by. + * # Example + * ```no_run + * // For example to increase the saturation by 10%: + * use photon_rs::colour_spaces::lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * lch(&mut img, "saturate", 0.1_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {string} mode + * @param {number} amt + */ +module.exports.lch = function(photon_image, mode, amt) { + _assertClass(photon_image, PhotonImage); + const ptr0 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.lch(photon_image.__wbg_ptr, ptr0, len0, amt); +}; + +/** + * Image manipulation effects in the HSL colour space. + * + * Effects include: + * * **saturate** - Saturation increase. + * * **desaturate** - Desaturate the image. + * * **shift_hue** - Hue rotation by a specified number of degrees. + * * **darken** - Decrease the brightness. + * * **lighten** - Increase the brightness. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `mode` - The effect desired to be applied. Choose from: `saturate`, `desaturate`, `shift_hue`, `darken`, `lighten` + * * `amt` - A float value from 0 to 1 which represents the amount the effect should be increased by. + * # Example + * ```no_run + * // For example to increase the saturation by 10%: + * use photon_rs::colour_spaces::hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hsl(&mut img, "saturate", 0.1_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {string} mode + * @param {number} amt + */ +module.exports.hsl = function(photon_image, mode, amt) { + _assertClass(photon_image, PhotonImage); + const ptr0 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.hsl(photon_image.__wbg_ptr, ptr0, len0, amt); +}; + +/** + * Image manipulation in the HSV colour space. + * + * Effects include: + * * **saturate** - Saturation increase. + * * **desaturate** - Desaturate the image. + * * **shift_hue** - Hue rotation by a specified number of degrees. + * * **darken** - Decrease the brightness. + * * **lighten** - Increase the brightness. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `mode` - The effect desired to be applied. Choose from: `saturate`, `desaturate`, `shift_hue`, `darken`, `lighten` + * * `amt` - A float value from 0 to 1 which represents the amount the effect should be increased by. + * + * # Example + * ```no_run + * // For example to increase the saturation by 10%: + * use photon_rs::colour_spaces::hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hsv(&mut img, "saturate", 0.1_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {string} mode + * @param {number} amt + */ +module.exports.hsv = function(photon_image, mode, amt) { + _assertClass(photon_image, PhotonImage); + const ptr0 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.hsv(photon_image.__wbg_ptr, ptr0, len0, amt); +}; + +/** + * Shift hue by a specified number of degrees in the HSL colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `mode` - A float value from 0 to 1 which is the amount to shift the hue by, or hue rotate by. + * + * # Example + * ```no_run + * // For example to hue rotate/shift the hue by 120 degrees in the HSL colour space: + * use photon_rs::colour_spaces::hue_rotate_hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hue_rotate_hsl(&mut img, 120_f32); + * ``` + * @param {PhotonImage} img + * @param {number} degrees + */ +module.exports.hue_rotate_hsl = function(img, degrees) { + _assertClass(img, PhotonImage); + wasm.hue_rotate_hsl(img.__wbg_ptr, degrees); +}; + +/** + * Shift hue by a specified number of degrees in the HSV colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `mode` - A float value from 0 to 1 which is the amount to shift the hue by, or hue rotate by. + * + * # Example + * ```no_run + * // For example to hue rotate/shift the hue by 120 degrees in the HSV colour space: + * use photon_rs::colour_spaces::hue_rotate_hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hue_rotate_hsv(&mut img, 120_f32); + * ``` + * @param {PhotonImage} img + * @param {number} degrees + */ +module.exports.hue_rotate_hsv = function(img, degrees) { + _assertClass(img, PhotonImage); + wasm.hue_rotate_hsv(img.__wbg_ptr, degrees); +}; + +/** + * Shift hue by a specified number of degrees in the LCh colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `mode` - A float value from 0 to 1 which is the amount to shift the hue by, or hue rotate by. + * + * # Example + * ```no_run + * // For example to hue rotate/shift the hue by 120 degrees in the HSL colour space: + * use photon_rs::colour_spaces::hue_rotate_lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hue_rotate_lch(&mut img, 120_f32); + * ``` + * @param {PhotonImage} img + * @param {number} degrees + */ +module.exports.hue_rotate_lch = function(img, degrees) { + _assertClass(img, PhotonImage); + wasm.hue_rotate_lch(img.__wbg_ptr, degrees); +}; + +/** + * Shift hue by a specified number of degrees in the HSLuv colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `mode` - A float value from 0 to 1 which is the amount to shift the hue by, or hue rotate by. + * + * # Example + * ```no_run + * // For example to hue rotate/shift the hue by 120 degrees in the HSL colour space: + * use photon_rs::colour_spaces::hue_rotate_hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * hue_rotate_hsluv(&mut img, 120_f32); + * ``` + * @param {PhotonImage} img + * @param {number} degrees + */ +module.exports.hue_rotate_hsluv = function(img, degrees) { + _assertClass(img, PhotonImage); + wasm.hue_rotate_hsluv(img.__wbg_ptr, degrees); +}; + +/** + * Increase the image's saturation by converting each pixel's colour to the HSL colour space + * and increasing the colour's saturation. + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to increase the saturation by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Increasing saturation by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to increase saturation by 10% in the HSL colour space: + * use photon_rs::colour_spaces::saturate_hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * saturate_hsl(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.saturate_hsl = function(img, level) { + _assertClass(img, PhotonImage); + wasm.saturate_hsl(img.__wbg_ptr, level); +}; + +/** + * Increase the image's saturation in the LCh colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to increase the saturation by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Increasing saturation by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to increase saturation by 40% in the Lch colour space: + * use photon_rs::colour_spaces::saturate_lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * saturate_lch(&mut img, 0.4_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.saturate_lch = function(img, level) { + _assertClass(img, PhotonImage); + wasm.saturate_lch(img.__wbg_ptr, level); +}; + +/** + * Increase the image's saturation in the HSLuv colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to increase the saturation by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Increasing saturation by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to increase saturation by 40% in the HSLuv colour space: + * use photon_rs::colour_spaces::saturate_hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * saturate_hsluv(&mut img, 0.4_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.saturate_hsluv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.saturate_hsluv(img.__wbg_ptr, level); +}; + +/** + * Increase the image's saturation in the HSV colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level by which to increase the saturation by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Increasing saturation by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to increase saturation by 30% in the HSV colour space: + * use photon_rs::colour_spaces::saturate_hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * saturate_hsv(&mut img, 0.3_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.saturate_hsv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.saturate_hsv(img.__wbg_ptr, level); +}; + +/** + * Lighten an image by a specified amount in the LCh colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to lighten the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Lightening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to lighten an image by 10% in the LCh colour space: + * use photon_rs::colour_spaces::lighten_lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * lighten_lch(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.lighten_lch = function(img, level) { + _assertClass(img, PhotonImage); + wasm.lighten_lch(img.__wbg_ptr, level); +}; + +/** + * Lighten an image by a specified amount in the HSLuv colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to lighten the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Lightening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to lighten an image by 10% in the HSLuv colour space: + * use photon_rs::colour_spaces::lighten_hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * lighten_hsluv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.lighten_hsluv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.lighten_hsluv(img.__wbg_ptr, level); +}; + +/** + * Lighten an image by a specified amount in the HSL colour space. + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to lighten the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Lightening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to lighten an image by 10% in the HSL colour space: + * use photon_rs::colour_spaces::lighten_hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * lighten_hsl(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.lighten_hsl = function(img, level) { + _assertClass(img, PhotonImage); + wasm.lighten_hsl(img.__wbg_ptr, level); +}; + +/** + * Lighten an image by a specified amount in the HSV colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to lighten the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Lightening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to lighten an image by 10% in the HSV colour space: + * use photon_rs::colour_spaces::lighten_hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * lighten_hsv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.lighten_hsv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.lighten_hsv(img.__wbg_ptr, level); +}; + +/** + * Darken the image by a specified amount in the LCh colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to darken the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Darkening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to darken an image by 10% in the LCh colour space: + * use photon_rs::colour_spaces::darken_lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * darken_lch(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.darken_lch = function(img, level) { + _assertClass(img, PhotonImage); + wasm.darken_lch(img.__wbg_ptr, level); +}; + +/** + * Darken the image by a specified amount in the HSLuv colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to darken the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Darkening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to darken an image by 10% in the HSLuv colour space: + * use photon_rs::colour_spaces::darken_hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * darken_hsluv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.darken_hsluv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.darken_hsluv(img.__wbg_ptr, level); +}; + +/** + * Darken the image by a specified amount in the HSL colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to darken the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Darkening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to darken an image by 10% in the HSL colour space: + * use photon_rs::colour_spaces::darken_hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * darken_hsl(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.darken_hsl = function(img, level) { + _assertClass(img, PhotonImage); + wasm.darken_hsl(img.__wbg_ptr, level); +}; + +/** + * Darken the image's colours by a specified amount in the HSV colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to darken the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Darkening by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to darken an image by 10% in the HSV colour space: + * use photon_rs::colour_spaces::darken_hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * darken_hsv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.darken_hsv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.darken_hsv(img.__wbg_ptr, level); +}; + +/** + * Desaturate the image by a specified amount in the HSV colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to desaturate the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Desaturating by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to desaturate an image by 10% in the HSV colour space: + * use photon_rs::colour_spaces::desaturate_hsv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * desaturate_hsv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.desaturate_hsv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.desaturate_hsv(img.__wbg_ptr, level); +}; + +/** + * Desaturate the image by a specified amount in the HSL colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to desaturate the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Desaturating by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to desaturate an image by 10% in the LCh colour space: + * use photon_rs::colour_spaces::desaturate_hsl; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * desaturate_hsl(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.desaturate_hsl = function(img, level) { + _assertClass(img, PhotonImage); + wasm.desaturate_hsl(img.__wbg_ptr, level); +}; + +/** + * Desaturate the image by a specified amount in the LCh colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to desaturate the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Desaturating by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to desaturate an image by 10% in the LCh colour space: + * use photon_rs::colour_spaces::desaturate_lch; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * desaturate_lch(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.desaturate_lch = function(img, level) { + _assertClass(img, PhotonImage); + wasm.desaturate_lch(img.__wbg_ptr, level); +}; + +/** + * Desaturate the image by a specified amount in the HSLuv colour space. + * + * # Arguments + * * `img` - A PhotonImage. + * * `level` - Float value from 0 to 1 representing the level to which to desaturate the image by. + * The `level` must be from 0 to 1 in floating-point, `f32` format. + * Desaturating by 80% would be represented by a `level` of 0.8 + * + * # Example + * ```no_run + * // For example to desaturate an image by 10% in the HSLuv colour space: + * use photon_rs::colour_spaces::desaturate_hsluv; + * use photon_rs::native::open_image; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * desaturate_hsluv(&mut img, 0.1_f32); + * ``` + * @param {PhotonImage} img + * @param {number} level + */ +module.exports.desaturate_hsluv = function(img, level) { + _assertClass(img, PhotonImage); + wasm.desaturate_hsluv(img.__wbg_ptr, level); +}; + +/** + * Mix image with a single color, supporting passing `opacity`. + * The algorithm comes from Jimp. See `function mix` and `function colorFn` at following link: + * https://github.com/oliver-moran/jimp/blob/29679faa597228ff2f20d34c5758e4d2257065a3/packages/plugin-color/src/index.js + * Specifically, result_value = (mix_color_value - origin_value) * opacity + origin_value = + * mix_color_value * opacity + (1 - opacity) * origin_value for each + * of RGB channel. + * + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * * `mix_color` - the color to be mixed in, as an RGB value. + * * `opacity` - the opacity of color when mixed to image. Float value from 0 to 1. + * # Example + * + * ```no_run + * // For example, to mix an image with rgb (50, 255, 254) and opacity 0.4: + * use photon_rs::Rgb; + * use photon_rs::colour_spaces::mix_with_colour; + * use photon_rs::native::open_image; + * + * let mix_colour = Rgb::new(50_u8, 255_u8, 254_u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * mix_with_colour(&mut img, mix_colour, 0.4_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {Rgb} mix_colour + * @param {number} opacity + */ +module.exports.mix_with_colour = function(photon_image, mix_colour, opacity) { + _assertClass(photon_image, PhotonImage); + _assertClass(mix_colour, Rgb); + var ptr0 = mix_colour.__destroy_into_raw(); + wasm.mix_with_colour(photon_image.__wbg_ptr, ptr0, opacity); +}; + +/** + * Noise reduction. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to noise reduct an image: + * use photon_rs::conv::noise_reduction; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * noise_reduction(&mut img); + * ``` + * Adds a constant to a select R, G, or B channel's value. + * @param {PhotonImage} photon_image + */ +module.exports.noise_reduction = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.noise_reduction(photon_image.__wbg_ptr); +}; + +/** + * Sharpen an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to sharpen an image: + * use photon_rs::conv::sharpen; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * sharpen(&mut img); + * ``` + * Adds a constant to a select R, G, or B channel's value. + * @param {PhotonImage} photon_image + */ +module.exports.sharpen = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.sharpen(photon_image.__wbg_ptr); +}; + +/** + * Apply edge detection to an image, to create a dark version with its edges highlighted. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to increase the Red channel for all pixels by 10: + * use photon_rs::conv::edge_detection; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * edge_detection(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.edge_detection = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.edge_detection(photon_image.__wbg_ptr); +}; + +/** + * Apply an identity kernel convolution to an image. + * + * # Arguments + * * `img` -A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply an identity kernel convolution: + * use photon_rs::conv::identity; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * identity(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.identity = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.identity(photon_image.__wbg_ptr); +}; + +/** + * Apply a box blur effect. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a box blur effect: + * use photon_rs::conv::box_blur; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * box_blur(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.box_blur = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.box_blur(photon_image.__wbg_ptr); +}; + +/** + * Gaussian blur in linear time. + * + * Reference: http://blog.ivank.net/fastest-gaussian-blur.html + * + * # Arguments + * * `photon_image` - A PhotonImage + * * `radius` - blur radius + * # Example + * + * ```no_run + * use photon_rs::conv::gaussian_blur; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * gaussian_blur(&mut img, 3_i32); + * ``` + * @param {PhotonImage} photon_image + * @param {number} radius + */ +module.exports.gaussian_blur = function(photon_image, radius) { + _assertClass(photon_image, PhotonImage); + wasm.gaussian_blur(photon_image.__wbg_ptr, radius); +}; + +/** + * Detect horizontal lines in an image, and highlight these only. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to display the horizontal lines in an image: + * use photon_rs::conv::detect_horizontal_lines; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * detect_horizontal_lines(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.detect_horizontal_lines = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.detect_horizontal_lines(photon_image.__wbg_ptr); +}; + +/** + * Detect vertical lines in an image, and highlight these only. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to display the vertical lines in an image: + * use photon_rs::conv::detect_vertical_lines; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * detect_vertical_lines(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.detect_vertical_lines = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.detect_vertical_lines(photon_image.__wbg_ptr); +}; + +/** + * Detect lines at a forty five degree angle in an image, and highlight these only. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to display the lines at a forty five degree angle in an image: + * use photon_rs::conv::detect_45_deg_lines; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * detect_45_deg_lines(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.detect_45_deg_lines = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.detect_45_deg_lines(photon_image.__wbg_ptr); +}; + +/** + * Detect lines at a 135 degree angle in an image, and highlight these only. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to display the lines at a 135 degree angle in an image: + * use photon_rs::conv::detect_135_deg_lines; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * detect_135_deg_lines(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.detect_135_deg_lines = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.detect_135_deg_lines(photon_image.__wbg_ptr); +}; + +/** + * Apply a standard laplace convolution. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a laplace effect: + * use photon_rs::conv::laplace; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * laplace(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.laplace = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.laplace(photon_image.__wbg_ptr); +}; + +/** + * Preset edge effect. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply this effect: + * use photon_rs::conv::edge_one; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * edge_one(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.edge_one = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.edge_one(photon_image.__wbg_ptr); +}; + +/** + * Apply an emboss effect to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply an emboss effect: + * use photon_rs::conv::emboss; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * emboss(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.emboss = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.emboss(photon_image.__wbg_ptr); +}; + +/** + * Apply a horizontal Sobel filter to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a horizontal Sobel filter: + * use photon_rs::conv::sobel_horizontal; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * sobel_horizontal(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.sobel_horizontal = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.sobel_horizontal(photon_image.__wbg_ptr); +}; + +/** + * Apply a horizontal Prewitt convolution to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a horizontal Prewitt convolution effect: + * use photon_rs::conv::prewitt_horizontal; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * prewitt_horizontal(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.prewitt_horizontal = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.prewitt_horizontal(photon_image.__wbg_ptr); +}; + +/** + * Apply a vertical Sobel filter to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a vertical Sobel filter: + * use photon_rs::conv::sobel_vertical; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * sobel_vertical(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.sobel_vertical = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.sobel_vertical(photon_image.__wbg_ptr); +}; + +/** + * Apply a global Sobel filter to an image + * + * Each pixel is calculated as the magnitude of the horizontal and vertical components of the Sobel filter, + * ie if X is the horizontal sobel and Y is the vertical, for each pixel, we calculate sqrt(X^2 + Y^2) + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to apply a global Sobel filter: + * use photon_rs::conv::sobel_global; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * sobel_global(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.sobel_global = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.sobel_global(photon_image.__wbg_ptr); +}; + +/** + * Add randomized noise to an image. + * This function adds a Gaussian Noise Sample to each pixel through incrementing each channel by a randomized offset. + * This randomized offset is generated by creating a randomized thread pool. + * **[WASM SUPPORT IS AVAILABLE]**: Randomized thread pools cannot be created with WASM, but + * a workaround using js_sys::Math::random works now. + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example: + * use photon_rs::native::open_image; + * use photon_rs::noise::add_noise_rand; + * use photon_rs::PhotonImage; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * add_noise_rand(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.add_noise_rand = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.add_noise_rand(photon_image.__wbg_ptr); +}; + +/** + * Add pink-tinted noise to an image. + * + * **[WASM SUPPORT IS AVAILABLE]**: Randomized thread pools cannot be created with WASM, but + * a workaround using js_sys::Math::random works now. + * # Arguments + * * `name` - A PhotonImage that contains a view into the image. + * + * # Example + * + * ```no_run + * // For example, to add pink-tinted noise to an image: + * use photon_rs::native::open_image; + * use photon_rs::noise::pink_noise; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * pink_noise(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.pink_noise = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.pink_noise(photon_image.__wbg_ptr); +}; + +/** + * Add a watermark to an image. + * + * # Arguments + * * `img` - A DynamicImage that contains a view into the image. + * * `watermark` - The watermark to be placed onto the `img` image. + * * `x` - The x coordinate where the watermark's top corner should be positioned. + * * `y` - The y coordinate where the watermark's top corner should be positioned. + * # Example + * + * ```no_run + * // For example, to add a watermark to an image at x: 30, y: 40: + * use photon_rs::multiple::watermark; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let water_mark = open_image("watermark.jpg").expect("File should open"); + * watermark(&mut img, &water_mark, 30_i64, 40_i64); + * ``` + * @param {PhotonImage} img + * @param {PhotonImage} watermark + * @param {bigint} x + * @param {bigint} y + */ +module.exports.watermark = function(img, watermark, x, y) { + _assertClass(img, PhotonImage); + _assertClass(watermark, PhotonImage); + wasm.watermark(img.__wbg_ptr, watermark.__wbg_ptr, x, y); +}; + +/** + * Blend two images together. + * + * The `blend_mode` (3rd param) determines which blending mode to use; change this for varying effects. + * The blend modes available include: `overlay`, `over`, `atop`, `xor`, `plus`, `multiply`, `burn`, + * `difference`, `soft_light`, `screen`, `hard_light`, `dodge`, `exclusion`, `lighten`, `darken` (more to come) + * NOTE: The first image must be smaller than the second image passed as params. + * If the first image were larger than the second, then there would be overflowing pixels which would have no corresponding pixels + * in the second image. + * # Arguments + * * `img` - A DynamicImage that contains a view into the image. + * * `img2` - The 2nd DynamicImage to be blended with the first. + * * `blend_mode` - The blending mode to use. See above for complete list of blend modes available. + * # Example + * + * ```no_run + * // For example, to blend two images with the `multiply` blend mode: + * use photon_rs::multiple::blend; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let img2 = open_image("img2.jpg").expect("File should open"); + * blend(&mut img, &img2, "multiply"); + * ``` + * @param {PhotonImage} photon_image + * @param {PhotonImage} photon_image2 + * @param {string} blend_mode + */ +module.exports.blend = function(photon_image, photon_image2, blend_mode) { + _assertClass(photon_image, PhotonImage); + _assertClass(photon_image2, PhotonImage); + const ptr0 = passStringToWasm0(blend_mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.blend(photon_image.__wbg_ptr, photon_image2.__wbg_ptr, ptr0, len0); +}; + +/** + * @param {number} width + * @param {number} height + * @returns {PhotonImage} + */ +module.exports.create_gradient = function(width, height) { + const ret = wasm.create_gradient(width, height); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply a gradient to an image. + * @param {PhotonImage} image + */ +module.exports.apply_gradient = function(image) { + _assertClass(image, PhotonImage); + wasm.apply_gradient(image.__wbg_ptr); +}; + +/** + * Solarization on the Blue channel. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::neue; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * neue(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.neue = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.neue(photon_image.__wbg_ptr); +}; + +/** + * Solarization on the Red and Green channels. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::lix; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * lix(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.lix = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.lix(photon_image.__wbg_ptr); +}; + +/** + * Solarization on the Red and Blue channels. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::ryo; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * ryo(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.ryo = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.ryo(photon_image.__wbg_ptr); +}; + +/** + * Apply a filter to an image. Over 20 filters are available. + * The filters are as follows: + * * **oceanic**: Add an aquamarine-tinted hue to an image. + * * **islands**: Aquamarine tint. + * * **marine**: Add a green/blue mixed hue to an image. + * * **seagreen**: Dark green hue, with tones of blue. + * * **flagblue**: Royal blue tint + * * **liquid**: Blue-inspired tint. + * * **diamante**: Custom filter with a blue/turquoise tint. + * * **radio**: Fallout-style radio effect. + * * **twenties**: Slight-blue tinted historical effect. + * * **rosetint**: Rose-tinted filter. + * * **mauve**: Purple-infused filter. + * * **bluechrome**: Blue monochrome effect. + * * **vintage**: Vintage filter with a red tint. + * * **perfume**: Increase the blue channel, with moderate increases in the Red and Green channels. + * * **serenity**: Custom filter with an increase in the Blue channel's values. + * # Arguments + * * `img` - A PhotonImage. + * * `filter_name` - The filter's name. Choose from the selection above, eg: "oceanic" + * # Example + * + * ```no_run + * // For example, to add a filter called "vintage" to an image: + * use photon_rs::filters::filter; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * filter(&mut img, "vintage"); + * ``` + * @param {PhotonImage} img + * @param {string} filter_name + */ +module.exports.filter = function(img, filter_name) { + _assertClass(img, PhotonImage); + const ptr0 = passStringToWasm0(filter_name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.filter(img.__wbg_ptr, ptr0, len0); +}; + +/** + * Apply a lofi effect to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::lofi; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * lofi(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.lofi = function(img) { + _assertClass(img, PhotonImage); + wasm.lofi(img.__wbg_ptr); +}; + +/** + * Apply a rose tint to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::pastel_pink; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * pastel_pink(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.pastel_pink = function(img) { + _assertClass(img, PhotonImage); + wasm.pastel_pink(img.__wbg_ptr); +}; + +/** + * Apply a vintage, golden hue to an image. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::golden; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * golden(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.golden = function(img) { + _assertClass(img, PhotonImage); + wasm.golden(img.__wbg_ptr); +}; + +/** + * Increased contrast filter effect. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::cali; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * cali(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.cali = function(img) { + _assertClass(img, PhotonImage); + wasm.cali(img.__wbg_ptr); +}; + +/** + * Greyscale effect with increased contrast. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::dramatic; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * dramatic(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.dramatic = function(img) { + _assertClass(img, PhotonImage); + wasm.dramatic(img.__wbg_ptr); +}; + +/** + * Monochrome tint effect with increased contrast + * + * # Arguments + * * `img` - A PhotonImage. + * * `rgb_color` - RGB color + * # Example + * + * ```no_run + * use photon_rs::filters::monochrome_tint; + * use photon_rs::native::open_image; + * use photon_rs::Rgb; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgb_color = Rgb::new(12, 12, 10); + * monochrome_tint(&mut img, rgb_color); + * ``` + * @param {PhotonImage} img + * @param {Rgb} rgb_color + */ +module.exports.monochrome_tint = function(img, rgb_color) { + _assertClass(img, PhotonImage); + _assertClass(rgb_color, Rgb); + var ptr0 = rgb_color.__destroy_into_raw(); + wasm.monochrome_tint(img.__wbg_ptr, ptr0); +}; + +/** + * Duotone effect with blue and purple tones. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::duotone_violette; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * duotone_violette(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.duotone_violette = function(img) { + _assertClass(img, PhotonImage); + wasm.duotone_violette(img.__wbg_ptr); +}; + +/** + * Duotone effect with purple tones. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::duotone_horizon; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * duotone_horizon(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.duotone_horizon = function(img) { + _assertClass(img, PhotonImage); + wasm.duotone_horizon(img.__wbg_ptr); +}; + +/** + * A duotone filter with a user-specified color and a gray color + * + * # Arguments + * * `img` - A PhotonImage. + * * `rgb_color` - RGB color + * # Example + * + * ```no_run + * use photon_rs::filters::duotone_tint; + * use photon_rs::native::open_image; + * use photon_rs::Rgb; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgb_color = Rgb::new(12, 12, 10); + * duotone_tint(&mut img, rgb_color); + * ``` + * @param {PhotonImage} img + * @param {Rgb} rgb_color + */ +module.exports.duotone_tint = function(img, rgb_color) { + _assertClass(img, PhotonImage); + _assertClass(rgb_color, Rgb); + var ptr0 = rgb_color.__destroy_into_raw(); + wasm.duotone_tint(img.__wbg_ptr, ptr0); +}; + +/** + * Duotone effect with a lilac hue + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::duotone_lilac; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * duotone_lilac(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.duotone_lilac = function(img) { + _assertClass(img, PhotonImage); + wasm.duotone_lilac(img.__wbg_ptr); +}; + +/** + * A duotone ochre tint effect + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::duotone_ochre; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * duotone_ochre(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.duotone_ochre = function(img) { + _assertClass(img, PhotonImage); + wasm.duotone_ochre(img.__wbg_ptr); +}; + +/** + * Apply a red hue, with increased contrast and brightness. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::firenze; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * firenze(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.firenze = function(img) { + _assertClass(img, PhotonImage); + wasm.firenze(img.__wbg_ptr); +}; + +/** + * Apply a greyscale effect with increased contrast. + * + * # Arguments + * * `img` - A PhotonImage. + * # Example + * + * ```no_run + * use photon_rs::filters::obsidian; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * obsidian(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.obsidian = function(img) { + _assertClass(img, PhotonImage); + wasm.obsidian(img.__wbg_ptr); +}; + +/** + * Crop an image. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to crop an image at (0, 0) to (500, 800) + * use photon_rs::native::{open_image}; + * use photon_rs::transform::crop; + * use photon_rs::PhotonImage; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let cropped_img: PhotonImage = crop(&img, 0_u32, 0_u32, 500_u32, 800_u32); + * // Write the contents of this image in JPG format. + * ``` + * @param {PhotonImage} photon_image + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @returns {PhotonImage} + */ +module.exports.crop = function(photon_image, x1, y1, x2, y2) { + _assertClass(photon_image, PhotonImage); + const ret = wasm.crop(photon_image.__wbg_ptr, x1, y1, x2, y2); + return PhotonImage.__wrap(ret); +}; + +/** + * @param {HTMLCanvasElement} source_canvas + * @param {number} width + * @param {number} height + * @param {number} left + * @param {number} top + * @returns {HTMLCanvasElement} + */ +module.exports.crop_img_browser = function(source_canvas, width, height, left, top) { + const ret = wasm.crop_img_browser(source_canvas, width, height, left, top); + return ret; +}; + +/** + * Flip an image horizontally. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to flip an image horizontally: + * use photon_rs::native::open_image; + * use photon_rs::transform::fliph; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * fliph(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.fliph = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.fliph(photon_image.__wbg_ptr); +}; + +/** + * Flip an image vertically. + * + * # Arguments + * * `img` - A PhotonImage. + * + * # Example + * + * ```no_run + * // For example, to flip an image vertically: + * use photon_rs::native::open_image; + * use photon_rs::transform::flipv; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * flipv(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.flipv = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.flipv(photon_image.__wbg_ptr); +}; + +/** + * Resize an image on the web. + * + * # Arguments + * * `img` - A PhotonImage. + * * `width` - New width. + * * `height` - New height. + * * `sampling_filter` - Nearest = 1, Triangle = 2, CatmullRom = 3, Gaussian = 4, Lanczos3 = 5 + * @param {PhotonImage} photon_img + * @param {number} width + * @param {number} height + * @param {SamplingFilter} sampling_filter + * @returns {HTMLCanvasElement} + */ +module.exports.resize_img_browser = function(photon_img, width, height, sampling_filter) { + _assertClass(photon_img, PhotonImage); + const ret = wasm.resize_img_browser(photon_img.__wbg_ptr, width, height, sampling_filter); + return ret; +}; + +/** + * Resize an image. + * + * # Arguments + * * `img` - A PhotonImage. + * * `width` - New width. + * * `height` - New height. + * * `sampling_filter` - Nearest = 1, Triangle = 2, CatmullRom = 3, Gaussian = 4, Lanczos3 = 5 + * @param {PhotonImage} photon_img + * @param {number} width + * @param {number} height + * @param {SamplingFilter} sampling_filter + * @returns {PhotonImage} + */ +module.exports.resize = function(photon_img, width, height, sampling_filter) { + _assertClass(photon_img, PhotonImage); + const ret = wasm.resize(photon_img.__wbg_ptr, width, height, sampling_filter); + return PhotonImage.__wrap(ret); +}; + +/** + * Resize image using seam carver. + * Resize only if new dimensions are smaller, than original image. + * # NOTE: This is still experimental feature, and pretty slow. + * + * # Arguments + * * `img` - A PhotonImage. + * * `width` - New width. + * * `height` - New height. + * + * # Example + * + * ```no_run + * // For example, resize image using seam carver: + * use photon_rs::native::open_image; + * use photon_rs::transform::seam_carve; + * use photon_rs::PhotonImage; + * + * let img = open_image("img.jpg").expect("File should open"); + * let result: PhotonImage = seam_carve(&img, 100_u32, 100_u32); + * ``` + * @param {PhotonImage} img + * @param {number} width + * @param {number} height + * @returns {PhotonImage} + */ +module.exports.seam_carve = function(img, width, height) { + _assertClass(img, PhotonImage); + const ret = wasm.seam_carve(img.__wbg_ptr, width, height); + return PhotonImage.__wrap(ret); +}; + +/** + * Shear the image along the X axis. + * A sheared PhotonImage is returned. + * + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `shear` - Amount to shear. + * + * # Example + * + * ```no_run + * // For example, to shear an image by 0.5: + * use photon_rs::native::open_image; + * use photon_rs::transform::shearx; + * + * let img = open_image("img.jpg").expect("File should open"); + * let sheared_img = shearx(&img, 0.5); + * ``` + * @param {PhotonImage} photon_img + * @param {number} shear + * @returns {PhotonImage} + */ +module.exports.shearx = function(photon_img, shear) { + _assertClass(photon_img, PhotonImage); + const ret = wasm.shearx(photon_img.__wbg_ptr, shear); + return PhotonImage.__wrap(ret); +}; + +/** + * Shear the image along the Y axis. + * A sheared PhotonImage is returned. + * + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `shear` - Amount to shear. + * + * # Example + * + * ```no_run + * // For example, to shear an image by 0.5: + * use photon_rs::native::open_image; + * use photon_rs::transform::sheary; + * + * let img = open_image("img.jpg").expect("File should open"); + * let sheared_img = sheary(&img, 0.5); + * ``` + * @param {PhotonImage} photon_img + * @param {number} shear + * @returns {PhotonImage} + */ +module.exports.sheary = function(photon_img, shear) { + _assertClass(photon_img, PhotonImage); + const ret = wasm.sheary(photon_img.__wbg_ptr, shear); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply uniform padding around the PhotonImage + * A padded PhotonImage is returned. + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `padding` - The amount of padding to be applied to the PhotonImage. + * * `padding_rgba` - Tuple containing the RGBA code for padding color. + * + * # Example + * + * ```no_run + * // For example, to apply a padding of 10 pixels around a PhotonImage: + * use photon_rs::transform::padding_uniform; + * use photon_rs::native::open_image; + * use photon_rs::Rgba; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8); + * padding_uniform(&img, 10_u32, rgba); + * ``` + * @param {PhotonImage} img + * @param {number} padding + * @param {Rgba} padding_rgba + * @returns {PhotonImage} + */ +module.exports.padding_uniform = function(img, padding, padding_rgba) { + _assertClass(img, PhotonImage); + _assertClass(padding_rgba, Rgba); + var ptr0 = padding_rgba.__destroy_into_raw(); + const ret = wasm.padding_uniform(img.__wbg_ptr, padding, ptr0); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply padding on the left side of the PhotonImage + * A padded PhotonImage is returned. + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `padding` - The amount of padding to be applied to the PhotonImage. + * * `padding_rgba` - Tuple containing the RGBA code for padding color. + * + * # Example + * + * ```no_run + * // For example, to apply a padding of 10 pixels on the left side of a PhotonImage: + * use photon_rs::transform::padding_left; + * use photon_rs::native::open_image; + * use photon_rs::Rgba; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8); + * padding_left(&img, 10_u32, rgba); + * ``` + * @param {PhotonImage} img + * @param {number} padding + * @param {Rgba} padding_rgba + * @returns {PhotonImage} + */ +module.exports.padding_left = function(img, padding, padding_rgba) { + _assertClass(img, PhotonImage); + _assertClass(padding_rgba, Rgba); + var ptr0 = padding_rgba.__destroy_into_raw(); + const ret = wasm.padding_left(img.__wbg_ptr, padding, ptr0); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply padding on the left side of the PhotonImage + * A padded PhotonImage is returned. + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `padding` - The amount of padding to be applied to the PhotonImage. + * * `padding_rgba` - Tuple containing the RGBA code for padding color. + * + * # Example + * + * ```no_run + * // For example, to apply a padding of 10 pixels on the right side of a PhotonImage: + * use photon_rs::transform::padding_right; + * use photon_rs::native::open_image; + * use photon_rs::Rgba; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8); + * padding_right(&img, 10_u32, rgba); + * ``` + * @param {PhotonImage} img + * @param {number} padding + * @param {Rgba} padding_rgba + * @returns {PhotonImage} + */ +module.exports.padding_right = function(img, padding, padding_rgba) { + _assertClass(img, PhotonImage); + _assertClass(padding_rgba, Rgba); + var ptr0 = padding_rgba.__destroy_into_raw(); + const ret = wasm.padding_right(img.__wbg_ptr, padding, ptr0); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply padding on the left side of the PhotonImage + * A padded PhotonImage is returned. + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `padding` - The amount of padding to be applied to the PhotonImage. + * * `padding_rgba` - Tuple containing the RGBA code for padding color. + * + * # Example + * + * ```no_run + * // For example, to apply a padding of 10 pixels on the top of a PhotonImage: + * use photon_rs::transform::padding_top; + * use photon_rs::native::open_image; + * use photon_rs::Rgba; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8); + * padding_top(&img, 10_u32, rgba); + * ``` + * @param {PhotonImage} img + * @param {number} padding + * @param {Rgba} padding_rgba + * @returns {PhotonImage} + */ +module.exports.padding_top = function(img, padding, padding_rgba) { + _assertClass(img, PhotonImage); + _assertClass(padding_rgba, Rgba); + var ptr0 = padding_rgba.__destroy_into_raw(); + const ret = wasm.padding_top(img.__wbg_ptr, padding, ptr0); + return PhotonImage.__wrap(ret); +}; + +/** + * Apply padding on the left side of the PhotonImage + * A padded PhotonImage is returned. + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `padding` - The amount of padding to be applied to the PhotonImage. + * * `padding_rgba` - Tuple containing the RGBA code for padding color. + * + * # Example + * + * ```no_run + * // For example, to apply a padding of 10 pixels on the bottom of a PhotonImage: + * use photon_rs::transform::padding_bottom; + * use photon_rs::native::open_image; + * use photon_rs::Rgba; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8); + * padding_bottom(&img, 10_u32, rgba); + * ``` + * @param {PhotonImage} img + * @param {number} padding + * @param {Rgba} padding_rgba + * @returns {PhotonImage} + */ +module.exports.padding_bottom = function(img, padding, padding_rgba) { + _assertClass(img, PhotonImage); + _assertClass(padding_rgba, Rgba); + var ptr0 = padding_rgba.__destroy_into_raw(); + const ret = wasm.padding_bottom(img.__wbg_ptr, padding, ptr0); + return PhotonImage.__wrap(ret); +}; + +/** + * Rotate the PhotonImage on an arbitrary angle + * A rotated PhotonImage is returned. + * + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `angle` - Rotation angle in degrees. + * + * # Example + * + * ```no_run + * // For example, to rotate a PhotonImage by 30 degrees: + * use photon_rs::native::open_image; + * use photon_rs::transform::rotate; + * + * let img = open_image("img.jpg").expect("File should open"); + * let rotated_img = rotate(&img, 30.0); + * ``` + * @param {PhotonImage} photon_img + * @param {number} angle + * @returns {PhotonImage} + */ +module.exports.rotate = function(photon_img, angle) { + _assertClass(photon_img, PhotonImage); + const ret = wasm.rotate(photon_img.__wbg_ptr, angle); + return PhotonImage.__wrap(ret); +}; + +/** + * Resample the PhotonImage. + * + * # Arguments + * * `img` - A PhotonImage. See the PhotonImage struct for details. + * * `dst_width` - Target width. + * * `dst_height` - Target height. + * + * # Example + * + * ```no_run + * // For example, to resample a PhotonImage to 1920x1080 size: + * use photon_rs::native::open_image; + * use photon_rs::transform::resample; + * + * let img = open_image("img.jpg").expect("File should open"); + * let rotated_img = resample(&img, 1920, 1080); + * ``` + * @param {PhotonImage} img + * @param {number} dst_width + * @param {number} dst_height + * @returns {PhotonImage} + */ +module.exports.resample = function(img, dst_width, dst_height) { + _assertClass(img, PhotonImage); + const ret = wasm.resample(img.__wbg_ptr, dst_width, dst_height); + return PhotonImage.__wrap(ret); +}; + +/** + * Adds an offset to the image by a certain number of pixels. + * + * This creates an RGB shift effect. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `channel_index`: The index of the channel to increment. 0 for red, 1 for green and 2 for blue. + * * `offset` - The offset is added to the pixels in the image. + * # Example + * + * ```no_run + * // For example, to offset pixels by 30 pixels on the red channel: + * use photon_rs::effects::offset; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * offset(&mut img, 0_usize, 30_u32); + * ``` + * @param {PhotonImage} photon_image + * @param {number} channel_index + * @param {number} offset + */ +module.exports.offset = function(photon_image, channel_index, offset) { + _assertClass(photon_image, PhotonImage); + wasm.offset(photon_image.__wbg_ptr, channel_index, offset); +}; + +/** + * Adds an offset to the red channel by a certain number of pixels. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `offset` - The offset you want to move the red channel by. + * # Example + * + * ```no_run + * // For example, to add an offset to the red channel by 30 pixels. + * use photon_rs::effects::offset_red; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * offset_red(&mut img, 30_u32); + * ``` + * @param {PhotonImage} img + * @param {number} offset_amt + */ +module.exports.offset_red = function(img, offset_amt) { + _assertClass(img, PhotonImage); + wasm.offset_red(img.__wbg_ptr, offset_amt); +}; + +/** + * Adds an offset to the green channel by a certain number of pixels. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `offset` - The offset you want to move the green channel by. + * # Example + * + * ```no_run + * // For example, to add an offset to the green channel by 30 pixels. + * use photon_rs::effects::offset_green; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * offset_green(&mut img, 30_u32); + * ``` + * @param {PhotonImage} img + * @param {number} offset_amt + */ +module.exports.offset_green = function(img, offset_amt) { + _assertClass(img, PhotonImage); + wasm.offset_green(img.__wbg_ptr, offset_amt); +}; + +/** + * Adds an offset to the blue channel by a certain number of pixels. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `offset_amt` - The offset you want to move the blue channel by. + * # Example + * // For example, to add an offset to the green channel by 40 pixels. + * + * ```no_run + * use photon_rs::effects::offset_blue; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * offset_blue(&mut img, 40_u32); + * ``` + * @param {PhotonImage} img + * @param {number} offset_amt + */ +module.exports.offset_blue = function(img, offset_amt) { + _assertClass(img, PhotonImage); + wasm.offset_blue(img.__wbg_ptr, offset_amt); +}; + +/** + * Adds multiple offsets to the image by a certain number of pixels (on two channels). + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `offset` - The offset is added to the pixels in the image. + * # Example + * + * ```no_run + * // For example, to add a 30-pixel offset to both the red and blue channels: + * use photon_rs::effects::multiple_offsets; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * multiple_offsets(&mut img, 30_u32, 0_usize, 2_usize); + * ``` + * @param {PhotonImage} photon_image + * @param {number} offset + * @param {number} channel_index + * @param {number} channel_index2 + */ +module.exports.multiple_offsets = function(photon_image, offset, channel_index, channel_index2) { + _assertClass(photon_image, PhotonImage); + wasm.multiple_offsets(photon_image.__wbg_ptr, offset, channel_index, channel_index2); +}; + +/** + * Halftoning effect. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example: + * use photon_rs::effects::halftone; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * halftone(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.halftone = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.halftone(photon_image.__wbg_ptr); +}; + +/** + * Reduces an image to the primary colours. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to add a primary colour effect to an image of type `DynamicImage`: + * use photon_rs::effects::primary; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * primary(&mut img); + * ``` + * @param {PhotonImage} img + */ +module.exports.primary = function(img) { + _assertClass(img, PhotonImage); + wasm.primary(img.__wbg_ptr); +}; + +/** + * Colorizes the green channels of the image. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to colorize an image of type `PhotonImage`: + * use photon_rs::effects::colorize; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * colorize(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.colorize = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.colorize(photon_image.__wbg_ptr); +}; + +/** + * Applies a solarizing effect to an image. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to colorize an image of type `PhotonImage`: + * use photon_rs::effects::solarize; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * solarize(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.solarize = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.solarize(photon_image.__wbg_ptr); +}; + +/** + * Applies a solarizing effect to an image and returns the resulting PhotonImage. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to solarize "retimg" an image of type `PhotonImage`: + * use photon_rs::effects::solarize_retimg; + * use photon_rs::native::open_image; + * use photon_rs::PhotonImage; + * + * let img = open_image("img.jpg").expect("File should open"); + * let result: PhotonImage = solarize_retimg(&img); + * ``` + * @param {PhotonImage} photon_image + * @returns {PhotonImage} + */ +module.exports.solarize_retimg = function(photon_image) { + _assertClass(photon_image, PhotonImage); + const ret = wasm.solarize_retimg(photon_image.__wbg_ptr); + return PhotonImage.__wrap(ret); +}; + +/** + * Adjust the brightness of an image by a factor. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `brightness` - A u8 to add or subtract to the brightness. To increase + * the brightness, pass a positive number (up to 255). To decrease the brightness, + * pass a negative number instead. + * # Example + * + * ```no_run + * use photon_rs::effects::adjust_brightness; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * adjust_brightness(&mut img, 10_i16); + * ``` + * @param {PhotonImage} photon_image + * @param {number} brightness + */ +module.exports.adjust_brightness = function(photon_image, brightness) { + _assertClass(photon_image, PhotonImage); + wasm.adjust_brightness(photon_image.__wbg_ptr, brightness); +}; + +/** + * Increase the brightness of an image by a constant. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `brightness` - A u8 to add to the brightness. + * # Example + * + * ```no_run + * use photon_rs::effects::inc_brightness; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * inc_brightness(&mut img, 10_u8); + * ``` + * @param {PhotonImage} photon_image + * @param {number} brightness + */ +module.exports.inc_brightness = function(photon_image, brightness) { + _assertClass(photon_image, PhotonImage); + wasm.inc_brightness(photon_image.__wbg_ptr, brightness); +}; + +/** + * Decrease the brightness of an image by a constant. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `brightness` - A u8 to subtract from the brightness. It should be a positive number, + * and this value will then be subtracted from the brightness. + * # Example + * + * ```no_run + * use photon_rs::effects::dec_brightness; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * dec_brightness(&mut img, 10_u8); + * ``` + * @param {PhotonImage} photon_image + * @param {number} brightness + */ +module.exports.dec_brightness = function(photon_image, brightness) { + _assertClass(photon_image, PhotonImage); + wasm.dec_brightness(photon_image.__wbg_ptr, brightness); +}; + +/** + * Adjust the contrast of an image by a factor. + * + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * * `contrast` - An f32 factor used to adjust contrast. Between [-255.0, 255.0]. The algorithm will + * clamp results if passed factor is out of range. + * # Example + * + * ```no_run + * use photon_rs::effects::adjust_contrast; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * adjust_contrast(&mut img, 30_f32); + * ``` + * @param {PhotonImage} photon_image + * @param {number} contrast + */ +module.exports.adjust_contrast = function(photon_image, contrast) { + _assertClass(photon_image, PhotonImage); + wasm.adjust_contrast(photon_image.__wbg_ptr, contrast); +}; + +/** + * Tint an image by adding an offset to averaged RGB channel values. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `r_offset` - The amount the R channel should be incremented by. + * * `g_offset` - The amount the G channel should be incremented by. + * * `b_offset` - The amount the B channel should be incremented by. + * # Example + * + * ```no_run + * // For example, to tint an image of type `PhotonImage`: + * use photon_rs::effects::tint; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * tint(&mut img, 10_u32, 20_u32, 15_u32); + * ``` + * @param {PhotonImage} photon_image + * @param {number} r_offset + * @param {number} g_offset + * @param {number} b_offset + */ +module.exports.tint = function(photon_image, r_offset, g_offset, b_offset) { + _assertClass(photon_image, PhotonImage); + wasm.tint(photon_image.__wbg_ptr, r_offset, g_offset, b_offset); +}; + +/** + * Horizontal strips. Divide an image into a series of equal-height strips, for an artistic effect. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `num_strips` - The number of strips + * # Example + * + * ```no_run + * // For example, to draw horizontal strips on a `PhotonImage`: + * use photon_rs::effects::horizontal_strips; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * horizontal_strips(&mut img, 8u8); + * ``` + * @param {PhotonImage} photon_image + * @param {number} num_strips + */ +module.exports.horizontal_strips = function(photon_image, num_strips) { + _assertClass(photon_image, PhotonImage); + wasm.horizontal_strips(photon_image.__wbg_ptr, num_strips); +}; + +/** + * Horizontal strips. Divide an image into a series of equal-width strips, for an artistic effect. Sepcify a color as well. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `num_strips` - The numbder of strips + * * `color` - Color of strips. + * # Example + * + * ```no_run + * // For example, to draw blue horizontal strips on a `PhotonImage`: + * use photon_rs::effects::color_horizontal_strips; + * use photon_rs::native::open_image; + * use photon_rs::Rgb; + * + * let color = Rgb::new(255u8, 0u8, 0u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * color_horizontal_strips(&mut img, 8u8, color); + * ``` + * @param {PhotonImage} photon_image + * @param {number} num_strips + * @param {Rgb} color + */ +module.exports.color_horizontal_strips = function(photon_image, num_strips, color) { + _assertClass(photon_image, PhotonImage); + _assertClass(color, Rgb); + var ptr0 = color.__destroy_into_raw(); + wasm.color_horizontal_strips(photon_image.__wbg_ptr, num_strips, ptr0); +}; + +/** + * Vertical strips. Divide an image into a series of equal-width strips, for an artistic effect. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `num_strips` - The numbder of strips + * # Example + * + * ```no_run + * // For example, to draw vertical strips on a `PhotonImage`: + * use photon_rs::effects::vertical_strips; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * vertical_strips(&mut img, 8u8); + * ``` + * @param {PhotonImage} photon_image + * @param {number} num_strips + */ +module.exports.vertical_strips = function(photon_image, num_strips) { + _assertClass(photon_image, PhotonImage); + wasm.vertical_strips(photon_image.__wbg_ptr, num_strips); +}; + +/** + * Vertical strips. Divide an image into a series of equal-width strips, for an artistic effect. Sepcify a color as well. + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `num_strips` - The numbder of strips + * * `color` - Color of strips. + * # Example + * + * ```no_run + * // For example, to draw red vertical strips on a `PhotonImage`: + * use photon_rs::effects::color_vertical_strips; + * use photon_rs::native::open_image; + * use photon_rs::Rgb; + * + * let color = Rgb::new(255u8, 0u8, 0u8); + * let mut img = open_image("img.jpg").expect("File should open"); + * color_vertical_strips(&mut img, 8u8, color); + * ``` + * @param {PhotonImage} photon_image + * @param {number} num_strips + * @param {Rgb} color + */ +module.exports.color_vertical_strips = function(photon_image, num_strips, color) { + _assertClass(photon_image, PhotonImage); + _assertClass(color, Rgb); + var ptr0 = color.__destroy_into_raw(); + wasm.color_vertical_strips(photon_image.__wbg_ptr, num_strips, ptr0); +}; + +/** + * Turn an image into an oil painting + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * * `radius` - Radius of each paint particle + * * `intesnity` - How artsy an Image should be + * # Example + * + * ```no_run + * // For example, to oil an image of type `PhotonImage`: + * use photon_rs::effects::oil; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * oil(&mut img, 4i32, 55.0); + * ``` + * @param {PhotonImage} photon_image + * @param {number} radius + * @param {number} intensity + */ +module.exports.oil = function(photon_image, radius, intensity) { + _assertClass(photon_image, PhotonImage); + wasm.oil(photon_image.__wbg_ptr, radius, intensity); +}; + +/** + * Turn an image into an frosted glass see through + * + * # Arguments + * * `img` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to turn an image of type `PhotonImage` into frosted glass see through: + * use photon_rs::effects::frosted_glass; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * frosted_glass(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.frosted_glass = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.frosted_glass(photon_image.__wbg_ptr); +}; + +/** + * Pixelize an image. + * + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * * `pixel_size` - Targeted pixel size of generated image. + * # Example + * + * ```no_run + * // For example, to turn an image of type `PhotonImage` into a pixelized image with 50 pixels blocks: + * use photon_rs::effects::pixelize; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * pixelize(&mut img, 50); + * ``` + * @param {PhotonImage} photon_image + * @param {number} pixel_size + */ +module.exports.pixelize = function(photon_image, pixel_size) { + _assertClass(photon_image, PhotonImage); + wasm.pixelize(photon_image.__wbg_ptr, pixel_size); +}; + +/** + * Normalizes an image by remapping its range of pixels values. Only RGB + * channels are processed and each channel is stretched to \[0, 255\] range + * independently. This process is also known as contrast stretching. + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * # Example + * + * ```no_run + * // For example, to turn an image of type `PhotonImage` into a normalized image: + * use photon_rs::effects::normalize; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * normalize(&mut img); + * ``` + * @param {PhotonImage} photon_image + */ +module.exports.normalize = function(photon_image) { + _assertClass(photon_image, PhotonImage); + wasm.normalize(photon_image.__wbg_ptr); +}; + +/** + * Applies Floyd-Steinberg dithering to an image. + * Only RGB channels are processed, alpha remains unchanged. + * # Arguments + * * `photon_image` - A PhotonImage that contains a view into the image. + * * `depth` - bits per channel. Clamped between 1 and 8. + * # Example + * + * ```no_run + * // For example, to turn an image of type `PhotonImage` into a dithered image: + * use photon_rs::effects::dither; + * use photon_rs::native::open_image; + * + * let mut img = open_image("img.jpg").expect("File should open"); + * let depth = 1; + * dither(&mut img, depth); + * ``` + * @param {PhotonImage} photon_image + * @param {number} depth + */ +module.exports.dither = function(photon_image, depth) { + _assertClass(photon_image, PhotonImage); + wasm.dither(photon_image.__wbg_ptr, depth); +}; + +/** + * @param {PhotonImage} photon_image + * @param {Rgb} color_a + * @param {Rgb} color_b + */ +module.exports.duotone = function(photon_image, color_a, color_b) { + _assertClass(photon_image, PhotonImage); + _assertClass(color_a, Rgb); + var ptr0 = color_a.__destroy_into_raw(); + _assertClass(color_b, Rgb); + var ptr1 = color_b.__destroy_into_raw(); + wasm.duotone(photon_image.__wbg_ptr, ptr0, ptr1); +}; + +/** + * Add bordered-text to an image. + * The only font available as of now is Roboto. + * Note: A graphic design/text-drawing library is currently being developed, so stay tuned. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `text` - Text string to be drawn to the image. + * * `x` - x-coordinate of where first letter's 1st pixel should be drawn. + * * `y` - y-coordinate of where first letter's 1st pixel should be drawn. + * * `font_size` - Font size in pixels of the text to be drawn. + * + * # Example + * + * ```no_run + * // For example to draw the string "Welcome to Photon!" at 10, 10: + * use photon_rs::native::open_image; + * use photon_rs::text::draw_text_with_border; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * draw_text_with_border(&mut img, "Welcome to Photon!", 10_i32, 10_i32, 90_f32); + * ``` + * @param {PhotonImage} photon_img + * @param {string} text + * @param {number} x + * @param {number} y + * @param {number} font_size + */ +module.exports.draw_text_with_border = function(photon_img, text, x, y, font_size) { + _assertClass(photon_img, PhotonImage); + const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.draw_text_with_border(photon_img.__wbg_ptr, ptr0, len0, x, y, font_size); +}; + +/** + * Add text to an image. + * The only font available as of now is Roboto. + * Note: A graphic design/text-drawing library is currently being developed, so stay tuned. + * + * # Arguments + * * `photon_image` - A PhotonImage. + * * `text` - Text string to be drawn to the image. + * * `x` - x-coordinate of where first letter's 1st pixel should be drawn. + * * `y` - y-coordinate of where first letter's 1st pixel should be drawn. + * * `font_size` - Font size in pixels of the text to be drawn. + * + * # Example + * + * ```no_run + * // For example to draw the string "Welcome to Photon!" at 10, 10: + * use photon_rs::native::open_image; + * use photon_rs::text::draw_text; + * + * // Open the image. A PhotonImage is returned. + * let mut img = open_image("img.jpg").expect("File should open"); + * draw_text(&mut img, "Welcome to Photon!", 10_i32, 10_i32, 90_f32); + * ``` + * @param {PhotonImage} photon_img + * @param {string} text + * @param {number} x + * @param {number} y + * @param {number} font_size + */ +module.exports.draw_text = function(photon_img, text, x, y, font_size) { + _assertClass(photon_img, PhotonImage); + const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.draw_text(photon_img.__wbg_ptr, ptr0, len0, x, y, font_size); +}; + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8ArrayMemory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} + +function getArrayU8FromWasm0(ptr, len) { + ptr = ptr >>> 0; + return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); +} + +function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_export_2.get(idx); + wasm.__externref_table_dealloc(idx); + return value; +} +/** + *! [temp] Check if WASM is supported. + */ +module.exports.run = function() { + const ret = wasm.run(); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } +}; + +/** + * Get the ImageData from a 2D canvas context + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} ctx + * @returns {ImageData} + */ +module.exports.get_image_data = function(canvas, ctx) { + const ret = wasm.get_image_data(canvas, ctx); + return ret; +}; + +/** + * Place a PhotonImage onto a 2D canvas. + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} ctx + * @param {PhotonImage} new_image + */ +module.exports.putImageData = function(canvas, ctx, new_image) { + _assertClass(new_image, PhotonImage); + var ptr0 = new_image.__destroy_into_raw(); + wasm.putImageData(canvas, ctx, ptr0); +}; + +/** + * Convert a HTML5 Canvas Element to a PhotonImage. + * + * This converts the ImageData found in the canvas context to a PhotonImage, + * which can then have effects or filters applied to it. + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} ctx + * @returns {PhotonImage} + */ +module.exports.open_image = function(canvas, ctx) { + const ret = wasm.open_image(canvas, ctx); + return PhotonImage.__wrap(ret); +}; + +/** + * Convert ImageData to a raw pixel vec of u8s. + * @param {ImageData} imgdata + * @returns {Uint8Array} + */ +module.exports.to_raw_pixels = function(imgdata) { + const ret = wasm.to_raw_pixels(imgdata); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; +}; + +/** + * Convert a base64 string to a PhotonImage. + * @param {string} base64 + * @returns {PhotonImage} + */ +module.exports.base64_to_image = function(base64) { + const ptr0 = passStringToWasm0(base64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.base64_to_image(ptr0, len0); + return PhotonImage.__wrap(ret); +}; + +/** + * Convert a base64 string to a Vec of u8s. + * @param {string} base64 + * @returns {Uint8Array} + */ +module.exports.base64_to_vec = function(base64) { + const ptr0 = passStringToWasm0(base64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.base64_to_vec(ptr0, len0); + var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v2; +}; + +/** + * Convert a PhotonImage to JS-compatible ImageData. + * @param {PhotonImage} photon_image + * @returns {ImageData} + */ +module.exports.to_image_data = function(photon_image) { + _assertClass(photon_image, PhotonImage); + var ptr0 = photon_image.__destroy_into_raw(); + const ret = wasm.to_image_data(ptr0); + return ret; +}; + +function isLikeNone(x) { + return x === undefined || x === null; +} + +function addToExternrefTable0(obj) { + const idx = wasm.__externref_table_alloc(); + wasm.__wbindgen_export_2.set(idx, obj); + return idx; +} + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + const idx = addToExternrefTable0(e); + wasm.__wbindgen_exn_store(idx); + } +} + +let cachedUint8ClampedArrayMemory0 = null; + +function getUint8ClampedArrayMemory0() { + if (cachedUint8ClampedArrayMemory0 === null || cachedUint8ClampedArrayMemory0.byteLength === 0) { + cachedUint8ClampedArrayMemory0 = new Uint8ClampedArray(wasm.memory.buffer); + } + return cachedUint8ClampedArrayMemory0; +} + +function getClampedArrayU8FromWasm0(ptr, len) { + ptr = ptr >>> 0; + return getUint8ClampedArrayMemory0().subarray(ptr / 1, ptr / 1 + len); +} + +module.exports.SamplingFilter = Object.freeze({ Nearest:1,"1":"Nearest",Triangle:2,"2":"Triangle",CatmullRom:3,"3":"CatmullRom",Gaussian:4,"4":"Gaussian",Lanczos3:5,"5":"Lanczos3", }); + +const PhotonImageFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_photonimage_free(ptr >>> 0, 1)); +/** + * Provides the image's height, width, and contains the image's raw pixels. + * For use when communicating between JS and WASM, and also natively. + */ +class PhotonImage { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(PhotonImage.prototype); + obj.__wbg_ptr = ptr; + PhotonImageFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + PhotonImageFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_photonimage_free(ptr, 0); + } + /** + * Create a new PhotonImage from a Vec of u8s, which represent raw pixels. + * @param {Uint8Array} raw_pixels + * @param {number} width + * @param {number} height + */ + constructor(raw_pixels, width, height) { + const ptr0 = passArray8ToWasm0(raw_pixels, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.photonimage_new(ptr0, len0, width, height); + this.__wbg_ptr = ret >>> 0; + PhotonImageFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Create a new PhotonImage from a base64 string. + * @param {string} base64 + * @returns {PhotonImage} + */ + static new_from_base64(base64) { + const ptr0 = passStringToWasm0(base64, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.base64_to_image(ptr0, len0); + return PhotonImage.__wrap(ret); + } + /** + * Create a new PhotonImage from a byteslice. + * @param {Uint8Array} vec + * @returns {PhotonImage} + */ + static new_from_byteslice(vec) { + const ptr0 = passArray8ToWasm0(vec, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.photonimage_new_from_byteslice(ptr0, len0); + return PhotonImage.__wrap(ret); + } + /** + * Create a new PhotonImage from a Blob/File. + * @param {Blob} blob + * @returns {PhotonImage} + */ + static new_from_blob(blob) { + const ret = wasm.photonimage_new_from_blob(blob); + return PhotonImage.__wrap(ret); + } + /** + * Create a new PhotonImage from a HTMLImageElement + * @param {HTMLImageElement} image + * @returns {PhotonImage} + */ + static new_from_image(image) { + const ret = wasm.photonimage_new_from_image(image); + return PhotonImage.__wrap(ret); + } + /** + * Get the width of the PhotonImage. + * @returns {number} + */ + get_width() { + const ret = wasm.photonimage_get_width(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Get the PhotonImage's pixels as a Vec of u8s. + * @returns {Uint8Array} + */ + get_raw_pixels() { + const ret = wasm.photonimage_get_raw_pixels(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Get the height of the PhotonImage. + * @returns {number} + */ + get_height() { + const ret = wasm.photonimage_get_height(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Convert the PhotonImage to base64. + * @returns {string} + */ + get_base64() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.photonimage_get_base64(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Convert the PhotonImage to raw bytes. Returns PNG. + * @returns {Uint8Array} + */ + get_bytes() { + const ret = wasm.photonimage_get_bytes(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Convert the PhotonImage to raw bytes. Returns a JPEG. + * @param {number} quality + * @returns {Uint8Array} + */ + get_bytes_jpeg(quality) { + const ret = wasm.photonimage_get_bytes_jpeg(this.__wbg_ptr, quality); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Convert the PhotonImage to raw bytes. Returns a WEBP. + * @returns {Uint8Array} + */ + get_bytes_webp() { + const ret = wasm.photonimage_get_bytes_webp(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Convert the PhotonImage's raw pixels to JS-compatible ImageData. + * @returns {ImageData} + */ + get_image_data() { + const ret = wasm.photonimage_get_image_data(this.__wbg_ptr); + return ret; + } + /** + * Convert ImageData to raw pixels, and update the PhotonImage's raw pixels to this. + * @param {ImageData} img_data + */ + set_imgdata(img_data) { + wasm.photonimage_set_imgdata(this.__wbg_ptr, img_data); + } + /** + * Calculates estimated filesize and returns number of bytes + * @returns {bigint} + */ + get_estimated_filesize() { + const ret = wasm.photonimage_get_estimated_filesize(this.__wbg_ptr); + return BigInt.asUintN(64, ret); + } +} +module.exports.PhotonImage = PhotonImage; + +const RgbFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_rgb_free(ptr >>> 0, 1)); +/** + * RGB color type. + */ +class Rgb { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + RgbFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_rgb_free(ptr, 0); + } + /** + * Create a new RGB struct. + * @param {number} r + * @param {number} g + * @param {number} b + */ + constructor(r, g, b) { + const ret = wasm.rgb_new(r, g, b); + this.__wbg_ptr = ret >>> 0; + RgbFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Set the Red value. + * @param {number} r + */ + set_red(r) { + wasm.rgb_set_red(this.__wbg_ptr, r); + } + /** + * Get the Green value. + * @param {number} g + */ + set_green(g) { + wasm.rgb_set_green(this.__wbg_ptr, g); + } + /** + * Set the Blue value. + * @param {number} b + */ + set_blue(b) { + wasm.rgb_set_blue(this.__wbg_ptr, b); + } + /** + * Get the Red value. + * @returns {number} + */ + get_red() { + const ret = wasm.rgb_get_red(this.__wbg_ptr); + return ret; + } + /** + * Get the Green value. + * @returns {number} + */ + get_green() { + const ret = wasm.rgb_get_green(this.__wbg_ptr); + return ret; + } + /** + * Get the Blue value. + * @returns {number} + */ + get_blue() { + const ret = wasm.rgb_get_blue(this.__wbg_ptr); + return ret; + } +} +module.exports.Rgb = Rgb; + +const RgbaFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_rgba_free(ptr >>> 0, 1)); +/** + * RGBA color type. + */ +class Rgba { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + RgbaFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_rgba_free(ptr, 0); + } + /** + * Create a new RGBA struct. + * @param {number} r + * @param {number} g + * @param {number} b + * @param {number} a + */ + constructor(r, g, b, a) { + const ret = wasm.rgba_new(r, g, b, a); + this.__wbg_ptr = ret >>> 0; + RgbaFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Set the Red value. + * @param {number} r + */ + set_red(r) { + wasm.rgb_set_red(this.__wbg_ptr, r); + } + /** + * Get the Green value. + * @param {number} g + */ + set_green(g) { + wasm.rgb_set_green(this.__wbg_ptr, g); + } + /** + * Set the Blue value. + * @param {number} b + */ + set_blue(b) { + wasm.rgb_set_blue(this.__wbg_ptr, b); + } + /** + * Set the alpha value. + * @param {number} a + */ + set_alpha(a) { + wasm.rgba_set_alpha(this.__wbg_ptr, a); + } + /** + * Get the Red value. + * @returns {number} + */ + get_red() { + const ret = wasm.rgb_get_red(this.__wbg_ptr); + return ret; + } + /** + * Get the Green value. + * @returns {number} + */ + get_green() { + const ret = wasm.rgb_get_green(this.__wbg_ptr); + return ret; + } + /** + * Get the Blue value. + * @returns {number} + */ + get_blue() { + const ret = wasm.rgb_get_blue(this.__wbg_ptr); + return ret; + } + /** + * Get the alpha value for this color. + * @returns {number} + */ + get_alpha() { + const ret = wasm.rgba_get_alpha(this.__wbg_ptr); + return ret; + } +} +module.exports.Rgba = Rgba; + +module.exports.__wbg_new_abda76e883ba8a5f = function() { + const ret = new Error(); + return ret; +}; + +module.exports.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) { + const ret = arg1.stack; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); +}; + +module.exports.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + console.error(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } +}; + +module.exports.__wbg_instanceof_Window_c4b70662a0d2c5ec = function(arg0) { + let result; + try { + result = arg0 instanceof Window; + } catch (_) { + result = false; + } + const ret = result; + return ret; +}; + +module.exports.__wbg_document_e5c1786dea6542e4 = function(arg0) { + const ret = arg0.document; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); +}; + +module.exports.__wbg_body_e70ae6abd01ae584 = function(arg0) { + const ret = arg0.body; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); +}; + +module.exports.__wbg_createElement_5d4c76f218b78145 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.createElement(getStringFromWasm0(arg1, arg2)); + return ret; +}, arguments) }; + +module.exports.__wbg_width_4c6f0048d64cf86b = function(arg0) { + const ret = arg0.width; + return ret; +}; + +module.exports.__wbg_height_21f0d3fd8f753394 = function(arg0) { + const ret = arg0.height; + return ret; +}; + +module.exports.__wbg_width_79e0847ed5883b03 = function(arg0) { + const ret = arg0.width; + return ret; +}; + +module.exports.__wbg_height_e4e4e4779f8feac0 = function(arg0) { + const ret = arg0.height; + return ret; +}; + +module.exports.__wbg_data_fda507064d127f5b = function(arg0, arg1) { + const ret = arg1.data; + const ptr1 = passArray8ToWasm0(ret, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); +}; + +module.exports.__wbg_newwithu8clampedarrayandsh_1fddccb3a94a5e05 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = new ImageData(getClampedArrayU8FromWasm0(arg0, arg1), arg2 >>> 0, arg3 >>> 0); + return ret; +}, arguments) }; + +module.exports.__wbg_instanceof_CanvasRenderingContext2d_3abbe7ec7af32cae = function(arg0) { + let result; + try { + result = arg0 instanceof CanvasRenderingContext2D; + } catch (_) { + result = false; + } + const ret = result; + return ret; +}; + +module.exports.__wbg_drawImage_fede06db74e39a60 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.drawImage(arg1, arg2, arg3); +}, arguments) }; + +module.exports.__wbg_drawImage_f395c8e43c79a909 = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) { + arg0.drawImage(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); +}, arguments) }; + +module.exports.__wbg_getImageData_5e1c242046e6b59e = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + const ret = arg0.getImageData(arg1, arg2, arg3, arg4); + return ret; +}, arguments) }; + +module.exports.__wbg_putImageData_a8b3e177ee06d521 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.putImageData(arg1, arg2, arg3); +}, arguments) }; + +module.exports.__wbg_instanceof_HtmlCanvasElement_25d964a0dde6717e = function(arg0) { + let result; + try { + result = arg0 instanceof HTMLCanvasElement; + } catch (_) { + result = false; + } + const ret = result; + return ret; +}; + +module.exports.__wbg_width_dc225e55343b745e = function(arg0) { + const ret = arg0.width; + return ret; +}; + +module.exports.__wbg_setwidth_488780db69b08846 = function(arg0, arg1) { + arg0.width = arg1 >>> 0; +}; + +module.exports.__wbg_height_3a8bec2f3fe71b26 = function(arg0) { + const ret = arg0.height; + return ret; +}; + +module.exports.__wbg_setheight_1761808c18403921 = function(arg0, arg1) { + arg0.height = arg1 >>> 0; +}; + +module.exports.__wbg_getContext_fc99dbd3a9a7e318 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.getContext(getStringFromWasm0(arg1, arg2)); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); +}, arguments) }; + +module.exports.__wbg_settextContent_f82a86a8df347e1c = function(arg0, arg1, arg2) { + arg0.textContent = arg1 === 0 ? undefined : getStringFromWasm0(arg1, arg2); +}; + +module.exports.__wbg_appendChild_fa3b00dade9fc4cf = function() { return handleError(function (arg0, arg1) { + const ret = arg0.appendChild(arg1); + return ret; +}, arguments) }; + +module.exports.__wbg_newnoargs_e643855c6572a4a8 = function(arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return ret; +}; + +module.exports.__wbg_call_f96b398515635514 = function() { return handleError(function (arg0, arg1) { + const ret = arg0.call(arg1); + return ret; +}, arguments) }; + +module.exports.__wbg_self_b9aad7f1c618bfaf = function() { return handleError(function () { + const ret = self.self; + return ret; +}, arguments) }; + +module.exports.__wbg_window_55e469842c98b086 = function() { return handleError(function () { + const ret = window.window; + return ret; +}, arguments) }; + +module.exports.__wbg_globalThis_d0957e302752547e = function() { return handleError(function () { + const ret = globalThis.globalThis; + return ret; +}, arguments) }; + +module.exports.__wbg_global_ae2f87312b8987fb = function() { return handleError(function () { + const ret = global.global; + return ret; +}, arguments) }; + +module.exports.__wbindgen_is_undefined = function(arg0) { + const ret = arg0 === undefined; + return ret; +}; + +module.exports.__wbg_buffer_fcbfb6d88b2732e9 = function(arg0) { + const ret = arg0.buffer; + return ret; +}; + +module.exports.__wbg_new_bc5d9aad3f9ac80e = function(arg0) { + const ret = new Uint8Array(arg0); + return ret; +}; + +module.exports.__wbg_set_4b3aa8445ac1e91c = function(arg0, arg1, arg2) { + arg0.set(arg1, arg2 >>> 0); +}; + +module.exports.__wbg_length_d9c4ded7e708c6a1 = function(arg0) { + const ret = arg0.length; + return ret; +}; + +module.exports.__wbindgen_debug_string = function(arg0, arg1) { + const ret = debugString(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); +}; + +module.exports.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); +}; + +module.exports.__wbindgen_memory = function() { + const ret = wasm.memory; + return ret; +}; + +module.exports.__wbindgen_init_externref_table = function() { + const table = wasm.__wbindgen_export_2; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + ; +}; + +const path = __webpack_require__.ab + "photon_rs_bg.wasm"; +const bytes = (__webpack_require__(79896).readFileSync)(__webpack_require__.ab + "photon_rs_bg.wasm"); + +const wasmModule = new WebAssembly.Module(bytes); +const wasmInstance = new WebAssembly.Instance(wasmModule, imports); +wasm = wasmInstance.exports; +module.exports.__wasm = wasm; + +wasm.__wbindgen_start(); + + + +/***/ }) + +}; diff --git a/dist/action/730.index.js b/dist/action/730.index.js new file mode 100644 index 000000000..48b040fca --- /dev/null +++ b/dist/action/730.index.js @@ -0,0 +1,13 @@ +export const id = 730; +export const ids = [730]; +export const modules = { + +/***/ 10730: +/***/ ((module) => { + +module.exports = eval("require")("kerberos"); + + +/***/ }) + +}; diff --git a/dist/action/731.index.js b/dist/action/731.index.js new file mode 100644 index 000000000..ed683b45d --- /dev/null +++ b/dist/action/731.index.js @@ -0,0 +1,290 @@ +export const id = 731; +export const ids = [731]; +export const modules = { + +/***/ 30731: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ stream: () => (/* binding */ stream), +/* harmony export */ streamSimple: () => (/* binding */ streamSimple) +/* harmony export */ }); +/* harmony import */ var openai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3840); +/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(25941); +/* harmony import */ var _utils_error_body_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20372); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(45174); +/* harmony import */ var _utils_headers_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(82003); +/* harmony import */ var _utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(55278); +/* harmony import */ var _utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67982); +/* harmony import */ var _utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(46863); +/* harmony import */ var _utils_transcript_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(19883); +/* harmony import */ var _constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(37776); +/* harmony import */ var _openai_prompt_cache_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(95304); +/* harmony import */ var _openai_responses_shared_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(33115); +/* harmony import */ var _simple_options_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(18296); + + + + + + + + + + + + + +const DEFAULT_AZURE_API_VERSION = "v1"; +const AZURE_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode", "azure-openai-responses"]); +// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265 +const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16; +function parseDeploymentNameMap(value) { + const map = new Map(); + if (!value) + return map; + for (const entry of value.split(",")) { + const trimmed = entry.trim(); + if (!trimmed) + continue; + const [modelId, deploymentName] = trimmed.split("=", 2); + if (!modelId || !deploymentName) + continue; + map.set(modelId.trim(), deploymentName.trim()); + } + return map; +} +function resolveDeploymentName(model, options) { + if (options?.azureDeploymentName) { + return options.azureDeploymentName; + } + const mappedDeployment = parseDeploymentNameMap((0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__/* .getProviderEnvValue */ .Y)("AZURE_OPENAI_DEPLOYMENT_NAME_MAP", options?.env)).get(model.id); + return mappedDeployment || model.id; +} +function formatAzureOpenAIError(error) { + return (0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_2__/* .formatProviderError */ .lR)((0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_2__/* .normalizeProviderError */ .Jo)(error), "Azure OpenAI API error"); +} +/** + * Generate function for Azure OpenAI Responses API + */ +const stream = (model, context, options) => { + const stream = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_3__/* .AssistantMessageEventStream */ .Q2(); + const normalizedContext = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_4__/* .resolveTranscript */ .lw)(context, model.compat?.supportsMidConvoSystemMessages); + // Start async processing + (async () => { + const deploymentName = resolveDeploymentName(model, options); + const output = { + role: "assistant", + content: [], + api: "azure-openai-responses", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + try { + // Create Azure OpenAI client + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const client = createClient(model, apiKey, options); + const grammarToolInputProperties = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__/* .createGrammarToolInputProperties */ .PJ)((0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_4__/* .getDeclaredTools */ .Wg)(normalizedContext.messages), model.compat?.supportsOpenAIGrammarTools ?? false); + let params = buildParams(model, normalizedContext, options, deploymentName, grammarToolInputProperties); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== undefined) { + params = nextParams; + } + const requestOptions = { + ...(options?.signal ? { signal: options.signal } : {}), + ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), + maxRetries: 0, + }; + const { data: openaiStream, response } = await (0,_utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_6__/* .retryProviderRequest */ .T)(() => client.responses.create(params, requestOptions).withResponse(), { + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + signal: options?.signal, + }); + await options?.onResponse?.({ status: response.status, headers: (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_7__/* .headersToRecord */ .j)(response.headers) }, model); + stream.push({ type: "start", partial: output }); + await (0,_openai_responses_shared_js__WEBPACK_IMPORTED_MODULE_8__/* .processResponsesStream */ .KB)(openaiStream, output, stream, model, { grammarToolInputProperties }); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "pending") { + throw new Error("Azure OpenAI Responses stream ended without a stop reason"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + for (const block of output.content) { + delete block.index; + // Streaming scratch buffers are only used during parsing; never persist them. + delete block.partialJson; + delete block.customInput; + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = formatAzureOpenAIError(error); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +const streamSimple = (model, context, options) => { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = { + ...(0,_simple_options_js__WEBPACK_IMPORTED_MODULE_9__/* .buildBaseOptions */ .QP)(model, context, options, apiKey), + toolChoice: options?.toolChoice, + }; + const clampedReasoning = options?.reasoning ? (0,_models_js__WEBPACK_IMPORTED_MODULE_10__/* .clampThinkingLevel */ .Kt)(model, options.reasoning) : undefined; + const reasoningEffort = clampedReasoning === "off" ? undefined : clampedReasoning; + return stream(model, context, { + ...base, + reasoningEffort, + }); +}; +function normalizeAzureBaseUrl(baseUrl) { + const trimmed = baseUrl.trim().replace(/\/+$/, ""); + let url; + try { + url = new URL(trimmed); + } + catch { + throw new Error(`Invalid Azure OpenAI base URL: ${baseUrl}`); + } + const isAzureHost = url.hostname.endsWith(".openai.azure.com") || + url.hostname.endsWith(".cognitiveservices.azure.com") || + url.hostname.endsWith(".ai.azure.com"); + const normalizedPath = url.pathname.replace(/\/+$/, ""); + // Ensure Azure hosts have /openai/v1 as base path so the AzureOpenAI SDK + // can append /deployments//... and ?api-version=v1 correctly. + if (isAzureHost && + (normalizedPath === "" || + normalizedPath === "/" || + normalizedPath === "/openai" || + normalizedPath === "/openai/v1/responses")) { + url.pathname = "/openai/v1"; + url.search = ""; + } + return url.toString().replace(/\/+$/, ""); +} +function buildDefaultBaseUrl(resourceName) { + return `https://${resourceName}.openai.azure.com/openai/v1`; +} +function resolveAzureConfig(model, options) { + const apiVersion = options?.azureApiVersion || + (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__/* .getProviderEnvValue */ .Y)("AZURE_OPENAI_API_VERSION", options?.env) || + DEFAULT_AZURE_API_VERSION; + const baseUrl = options?.azureBaseUrl?.trim() || (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__/* .getProviderEnvValue */ .Y)("AZURE_OPENAI_BASE_URL", options?.env)?.trim() || undefined; + const resourceName = options?.azureResourceName || (0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__/* .getProviderEnvValue */ .Y)("AZURE_OPENAI_RESOURCE_NAME", options?.env); + let resolvedBaseUrl = baseUrl; + if (!resolvedBaseUrl && resourceName) { + resolvedBaseUrl = buildDefaultBaseUrl(resourceName); + } + if (!resolvedBaseUrl && model.baseUrl) { + resolvedBaseUrl = model.baseUrl; + } + if (!resolvedBaseUrl) { + throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl."); + } + return { + baseUrl: normalizeAzureBaseUrl(resolvedBaseUrl), + apiVersion, + }; +} +function createClient(model, apiKey, options) { + const headers = { "User-Agent": (0,_utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_11__/* .getPiUserAgent */ .w)(), ...model.headers }; + if (options?.headers) { + Object.assign(headers, options.headers); + } + const { baseUrl, apiVersion } = resolveAzureConfig(model, options); + return new openai__WEBPACK_IMPORTED_MODULE_0__/* .AzureOpenAI */ .AC({ + apiKey, + apiVersion, + dangerouslyAllowBrowser: true, + fetch: options?.fetch, + defaultHeaders: headers, + baseURL: baseUrl, + }); +} +function buildParams(model, context, options, deploymentName, grammarToolInputProperties = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__/* .createGrammarToolInputProperties */ .PJ)((0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_4__/* .getDeclaredTools */ .Wg)(context.messages), model.compat?.supportsOpenAIGrammarTools ?? false)) { + const supportsAdditionalTools = model.compat?.supportsAdditionalTools ?? false; + const supportsToolSearch = model.compat?.supportsToolSearch ?? false; + const transcriptTools = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_4__/* .resolveTranscriptTools */ .eW)(context.messages, supportsAdditionalTools || supportsToolSearch); + const messages = (0,_openai_responses_shared_js__WEBPACK_IMPORTED_MODULE_8__/* .convertResponsesMessages */ .iq)(model, context, AZURE_TOOL_CALL_PROVIDERS, { + grammarToolInputProperties, + supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false, + supportsAdditionalTools, + supportsToolSearch, + toolOptions: { + supportsStrictMode: model.compat?.supportsStrictMode ?? true, + supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false, + }, + }); + const params = { + model: deploymentName, + input: messages, + stream: true, + prompt_cache_key: (0,_openai_prompt_cache_js__WEBPACK_IMPORTED_MODULE_12__/* .clampOpenAIPromptCacheKey */ .l)(options?.sessionId), + store: false, + }; + if (options?.maxTokens) { + params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS); + } + if (options?.temperature !== undefined) { + params.temperature = options?.temperature; + } + if (transcriptTools.requestTools.length > 0) { + params.tools = (0,_openai_responses_shared_js__WEBPACK_IMPORTED_MODULE_8__/* .convertResponsesTools */ .hX)(transcriptTools.requestTools, { + supportsStrictMode: model.compat?.supportsStrictMode ?? true, + supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false, + }); + } + if (options?.toolChoice !== undefined) { + params.tool_choice = options.toolChoice; + } + if (model.reasoning) { + if (options?.reasoningEffort || options?.reasoningSummary) { + const effort = options?.reasoningEffort + ? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort) + : "medium"; + params.reasoning = { + effort: effort, + summary: options?.reasoningSummary || "auto", + }; + params.include = ["reasoning.encrypted_content"]; + } + else if (model.thinkingLevelMap?.off !== null) { + params.reasoning = { + effort: (model.thinkingLevelMap?.off ?? "none"), + }; + } + } + // Last so custom keys override the named request fields. + if (options?.samplingParams) { + Object.assign(params, options.samplingParams); + } + return params; +} +//# sourceMappingURL=azure-openai-responses.js.map + +/***/ }) + +}; diff --git a/dist/action/758.index.js b/dist/action/758.index.js new file mode 100644 index 000000000..2cba92529 --- /dev/null +++ b/dist/action/758.index.js @@ -0,0 +1,48505 @@ +export const id = 758; +export const ids = [758]; +export const modules = { + +/***/ 31934: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +const PROTECTED_KEYS = { + REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"), + X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"), + TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID"), + TRACEPARENT: Symbol.for("_AWS_LAMBDA_TRACEPARENT"), + TRACESTATE: Symbol.for("_AWS_LAMBDA_TRACESTATE"), + BAGGAGE: Symbol.for("_AWS_LAMBDA_BAGGAGE"), +}; +const NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? ""); +if (!NO_GLOBAL_AWS_LAMBDA) { + globalThis.awslambda = globalThis.awslambda || {}; +} +class InvokeStoreBase { + static PROTECTED_KEYS = PROTECTED_KEYS; + isProtectedKey(key) { + return Object.values(PROTECTED_KEYS).includes(key); + } + getRequestId() { + return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-"; + } + getXRayTraceId() { + return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID); + } + getTenantId() { + return this.get(PROTECTED_KEYS.TENANT_ID); + } + getTraceparent() { + return this.get(PROTECTED_KEYS.TRACEPARENT); + } + getTracestate() { + return this.get(PROTECTED_KEYS.TRACESTATE); + } + getBaggage() { + return this.get(PROTECTED_KEYS.BAGGAGE); + } +} +class InvokeStoreSingle extends InvokeStoreBase { + currentContext; + getContext() { + return this.currentContext; + } + hasContext() { + return this.currentContext !== undefined; + } + get(key) { + return this.currentContext?.[key]; + } + set(key, value) { + if (this.isProtectedKey(key)) { + throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); + } + this.currentContext = this.currentContext || {}; + this.currentContext[key] = value; + } + run(context, fn) { + this.currentContext = context; + return fn(); + } +} +class InvokeStoreMulti extends InvokeStoreBase { + als; + static async create() { + const instance = new InvokeStoreMulti(); + const asyncHooks = await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 16698, 23)); + instance.als = new asyncHooks.AsyncLocalStorage(); + return instance; + } + getContext() { + return this.als.getStore(); + } + hasContext() { + return this.als.getStore() !== undefined; + } + get(key) { + return this.als.getStore()?.[key]; + } + set(key, value) { + if (this.isProtectedKey(key)) { + throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); + } + const store = this.als.getStore(); + if (!store) { + throw new Error("No context available"); + } + store[key] = value; + } + run(context, fn) { + return this.als.run(context, fn); + } +} +exports.InvokeStore = void 0; +(function (InvokeStore) { + let instance = null; + async function getInstanceAsync(forceInvokeStoreMulti) { + if (!instance) { + instance = (async () => { + const isMulti = forceInvokeStoreMulti === true || "AWS_LAMBDA_MAX_CONCURRENCY" in process.env; + const newInstance = isMulti + ? await InvokeStoreMulti.create() + : new InvokeStoreSingle(); + if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) { + return globalThis.awslambda.InvokeStore; + } + else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) { + globalThis.awslambda.InvokeStore = newInstance; + return newInstance; + } + else { + return newInstance; + } + })(); + } + return instance; + } + InvokeStore.getInstanceAsync = getInstanceAsync; + InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" + ? { + reset: () => { + instance = null; + if (globalThis.awslambda?.InvokeStore) { + delete globalThis.awslambda.InvokeStore; + } + globalThis.awslambda = { InvokeStore: undefined }; + }, + } + : undefined; +})(exports.InvokeStore || (exports.InvokeStore = {})); + +exports.InvokeStoreBase = InvokeStoreBase; + + +/***/ }), + +/***/ 99527: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var __webpack_unused_export__; +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = __webpack_require__(82172); +const { resolveEventStreamConfig, getEventStreamPlugin } = __webpack_require__(72593); +const { resolveWebSocketConfig, getWebSocketPlugin } = __webpack_require__(69779); +const { memoizeIdentityProvider, isIdentityExpired, doesIdentityRequireRefresh, HttpBearerAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin, createPaginator } = __webpack_require__(89273); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(40417); +const { Command: $Command } = __webpack_require__(40417); +__webpack_unused_export__ = $Command; +__webpack_unused_export__ = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(48132); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(19564); +const { eventStreamSerdeProvider, resolveEventStreamSerdeConfig } = __webpack_require__(49458); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(37015); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(89368); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(31829); +const { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(17727); +const { defaultProvider } = __webpack_require__(83090); +const { eventStreamPayloadHandlerProvider } = __webpack_require__(31683); +const { fromEnvSigningName, nodeProvider } = __webpack_require__(84341); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(26591); +const { streamCollector, NodeHttp2Handler } = __webpack_require__(60517); +const { AwsRestJsonProtocol } = __webpack_require__(37828); +const { Sha256 } = __webpack_require__(7629); + +const defaultBedrockRuntimeHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "bedrock", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#httpBearerAuth", + propertiesExtractor: ({ profile, filepath, configFilepath, ignoreCache, }, context) => ({ + identityProperties: { + profile, + filepath, + configFilepath, + ignoreCache, + }, + }), + }; +} +const defaultBedrockRuntimeHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + options.push(createSmithyApiHttpBearerAuthHttpAuthOption()); + } + } + return options; +}; +const resolveHttpAuthSchemeConfig = (config) => { + const token = memoizeIdentityProvider(config.token, isIdentityExpired, doesIdentityRequireRefresh); + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + token, + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "bedrock", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.1126.0"; +var packageInfo = { + version: version}; + +const k = "ref"; +const a = -1, b = true, c = "isSet", d = "PartitionResult", e = "booleanEquals", f = "getAttr", g = { [k]: "Endpoint" }, h = { [k]: d }, i = {}, j = [{ [k]: "Region" }]; +const _data = { + conditions: [ + [c, [g]], + [c, j], + ["aws.partition", j, d], + [e, [{ [k]: "UseFIPS" }, b]], + [e, [{ [k]: "UseDualStack" }, b]], + [e, [{ fn: f, argv: [h, "supportsDualStack"] }, b]], + [e, [{ fn: f, argv: [h, "supportsFIPS"] }, b]] + ], + results: [ + [a], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [g, i], + ["https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "FIPS is enabled but this partition does not support FIPS"], + ["https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "DualStack is enabled but this partition does not support DualStack"], + ["https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 12, 3, + 1, 4, r + 11, + 2, 5, r + 11, + 3, 8, 6, + 4, 7, r + 10, + 5, r + 8, r + 9, + 4, 10, 9, + 6, r + 6, r + 7, + 5, 11, r + 5, + 6, r + 4, r + 5, + 3, r + 1, 13, + 4, r + 2, r + 3, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +class BedrockRuntimeServiceException extends ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, BedrockRuntimeServiceException.prototype); + } +} + +class AccessDeniedException extends BedrockRuntimeServiceException { + name = "AccessDeniedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + } +} +class InternalServerException extends BedrockRuntimeServiceException { + name = "InternalServerException"; + $fault = "server"; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + } +} +class ThrottlingException extends BedrockRuntimeServiceException { + name = "ThrottlingException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ThrottlingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ThrottlingException.prototype); + } +} +class ValidationException extends BedrockRuntimeServiceException { + name = "ValidationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + } +} +class ConflictException extends BedrockRuntimeServiceException { + name = "ConflictException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ConflictException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ConflictException.prototype); + } +} +class ResourceNotFoundException extends BedrockRuntimeServiceException { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +} +class ServiceQuotaExceededException extends BedrockRuntimeServiceException { + name = "ServiceQuotaExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ServiceQuotaExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); + } +} +class ServiceUnavailableException extends BedrockRuntimeServiceException { + name = "ServiceUnavailableException"; + $fault = "server"; + constructor(opts) { + super({ + name: "ServiceUnavailableException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, ServiceUnavailableException.prototype); + } +} +class ModelErrorException extends BedrockRuntimeServiceException { + name = "ModelErrorException"; + $fault = "client"; + originalStatusCode; + resourceName; + constructor(opts) { + super({ + name: "ModelErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.resourceName = opts.resourceName; + } +} +class ModelNotReadyException extends BedrockRuntimeServiceException { + name = "ModelNotReadyException"; + $fault = "client"; + $retryable = {}; + constructor(opts) { + super({ + name: "ModelNotReadyException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelNotReadyException.prototype); + } +} +class ModelTimeoutException extends BedrockRuntimeServiceException { + name = "ModelTimeoutException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ModelTimeoutException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelTimeoutException.prototype); + } +} +class ModelStreamErrorException extends BedrockRuntimeServiceException { + name = "ModelStreamErrorException"; + $fault = "client"; + originalStatusCode; + originalMessage; + constructor(opts) { + super({ + name: "ModelStreamErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelStreamErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.originalMessage = opts.originalMessage; + } +} + +const _A = "Accept"; +const _AB = "AudioBlock"; +const _ADE = "AccessDeniedException"; +const _AG = "ApplyGuardrail"; +const _AGD = "AppliedGuardrailDetails"; +const _AGR = "ApplyGuardrailRequest"; +const _AGRp = "ApplyGuardrailResponse"; +const _AIM = "AsyncInvokeMessage"; +const _AIODC = "AsyncInvokeOutputDataConfig"; +const _AIS = "AsyncInvokeSummary"; +const _AISODC = "AsyncInvokeS3OutputDataConfig"; +const _AISs = "AsyncInvokeSummaries"; +const _AS = "AudioSource"; +const _ATC = "AnyToolChoice"; +const _ATCu = "AutoToolChoice"; +const _B = "Body"; +const _BIPP = "BidirectionalInputPayloadPart"; +const _BOPP = "BidirectionalOutputPayloadPart"; +const _C = "Citation"; +const _CB = "ContentBlocks"; +const _CBD = "ContentBlockDelta"; +const _CBDE = "ContentBlockDeltaEvent"; +const _CBS = "ContentBlockStart"; +const _CBSE = "ContentBlockStartEvent"; +const _CBSEo = "ContentBlockStopEvent"; +const _CBo = "ContentBlock"; +const _CC = "CitationsConfig"; +const _CCB = "CitationsContentBlock"; +const _CD = "CacheDetail"; +const _CDL = "CacheDetailsList"; +const _CDi = "CitationsDelta"; +const _CE = "ConflictException"; +const _CGC = "CitationGeneratedContent"; +const _CGCL = "CitationGeneratedContentList"; +const _CL = "CitationLocation"; +const _CM = "ConverseMetrics"; +const _CO = "ConverseOutput"; +const _CPB = "CachePointBlock"; +const _CR = "ConverseRequest"; +const _CRo = "ConverseResponse"; +const _CS = "ConverseStream"; +const _CSC = "CitationSourceContent"; +const _CSCD = "CitationSourceContentDelta"; +const _CSCL = "CitationSourceContentList"; +const _CSCLD = "CitationSourceContentListDelta"; +const _CSM = "ConverseStreamMetrics"; +const _CSME = "ConverseStreamMetadataEvent"; +const _CSO = "ConverseStreamOutput"; +const _CSR = "ConverseStreamRequest"; +const _CSRo = "ConverseStreamResponse"; +const _CST = "ConverseStreamTrace"; +const _CT = "ConverseTrace"; +const _CTI = "CountTokensInput"; +const _CTR = "ConverseTokensRequest"; +const _CTRo = "CountTokensRequest"; +const _CTRou = "CountTokensResponse"; +const _CT_ = "Content-Type"; +const _CTo = "CountTokens"; +const _Ci = "Citations"; +const _Co = "Converse"; +const _DB = "DocumentBlock"; +const _DCB = "DocumentContentBlocks"; +const _DCBo = "DocumentContentBlock"; +const _DCL = "DocumentCharLocation"; +const _DCLo = "DocumentChunkLocation"; +const _DPL = "DocumentPageLocation"; +const _DS = "DocumentSource"; +const _EB = "ErrorBlock"; +const _GA = "GuardrailAssessment"; +const _GAI = "GetAsyncInvoke"; +const _GAIR = "GetAsyncInvokeRequest"; +const _GAIRe = "GetAsyncInvokeResponse"; +const _GAL = "GuardrailAssessmentList"; +const _GALM = "GuardrailAssessmentListMap"; +const _GAM = "GuardrailAssessmentMap"; +const _GARDSL = "GuardrailAutomatedReasoningDifferenceScenarioList"; +const _GARF = "GuardrailAutomatedReasoningFinding"; +const _GARFL = "GuardrailAutomatedReasoningFindingList"; +const _GARIF = "GuardrailAutomatedReasoningImpossibleFinding"; +const _GARIFu = "GuardrailAutomatedReasoningInvalidFinding"; +const _GARITR = "GuardrailAutomatedReasoningInputTextReference"; +const _GARITRL = "GuardrailAutomatedReasoningInputTextReferenceList"; +const _GARLW = "GuardrailAutomatedReasoningLogicWarning"; +const _GARNTF = "GuardrailAutomatedReasoningNoTranslationsFinding"; +const _GARPA = "GuardrailAutomatedReasoningPolicyAssessment"; +const _GARR = "GuardrailAutomatedReasoningRule"; +const _GARRL = "GuardrailAutomatedReasoningRuleList"; +const _GARS = "GuardrailAutomatedReasoningScenario"; +const _GARSF = "GuardrailAutomatedReasoningSatisfiableFinding"; +const _GARSL = "GuardrailAutomatedReasoningStatementList"; +const _GARSLC = "GuardrailAutomatedReasoningStatementLogicContent"; +const _GARSNLC = "GuardrailAutomatedReasoningStatementNaturalLanguageContent"; +const _GARSu = "GuardrailAutomatedReasoningStatement"; +const _GART = "GuardrailAutomatedReasoningTranslation"; +const _GARTAF = "GuardrailAutomatedReasoningTranslationAmbiguousFinding"; +const _GARTCF = "GuardrailAutomatedReasoningTooComplexFinding"; +const _GARTL = "GuardrailAutomatedReasoningTranslationList"; +const _GARTO = "GuardrailAutomatedReasoningTranslationOption"; +const _GARTOL = "GuardrailAutomatedReasoningTranslationOptionList"; +const _GARVF = "GuardrailAutomatedReasoningValidFinding"; +const _GC = "GuardrailConfiguration"; +const _GCB = "GuardrailContentBlock"; +const _GCBL = "GuardrailContentBlockList"; +const _GCC = "GuardrailChecksConfig"; +const _GCCB = "GuardrailChecksContentBlock"; +const _GCCBL = "GuardrailChecksContentBlockList"; +const _GCCBu = "GuardrailConverseContentBlock"; +const _GCCFC = "GuardrailChecksContentFilterConfig"; +const _GCCFCC = "GuardrailChecksContentFilterCategoryConfig"; +const _GCCFCCL = "GuardrailChecksContentFilterCategoryConfigList"; +const _GCCFR = "GuardrailChecksContentFilterResult"; +const _GCCFRE = "GuardrailChecksContentFilterResultEntry"; +const _GCCFRL = "GuardrailChecksContentFilterResultList"; +const _GCCFU = "GuardrailChecksContentFilterUsage"; +const _GCF = "GuardrailContentFilter"; +const _GCFL = "GuardrailContentFilterList"; +const _GCGF = "GuardrailContextualGroundingFilter"; +const _GCGFu = "GuardrailContextualGroundingFilters"; +const _GCGPA = "GuardrailContextualGroundingPolicyAssessment"; +const _GCIB = "GuardrailConverseImageBlock"; +const _GCIS = "GuardrailConverseImageSource"; +const _GCM = "GuardrailChecksMessage"; +const _GCML = "GuardrailChecksMessageList"; +const _GCPA = "GuardrailContentPolicyAssessment"; +const _GCPAC = "GuardrailChecksPromptAttackConfig"; +const _GCPACC = "GuardrailChecksPromptAttackCategoryConfig"; +const _GCPACCL = "GuardrailChecksPromptAttackCategoryConfigList"; +const _GCPAR = "GuardrailChecksPromptAttackResult"; +const _GCPARE = "GuardrailChecksPromptAttackResultEntry"; +const _GCPARL = "GuardrailChecksPromptAttackResultList"; +const _GCPAU = "GuardrailChecksPromptAttackUsage"; +const _GCR = "GuardrailChecksResults"; +const _GCSIC = "GuardrailChecksSensitiveInformationConfig"; +const _GCSIEC = "GuardrailChecksSensitiveInformationEntityConfig"; +const _GCSIECL = "GuardrailChecksSensitiveInformationEntityConfigList"; +const _GCSIR = "GuardrailChecksSensitiveInformationResult"; +const _GCSIRE = "GuardrailChecksSensitiveInformationResultEntry"; +const _GCSIRL = "GuardrailChecksSensitiveInformationResultList"; +const _GCSIU = "GuardrailChecksSensitiveInformationUsage"; +const _GCTB = "GuardrailConverseTextBlock"; +const _GCTC = "GuardrailChecksTextContent"; +const _GCUR = "GuardrailChecksUsageResults"; +const _GCW = "GuardrailCustomWord"; +const _GCWL = "GuardrailCustomWordList"; +const _GCu = "GuardrailCoverage"; +const _GIB = "GuardrailImageBlock"; +const _GIC = "GuardrailImageCoverage"; +const _GIM = "GuardrailInvocationMetrics"; +const _GIS = "GuardrailImageSource"; +const _GMW = "GuardrailManagedWord"; +const _GMWL = "GuardrailManagedWordList"; +const _GOC = "GuardrailOutputContent"; +const _GOCL = "GuardrailOutputContentList"; +const _GPEF = "GuardrailPiiEntityFilter"; +const _GPEFL = "GuardrailPiiEntityFilterList"; +const _GRF = "GuardrailRegexFilter"; +const _GRFL = "GuardrailRegexFilterList"; +const _GSC = "GuardrailStreamConfiguration"; +const _GSIPA = "GuardrailSensitiveInformationPolicyAssessment"; +const _GT = "GuardrailTopic"; +const _GTA = "GuardrailTraceAssessment"; +const _GTB = "GuardrailTextBlock"; +const _GTCC = "GuardrailTextCharactersCoverage"; +const _GTL = "GuardrailTopicList"; +const _GTPA = "GuardrailTopicPolicyAssessment"; +const _GU = "GuardrailUsage"; +const _GWPA = "GuardrailWordPolicyAssessment"; +const _IB = "ImageBlock"; +const _IBD = "ImageBlockDelta"; +const _IBS = "ImageBlockStart"; +const _IC = "InferenceConfiguration"; +const _IGC = "InvokeGuardrailChecks"; +const _IGCR = "InvokeGuardrailChecksRequest"; +const _IGCRn = "InvokeGuardrailChecksResponse"; +const _IM = "InvokeModel"; +const _IMR = "InvokeModelRequest"; +const _IMRn = "InvokeModelResponse"; +const _IMTR = "InvokeModelTokensRequest"; +const _IMWBS = "InvokeModelWithBidirectionalStream"; +const _IMWBSI = "InvokeModelWithBidirectionalStreamInput"; +const _IMWBSO = "InvokeModelWithBidirectionalStreamOutput"; +const _IMWBSR = "InvokeModelWithBidirectionalStreamRequest"; +const _IMWBSRn = "InvokeModelWithBidirectionalStreamResponse"; +const _IMWRS = "InvokeModelWithResponseStream"; +const _IMWRSR = "InvokeModelWithResponseStreamRequest"; +const _IMWRSRn = "InvokeModelWithResponseStreamResponse"; +const _IS = "ImageSource"; +const _ISE = "InternalServerException"; +const _JSD = "JsonSchemaDefinition"; +const _LAI = "ListAsyncInvokes"; +const _LAIR = "ListAsyncInvokesRequest"; +const _LAIRi = "ListAsyncInvokesResponse"; +const _M = "Message"; +const _MEE = "ModelErrorException"; +const _MIP = "ModelInputPayload"; +const _MNRE = "ModelNotReadyException"; +const _MSE = "MessageStartEvent"; +const _MSEE = "ModelStreamErrorException"; +const _MSEe = "MessageStopEvent"; +const _MTE = "ModelTimeoutException"; +const _Me = "Messages"; +const _OC = "OutputConfig"; +const _OF = "OutputFormat"; +const _OFS = "OutputFormatStructure"; +const _PB = "PartBody"; +const _PC = "PerformanceConfiguration"; +const _PP = "PayloadPart"; +const _PRT = "PromptRouterTrace"; +const _PVM = "PromptVariableMap"; +const _PVV = "PromptVariableValues"; +const _RCB = "ReasoningContentBlock"; +const _RCBD = "ReasoningContentBlockDelta"; +const _RM = "RequestMetadata"; +const _RMJ = "RequestMetadataJson"; +const _RNFE = "ResourceNotFoundException"; +const _RS = "ResponseStream"; +const _RTB = "ReasoningTextBlock"; +const _SAI = "StartAsyncInvoke"; +const _SAIR = "StartAsyncInvokeRequest"; +const _SAIRt = "StartAsyncInvokeResponse"; +const _SCB = "SystemContentBlocks"; +const _SCBy = "SystemContentBlock"; +const _SL = "S3Location"; +const _SQEE = "ServiceQuotaExceededException"; +const _SRB = "SearchResultBlock"; +const _SRCB = "SearchResultContentBlock"; +const _SRCBe = "SearchResultContentBlocks"; +const _SRL = "SearchResultLocation"; +const _ST = "ServiceTier"; +const _STC = "SpecificToolChoice"; +const _STy = "SystemTool"; +const _SUE = "ServiceUnavailableException"; +const _T = "Tag"; +const _TAB = "ToolAdditionBlock"; +const _TC = "ToolConfiguration"; +const _TCo = "ToolChoice"; +const _TE = "ThrottlingException"; +const _TIS = "ToolInputSchema"; +const _TL = "TagList"; +const _TR = "ToolReference"; +const _TRB = "ToolRemovalBlock"; +const _TRBD = "ToolResultBlocksDelta"; +const _TRBDo = "ToolResultBlockDelta"; +const _TRBS = "ToolResultBlockStart"; +const _TRBo = "ToolResultBlock"; +const _TRCB = "ToolResultContentBlocks"; +const _TRCBo = "ToolResultContentBlock"; +const _TS = "ToolSpecification"; +const _TU = "TokenUsage"; +const _TUB = "ToolUseBlock"; +const _TUBD = "ToolUseBlockDelta"; +const _TUBS = "ToolUseBlockStart"; +const _To = "Tools"; +const _Too = "Tool"; +const _VB = "VideoBlock"; +const _VE = "ValidationException"; +const _VS = "VideoSource"; +const _WL = "WebLocation"; +const _XABA = "X-Amzn-Bedrock-Accept"; +const _XABCT = "X-Amzn-Bedrock-Content-Type"; +const _XABG = "X-Amzn-Bedrock-GuardrailIdentifier"; +const _XABG_ = "X-Amzn-Bedrock-GuardrailVersion"; +const _XABPL = "X-Amzn-Bedrock-PerformanceConfig-Latency"; +const _XABRM = "X-Amzn-Bedrock-Request-Metadata"; +const _XABST = "X-Amzn-Bedrock-Service-Tier"; +const _XABT = "X-Amzn-Bedrock-Trace"; +const _a = "action"; +const _aGD = "appliedGuardrailDetails"; +const _aIS = "asyncInvokeSummaries"; +const _aMRF = "additionalModelRequestFields"; +const _aMRFP = "additionalModelResponseFieldPaths"; +const _aMRFd = "additionalModelResponseFields"; +const _aR = "actionReason"; +const _aRP = "automatedReasoningPolicy"; +const _aRPU = "automatedReasoningPolicyUnits"; +const _aRPu = "automatedReasoningPolicies"; +const _ac = "accept"; +const _an = "any"; +const _as = "assessments"; +const _au = "audio"; +const _aut = "auto"; +const _b = "bytes"; +const _bO = "bucketOwner"; +const _bOe = "beginOffset"; +const _bo = "body"; +const _c = "client"; +const _cBD = "contentBlockDelta"; +const _cBI = "contentBlockIndex"; +const _cBS = "contentBlockStart"; +const _cBSo = "contentBlockStop"; +const _cC = "citationsContent"; +const _cD = "cacheDetails"; +const _cF = "contentFilter"; +const _cFS = "claimsFalseScenario"; +const _cGP = "contextualGroundingPolicy"; +const _cGPU = "contextualGroundingPolicyUnits"; +const _cI = "contentIndex"; +const _cP = "contentPolicy"; +const _cPIU = "contentPolicyImageUnits"; +const _cPU = "contentPolicyUnits"; +const _cPa = "cachePoint"; +const _cR = "contradictingRules"; +const _cRIT = "cacheReadInputTokens"; +const _cRT = "clientRequestToken"; +const _cS = "confidenceScore"; +const _cT = "contentType"; +const _cTS = "claimsTrueScenario"; +const _cW = "customWords"; +const _cWIT = "cacheWriteInputTokens"; +const _ca = "category"; +const _cat = "categories"; +const _ch = "checks"; +const _chu = "chunk"; +const _ci = "citations"; +const _cit = "citation"; +const _cl = "claims"; +const _co = "content"; +const _con = "context"; +const _conf = "confidence"; +const _conv = "converse"; +const _d = "delta"; +const _dC = "documentChar"; +const _dCo = "documentChunk"; +const _dI = "documentIndex"; +const _dP = "documentPage"; +const _dS = "differenceScenarios"; +const _de = "detected"; +const _des = "description"; +const _do = "domain"; +const _doc = "document"; +const _e = "error"; +const _eO = "endOffset"; +const _eT = "endTime"; +const _ef = "effort"; +const _en = "enabled"; +const _end = "end"; +const _ent = "entities"; +const _f = "format"; +const _fM = "failureMessage"; +const _fS = "filterStrength"; +const _fi = "findings"; +const _fil = "filters"; +const _g = "guardrail"; +const _gA = "guardrailArn"; +const _gC = "guardrailCoverage"; +const _gCu = "guardrailConfig"; +const _gCua = "guardContent"; +const _gI = "guardrailId"; +const _gIu = "guardrailIdentifier"; +const _gO = "guardrailOrigin"; +const _gOu = "guardrailOwnership"; +const _gPL = "guardrailProcessingLatency"; +const _gV = "guardrailVersion"; +const _gu = "guarded"; +const _h = "http"; +const _hE = "httpError"; +const _hH = "httpHeader"; +const _hQ = "httpQuery"; +const _i = "input"; +const _iA = "invocationArn"; +const _iAn = "inputAssessment"; +const _iC = "inferenceConfig"; +const _iM = "invocationMetrics"; +const _iMI = "invokedModelId"; +const _iMn = "invokeModel"; +const _iS = "inputSchema"; +const _iSE = "internalServerException"; +const _iT = "inputTokens"; +const _id = "identifier"; +const _im = "images"; +const _ima = "image"; +const _imp = "impossible"; +const _in = "invalid"; +const _j = "json"; +const _jS = "jsonSchema"; +const _k = "key"; +const _kKI = "kmsKeyId"; +const _l = "location"; +const _lM = "latencyMs"; +const _lMT = "lastModifiedTime"; +const _lW = "logicWarning"; +const _la = "latency"; +const _lo = "logic"; +const _m = "message"; +const _mA = "modelArn"; +const _mI = "modelId"; +const _mIe = "messageIndex"; +const _mIo = "modelInput"; +const _mO = "modelOutput"; +const _mR = "maxResults"; +const _mS = "messageStart"; +const _mSEE = "modelStreamErrorException"; +const _mSe = "messageStop"; +const _mT = "maxTokens"; +const _mTE = "modelTimeoutException"; +const _mWL = "managedWordLists"; +const _ma = "match"; +const _me = "messages"; +const _met = "metrics"; +const _meta = "metadata"; +const _n = "name"; +const _nL = "naturalLanguage"; +const _nT = "nextToken"; +const _nTo = "noTranslations"; +const _o = "outputs"; +const _oA = "outputAssessments"; +const _oC = "outputConfig"; +const _oDC = "outputDataConfig"; +const _oM = "originalMessage"; +const _oS = "outputScope"; +const _oSC = "originalStatusCode"; +const _oT = "outputTokens"; +const _op = "options"; +const _ou = "output"; +const _p = "premises"; +const _pA = "promptAttack"; +const _pC = "performanceConfig"; +const _pCL = "performanceConfigLatency"; +const _pE = "piiEntities"; +const _pR = "promptRouter"; +const _pV = "promptVariables"; +const _pVA = "policyVersionArn"; +const _q = "qualifiers"; +const _r = "results"; +const _rC = "reasoningContent"; +const _rCe = "redactedContent"; +const _rM = "requestMetadata"; +const _rN = "resourceName"; +const _rT = "reasoningText"; +const _re = "regex"; +const _reg = "regexes"; +const _ro = "role"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime"; +const _sB = "sortBy"; +const _sC = "sourceContent"; +const _sE = "statusEquals"; +const _sI = "sensitiveInformation"; +const _sIP = "sensitiveInformationPolicy"; +const _sIPFU = "sensitiveInformationPolicyFreeUnits"; +const _sIPU = "sensitiveInformationPolicyUnits"; +const _sL = "s3Location"; +const _sN = "serverName"; +const _sO = "sortOrder"; +const _sODC = "s3OutputDataConfig"; +const _sPM = "streamProcessingMode"; +const _sR = "stopReason"; +const _sRI = "searchResultIndex"; +const _sRL = "searchResultLocation"; +const _sRe = "searchResult"; +const _sRu = "supportingRules"; +const _sS = "severityScore"; +const _sSt = "stopSequences"; +const _sT = "submitTime"; +const _sTA = "submitTimeAfter"; +const _sTB = "submitTimeBefore"; +const _sTe = "serviceTier"; +const _sTy = "systemTool"; +const _sU = "s3Uri"; +const _sUE = "serviceUnavailableException"; +const _sa = "satisfiable"; +const _sc = "score"; +const _sch = "schema"; +const _se = "server"; +const _si = "signature"; +const _so = "source"; +const _st = "status"; +const _sta = "start"; +const _stat = "statements"; +const _str = "stream"; +const _stre = "streaming"; +const _stri = "strict"; +const _stru = "structure"; +const _sy = "system"; +const _t = "ttl"; +const _tA = "toolAddition"; +const _tAr = "translationAmbiguous"; +const _tC = "toolConfig"; +const _tCe = "textCharacters"; +const _tCo = "toolChoice"; +const _tCoo = "tooComplex"; +const _tE = "throttlingException"; +const _tF = "textFormat"; +const _tP = "topicPolicy"; +const _tPU = "topicPolicyUnits"; +const _tPo = "topP"; +const _tR = "toolResult"; +const _tRo = "toolRemoval"; +const _tS = "toolSpec"; +const _tT = "totalTokens"; +const _tU = "textUnits"; +const _tUI = "toolUseId"; +const _tUo = "toolUse"; +const _ta = "tags"; +const _te = "text"; +const _tem = "temperature"; +const _th = "threshold"; +const _ti = "title"; +const _to = "total"; +const _too = "tool"; +const _tool = "tools"; +const _top = "topics"; +const _tr = "trace"; +const _tra = "translation"; +const _tran = "translations"; +const _tru = "truncated"; +const _ty = "type"; +const _u = "usage"; +const _uC = "untranslatedClaims"; +const _uP = "untranslatedPremises"; +const _ur = "uri"; +const _url = "url"; +const _v = "value"; +const _vE = "validationException"; +const _va = "valid"; +const _vi = "video"; +const _w = "web"; +const _wP = "wordPolicy"; +const _wPU = "wordPolicyUnits"; +const n0 = "com.amazonaws.bedrockruntime"; +const _s_registry = TypeRegistry.for(_s); +var BedrockRuntimeServiceException$ = [-3, _s, "BedrockRuntimeServiceException", 0, [], []]; +_s_registry.registerError(BedrockRuntimeServiceException$, BedrockRuntimeServiceException); +const n0_registry = TypeRegistry.for(n0); +var AccessDeniedException$ = [-3, n0, _ADE, + { [_e]: _c, [_hE]: 403 }, + [_m], + [0] +]; +n0_registry.registerError(AccessDeniedException$, AccessDeniedException); +var ConflictException$ = [-3, n0, _CE, + { [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(ConflictException$, ConflictException); +var InternalServerException$ = [-3, n0, _ISE, + { [_e]: _se, [_hE]: 500 }, + [_m], + [0] +]; +n0_registry.registerError(InternalServerException$, InternalServerException); +var ModelErrorException$ = [-3, n0, _MEE, + { [_e]: _c, [_hE]: 424 }, + [_m, _oSC, _rN], + [0, 1, 0] +]; +n0_registry.registerError(ModelErrorException$, ModelErrorException); +var ModelNotReadyException$ = [-3, n0, _MNRE, + { [_e]: _c, [_hE]: 429 }, + [_m], + [0] +]; +n0_registry.registerError(ModelNotReadyException$, ModelNotReadyException); +var ModelStreamErrorException$ = [-3, n0, _MSEE, + { [_e]: _c, [_hE]: 424 }, + [_m, _oSC, _oM], + [0, 1, 0] +]; +n0_registry.registerError(ModelStreamErrorException$, ModelStreamErrorException); +var ModelTimeoutException$ = [-3, n0, _MTE, + { [_e]: _c, [_hE]: 408 }, + [_m], + [0] +]; +n0_registry.registerError(ModelTimeoutException$, ModelTimeoutException); +var ResourceNotFoundException$ = [-3, n0, _RNFE, + { [_e]: _c, [_hE]: 404 }, + [_m], + [0] +]; +n0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException); +var ServiceQuotaExceededException$ = [-3, n0, _SQEE, + { [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(ServiceQuotaExceededException$, ServiceQuotaExceededException); +var ServiceUnavailableException$ = [-3, n0, _SUE, + { [_e]: _se, [_hE]: 503 }, + [_m], + [0] +]; +n0_registry.registerError(ServiceUnavailableException$, ServiceUnavailableException); +var ThrottlingException$ = [-3, n0, _TE, + { [_e]: _c, [_hE]: 429 }, + [_m], + [0] +]; +n0_registry.registerError(ThrottlingException$, ThrottlingException); +var ValidationException$ = [-3, n0, _VE, + { [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(ValidationException$, ValidationException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var AsyncInvokeMessage = [0, n0, _AIM, 8, 0]; +var Body = [0, n0, _B, 8, 21]; +var GuardrailAutomatedReasoningStatementLogicContent = [0, n0, _GARSLC, 8, 0]; +var GuardrailAutomatedReasoningStatementNaturalLanguageContent = [0, n0, _GARSNLC, 8, 0]; +var GuardrailChecksTextContent = [0, n0, _GCTC, 8, 0]; +var ModelInputPayload = [0, n0, _MIP, 8, 15]; +var PartBody = [0, n0, _PB, 8, 21]; +var RequestMetadataJson = [0, n0, _RMJ, 8, 0]; +var AnyToolChoice$ = [3, n0, _ATC, + 0, + [], + [] +]; +var AppliedGuardrailDetails$ = [3, n0, _AGD, + 0, + [_gI, _gV, _gA, _gO, _gOu], + [0, 0, 0, 64 | 0, 0] +]; +var ApplyGuardrailRequest$ = [3, n0, _AGR, + 0, + [_gIu, _gV, _so, _co, _oS], + [[0, 1], [0, 1], 0, [() => GuardrailContentBlockList, 0], 0], 4 +]; +var ApplyGuardrailResponse$ = [3, n0, _AGRp, + 0, + [_u, _a, _o, _as, _aR, _gC], + [() => GuardrailUsage$, 0, () => GuardrailOutputContentList, [() => GuardrailAssessmentList, 0], 0, () => GuardrailCoverage$], 4 +]; +var AsyncInvokeS3OutputDataConfig$ = [3, n0, _AISODC, + 0, + [_sU, _kKI, _bO], + [0, 0, 0], 1 +]; +var AsyncInvokeSummary$ = [3, n0, _AIS, + 0, + [_iA, _mA, _sT, _oDC, _cRT, _st, _fM, _lMT, _eT], + [0, 0, 5, () => AsyncInvokeOutputDataConfig$, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5], 4 +]; +var AudioBlock$ = [3, n0, _AB, + 0, + [_f, _so, _e], + [0, [() => AudioSource$, 0], [() => ErrorBlock$, 0]], 2 +]; +var AutoToolChoice$ = [3, n0, _ATCu, + 0, + [], + [] +]; +var BidirectionalInputPayloadPart$ = [3, n0, _BIPP, + 8, + [_b], + [[() => PartBody, 0]] +]; +var BidirectionalOutputPayloadPart$ = [3, n0, _BOPP, + 8, + [_b], + [[() => PartBody, 0]] +]; +var CacheDetail$ = [3, n0, _CD, + 0, + [_t, _iT], + [0, 1], 2 +]; +var CachePointBlock$ = [3, n0, _CPB, + 0, + [_ty, _t], + [0, 0], 1 +]; +var Citation$ = [3, n0, _C, + 0, + [_ti, _so, _sC, _l], + [0, 0, () => CitationSourceContentList, () => CitationLocation$] +]; +var CitationsConfig$ = [3, n0, _CC, + 0, + [_en], + [2], 1 +]; +var CitationsContentBlock$ = [3, n0, _CCB, + 0, + [_co, _ci], + [() => CitationGeneratedContentList, () => Citations] +]; +var CitationsDelta$ = [3, n0, _CDi, + 0, + [_ti, _so, _sC, _l], + [0, 0, () => CitationSourceContentListDelta, () => CitationLocation$] +]; +var CitationSourceContentDelta$ = [3, n0, _CSCD, + 0, + [_te], + [0] +]; +var ContentBlockDeltaEvent$ = [3, n0, _CBDE, + 0, + [_d, _cBI], + [[() => ContentBlockDelta$, 0], 1], 2 +]; +var ContentBlockStartEvent$ = [3, n0, _CBSE, + 0, + [_sta, _cBI], + [() => ContentBlockStart$, 1], 2 +]; +var ContentBlockStopEvent$ = [3, n0, _CBSEo, + 0, + [_cBI], + [1], 1 +]; +var ConverseMetrics$ = [3, n0, _CM, + 0, + [_lM], + [1], 1 +]; +var ConverseRequest$ = [3, n0, _CR, + 0, + [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe, _oC], + [[0, 1], [() => Messages, 0], [() => SystemContentBlocks, 0], () => InferenceConfiguration$, () => ToolConfiguration$, () => GuardrailConfiguration$, 15, [() => PromptVariableMap, 0], 64 | 0, [() => RequestMetadata, 0], () => PerformanceConfiguration$, () => ServiceTier$, [() => OutputConfig$, 0]], 1 +]; +var ConverseResponse$ = [3, n0, _CRo, + 0, + [_ou, _sR, _u, _met, _aMRFd, _tr, _pC, _sTe], + [[() => ConverseOutput$, 0], 0, () => TokenUsage$, () => ConverseMetrics$, 15, [() => ConverseTrace$, 0], () => PerformanceConfiguration$, () => ServiceTier$], 4 +]; +var ConverseStreamMetadataEvent$ = [3, n0, _CSME, + 0, + [_u, _met, _tr, _pC, _sTe], + [() => TokenUsage$, () => ConverseStreamMetrics$, [() => ConverseStreamTrace$, 0], () => PerformanceConfiguration$, () => ServiceTier$], 2 +]; +var ConverseStreamMetrics$ = [3, n0, _CSM, + 0, + [_lM], + [1], 1 +]; +var ConverseStreamRequest$ = [3, n0, _CSR, + 0, + [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe, _oC], + [[0, 1], [() => Messages, 0], [() => SystemContentBlocks, 0], () => InferenceConfiguration$, () => ToolConfiguration$, () => GuardrailStreamConfiguration$, 15, [() => PromptVariableMap, 0], 64 | 0, [() => RequestMetadata, 0], () => PerformanceConfiguration$, () => ServiceTier$, [() => OutputConfig$, 0]], 1 +]; +var ConverseStreamResponse$ = [3, n0, _CSRo, + 0, + [_str], + [[() => ConverseStreamOutput$, 16]] +]; +var ConverseStreamTrace$ = [3, n0, _CST, + 0, + [_g, _pR], + [[() => GuardrailTraceAssessment$, 0], () => PromptRouterTrace$] +]; +var ConverseTokensRequest$ = [3, n0, _CTR, + 0, + [_me, _sy, _tC, _aMRF], + [[() => Messages, 0], [() => SystemContentBlocks, 0], () => ToolConfiguration$, 15] +]; +var ConverseTrace$ = [3, n0, _CT, + 0, + [_g, _pR], + [[() => GuardrailTraceAssessment$, 0], () => PromptRouterTrace$] +]; +var CountTokensRequest$ = [3, n0, _CTRo, + 0, + [_mI, _i], + [[0, 1], [() => CountTokensInput$, 0]], 2 +]; +var CountTokensResponse$ = [3, n0, _CTRou, + 0, + [_iT], + [1], 1 +]; +var DocumentBlock$ = [3, n0, _DB, + 0, + [_n, _so, _f, _con, _ci], + [0, () => DocumentSource$, 0, 0, () => CitationsConfig$], 2 +]; +var DocumentCharLocation$ = [3, n0, _DCL, + 0, + [_dI, _sta, _end], + [1, 1, 1] +]; +var DocumentChunkLocation$ = [3, n0, _DCLo, + 0, + [_dI, _sta, _end], + [1, 1, 1] +]; +var DocumentPageLocation$ = [3, n0, _DPL, + 0, + [_dI, _sta, _end], + [1, 1, 1] +]; +var ErrorBlock$ = [3, n0, _EB, + 8, + [_m], + [0] +]; +var GetAsyncInvokeRequest$ = [3, n0, _GAIR, + 0, + [_iA], + [[0, 1]], 1 +]; +var GetAsyncInvokeResponse$ = [3, n0, _GAIRe, + 0, + [_iA, _mA, _st, _sT, _oDC, _cRT, _fM, _lMT, _eT], + [0, 0, 0, 5, () => AsyncInvokeOutputDataConfig$, 0, [() => AsyncInvokeMessage, 0], 5, 5], 5 +]; +var GuardrailAssessment$ = [3, n0, _GA, + 0, + [_tP, _cP, _wP, _sIP, _cGP, _aRP, _iM, _aGD], + [() => GuardrailTopicPolicyAssessment$, () => GuardrailContentPolicyAssessment$, () => GuardrailWordPolicyAssessment$, () => GuardrailSensitiveInformationPolicyAssessment$, () => GuardrailContextualGroundingPolicyAssessment$, [() => GuardrailAutomatedReasoningPolicyAssessment$, 0], () => GuardrailInvocationMetrics$, () => AppliedGuardrailDetails$] +]; +var GuardrailAutomatedReasoningImpossibleFinding$ = [3, n0, _GARIF, + 0, + [_tra, _cR, _lW], + [[() => GuardrailAutomatedReasoningTranslation$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]] +]; +var GuardrailAutomatedReasoningInputTextReference$ = [3, n0, _GARITR, + 0, + [_te], + [[() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]] +]; +var GuardrailAutomatedReasoningInvalidFinding$ = [3, n0, _GARIFu, + 0, + [_tra, _cR, _lW], + [[() => GuardrailAutomatedReasoningTranslation$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]] +]; +var GuardrailAutomatedReasoningLogicWarning$ = [3, n0, _GARLW, + 0, + [_ty, _p, _cl], + [0, [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0]] +]; +var GuardrailAutomatedReasoningNoTranslationsFinding$ = [3, n0, _GARNTF, + 0, + [], + [] +]; +var GuardrailAutomatedReasoningPolicyAssessment$ = [3, n0, _GARPA, + 0, + [_fi], + [[() => GuardrailAutomatedReasoningFindingList, 0]] +]; +var GuardrailAutomatedReasoningRule$ = [3, n0, _GARR, + 0, + [_id, _pVA], + [0, 0] +]; +var GuardrailAutomatedReasoningSatisfiableFinding$ = [3, n0, _GARSF, + 0, + [_tra, _cTS, _cFS, _lW], + [[() => GuardrailAutomatedReasoningTranslation$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], [() => GuardrailAutomatedReasoningLogicWarning$, 0]] +]; +var GuardrailAutomatedReasoningScenario$ = [3, n0, _GARS, + 0, + [_stat], + [[() => GuardrailAutomatedReasoningStatementList, 0]] +]; +var GuardrailAutomatedReasoningStatement$ = [3, n0, _GARSu, + 0, + [_lo, _nL], + [[() => GuardrailAutomatedReasoningStatementLogicContent, 0], [() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]] +]; +var GuardrailAutomatedReasoningTooComplexFinding$ = [3, n0, _GARTCF, + 0, + [], + [] +]; +var GuardrailAutomatedReasoningTranslation$ = [3, n0, _GART, + 0, + [_p, _cl, _uP, _uC, _conf], + [[() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], 1] +]; +var GuardrailAutomatedReasoningTranslationAmbiguousFinding$ = [3, n0, _GARTAF, + 0, + [_op, _dS], + [[() => GuardrailAutomatedReasoningTranslationOptionList, 0], [() => GuardrailAutomatedReasoningDifferenceScenarioList, 0]] +]; +var GuardrailAutomatedReasoningTranslationOption$ = [3, n0, _GARTO, + 0, + [_tran], + [[() => GuardrailAutomatedReasoningTranslationList, 0]] +]; +var GuardrailAutomatedReasoningValidFinding$ = [3, n0, _GARVF, + 0, + [_tra, _cTS, _sRu, _lW], + [[() => GuardrailAutomatedReasoningTranslation$, 0], [() => GuardrailAutomatedReasoningScenario$, 0], () => GuardrailAutomatedReasoningRuleList, [() => GuardrailAutomatedReasoningLogicWarning$, 0]] +]; +var GuardrailChecksConfig$ = [3, n0, _GCC, + 0, + [_cF, _pA, _sI], + [() => GuardrailChecksContentFilterConfig$, () => GuardrailChecksPromptAttackConfig$, () => GuardrailChecksSensitiveInformationConfig$] +]; +var GuardrailChecksContentFilterCategoryConfig$ = [3, n0, _GCCFCC, + 0, + [_ca], + [0], 1 +]; +var GuardrailChecksContentFilterConfig$ = [3, n0, _GCCFC, + 0, + [_cat], + [() => GuardrailChecksContentFilterCategoryConfigList], 1 +]; +var GuardrailChecksContentFilterResult$ = [3, n0, _GCCFR, + 0, + [_r], + [() => GuardrailChecksContentFilterResultList], 1 +]; +var GuardrailChecksContentFilterResultEntry$ = [3, n0, _GCCFRE, + 0, + [_ca, _sS], + [0, 1], 2 +]; +var GuardrailChecksContentFilterUsage$ = [3, n0, _GCCFU, + 0, + [_tU], + [1], 1 +]; +var GuardrailChecksMessage$ = [3, n0, _GCM, + 0, + [_ro, _co], + [0, [() => GuardrailChecksContentBlockList, 0]], 2 +]; +var GuardrailChecksPromptAttackCategoryConfig$ = [3, n0, _GCPACC, + 0, + [_ca], + [0], 1 +]; +var GuardrailChecksPromptAttackConfig$ = [3, n0, _GCPAC, + 0, + [_cat], + [() => GuardrailChecksPromptAttackCategoryConfigList], 1 +]; +var GuardrailChecksPromptAttackResult$ = [3, n0, _GCPAR, + 0, + [_r], + [() => GuardrailChecksPromptAttackResultList], 1 +]; +var GuardrailChecksPromptAttackResultEntry$ = [3, n0, _GCPARE, + 0, + [_ca, _sS], + [0, 1], 2 +]; +var GuardrailChecksPromptAttackUsage$ = [3, n0, _GCPAU, + 0, + [_tU], + [1], 1 +]; +var GuardrailChecksResults$ = [3, n0, _GCR, + 0, + [_cF, _pA, _sI], + [() => GuardrailChecksContentFilterResult$, () => GuardrailChecksPromptAttackResult$, () => GuardrailChecksSensitiveInformationResult$] +]; +var GuardrailChecksSensitiveInformationConfig$ = [3, n0, _GCSIC, + 0, + [_ent], + [() => GuardrailChecksSensitiveInformationEntityConfigList], 1 +]; +var GuardrailChecksSensitiveInformationEntityConfig$ = [3, n0, _GCSIEC, + 0, + [_ty], + [0], 1 +]; +var GuardrailChecksSensitiveInformationResult$ = [3, n0, _GCSIR, + 0, + [_r, _tru], + [() => GuardrailChecksSensitiveInformationResultList, 2], 1 +]; +var GuardrailChecksSensitiveInformationResultEntry$ = [3, n0, _GCSIRE, + 0, + [_ty, _cS, _bOe, _eO, _mIe, _cI], + [0, 1, 1, 1, 1, 1], 6 +]; +var GuardrailChecksSensitiveInformationUsage$ = [3, n0, _GCSIU, + 0, + [_tU], + [1], 1 +]; +var GuardrailChecksUsageResults$ = [3, n0, _GCUR, + 0, + [_cF, _pA, _sI], + [() => GuardrailChecksContentFilterUsage$, () => GuardrailChecksPromptAttackUsage$, () => GuardrailChecksSensitiveInformationUsage$] +]; +var GuardrailConfiguration$ = [3, n0, _GC, + 0, + [_gIu, _gV, _tr], + [0, 0, 0] +]; +var GuardrailContentFilter$ = [3, n0, _GCF, + 0, + [_ty, _conf, _a, _fS, _de], + [0, 0, 0, 0, 2], 3 +]; +var GuardrailContentPolicyAssessment$ = [3, n0, _GCPA, + 0, + [_fil], + [() => GuardrailContentFilterList], 1 +]; +var GuardrailContextualGroundingFilter$ = [3, n0, _GCGF, + 0, + [_ty, _th, _sc, _a, _de], + [0, 1, 1, 0, 2], 4 +]; +var GuardrailContextualGroundingPolicyAssessment$ = [3, n0, _GCGPA, + 0, + [_fil], + [() => GuardrailContextualGroundingFilters] +]; +var GuardrailConverseImageBlock$ = [3, n0, _GCIB, + 8, + [_f, _so], + [0, [() => GuardrailConverseImageSource$, 0]], 2 +]; +var GuardrailConverseTextBlock$ = [3, n0, _GCTB, + 0, + [_te, _q], + [0, 64 | 0], 1 +]; +var GuardrailCoverage$ = [3, n0, _GCu, + 0, + [_tCe, _im], + [() => GuardrailTextCharactersCoverage$, () => GuardrailImageCoverage$] +]; +var GuardrailCustomWord$ = [3, n0, _GCW, + 0, + [_ma, _a, _de], + [0, 0, 2], 2 +]; +var GuardrailImageBlock$ = [3, n0, _GIB, + 8, + [_f, _so], + [0, [() => GuardrailImageSource$, 0]], 2 +]; +var GuardrailImageCoverage$ = [3, n0, _GIC, + 0, + [_gu, _to], + [1, 1] +]; +var GuardrailInvocationMetrics$ = [3, n0, _GIM, + 0, + [_gPL, _u, _gC], + [1, () => GuardrailUsage$, () => GuardrailCoverage$] +]; +var GuardrailManagedWord$ = [3, n0, _GMW, + 0, + [_ma, _ty, _a, _de], + [0, 0, 0, 2], 3 +]; +var GuardrailOutputContent$ = [3, n0, _GOC, + 0, + [_te], + [0] +]; +var GuardrailPiiEntityFilter$ = [3, n0, _GPEF, + 0, + [_ma, _ty, _a, _de], + [0, 0, 0, 2], 3 +]; +var GuardrailRegexFilter$ = [3, n0, _GRF, + 0, + [_a, _n, _ma, _re, _de], + [0, 0, 0, 0, 2], 1 +]; +var GuardrailSensitiveInformationPolicyAssessment$ = [3, n0, _GSIPA, + 0, + [_pE, _reg], + [() => GuardrailPiiEntityFilterList, () => GuardrailRegexFilterList], 2 +]; +var GuardrailStreamConfiguration$ = [3, n0, _GSC, + 0, + [_gIu, _gV, _tr, _sPM], + [0, 0, 0, 0] +]; +var GuardrailTextBlock$ = [3, n0, _GTB, + 0, + [_te, _q], + [0, 64 | 0], 1 +]; +var GuardrailTextCharactersCoverage$ = [3, n0, _GTCC, + 0, + [_gu, _to], + [1, 1] +]; +var GuardrailTopic$ = [3, n0, _GT, + 0, + [_n, _ty, _a, _de], + [0, 0, 0, 2], 3 +]; +var GuardrailTopicPolicyAssessment$ = [3, n0, _GTPA, + 0, + [_top], + [() => GuardrailTopicList], 1 +]; +var GuardrailTraceAssessment$ = [3, n0, _GTA, + 0, + [_mO, _iAn, _oA, _aR], + [64 | 0, [() => GuardrailAssessmentMap, 0], [() => GuardrailAssessmentListMap, 0], 0] +]; +var GuardrailUsage$ = [3, n0, _GU, + 0, + [_tPU, _cPU, _wPU, _sIPU, _sIPFU, _cGPU, _cPIU, _aRPU, _aRPu], + [1, 1, 1, 1, 1, 1, 1, 1, 1], 6 +]; +var GuardrailWordPolicyAssessment$ = [3, n0, _GWPA, + 0, + [_cW, _mWL], + [() => GuardrailCustomWordList, () => GuardrailManagedWordList], 2 +]; +var ImageBlock$ = [3, n0, _IB, + 0, + [_f, _so, _e], + [0, [() => ImageSource$, 0], [() => ErrorBlock$, 0]], 2 +]; +var ImageBlockDelta$ = [3, n0, _IBD, + 0, + [_so, _e], + [[() => ImageSource$, 0], [() => ErrorBlock$, 0]] +]; +var ImageBlockStart$ = [3, n0, _IBS, + 0, + [_f], + [0], 1 +]; +var InferenceConfiguration$ = [3, n0, _IC, + 0, + [_mT, _tem, _tPo, _sSt], + [1, 1, 1, 64 | 0] +]; +var InvokeGuardrailChecksRequest$ = [3, n0, _IGCR, + 0, + [_me, _ch], + [[() => GuardrailChecksMessageList, 0], () => GuardrailChecksConfig$], 2 +]; +var InvokeGuardrailChecksResponse$ = [3, n0, _IGCRn, + 0, + [_r, _u], + [() => GuardrailChecksResults$, () => GuardrailChecksUsageResults$], 2 +]; +var InvokeModelRequest$ = [3, n0, _IMR, + 0, + [_mI, _bo, _cT, _ac, _tr, _gIu, _gV, _pCL, _sTe, _rM], + [[0, 1], [() => Body, 16], [0, { [_hH]: _CT_ }], [0, { [_hH]: _A }], [0, { [_hH]: _XABT }], [0, { [_hH]: _XABG }], [0, { [_hH]: _XABG_ }], [0, { [_hH]: _XABPL }], [0, { [_hH]: _XABST }], [() => RequestMetadataJson, { [_hH]: _XABRM }]], 1 +]; +var InvokeModelResponse$ = [3, n0, _IMRn, + 0, + [_bo, _cT, _pCL, _sTe], + [[() => Body, 16], [0, { [_hH]: _CT_ }], [0, { [_hH]: _XABPL }], [0, { [_hH]: _XABST }]], 2 +]; +var InvokeModelTokensRequest$ = [3, n0, _IMTR, + 0, + [_bo], + [[() => Body, 0]], 1 +]; +var InvokeModelWithBidirectionalStreamRequest$ = [3, n0, _IMWBSR, + 0, + [_mI, _bo], + [[0, 1], [() => InvokeModelWithBidirectionalStreamInput$, 16]], 2 +]; +var InvokeModelWithBidirectionalStreamResponse$ = [3, n0, _IMWBSRn, + 0, + [_bo], + [[() => InvokeModelWithBidirectionalStreamOutput$, 16]], 1 +]; +var InvokeModelWithResponseStreamRequest$ = [3, n0, _IMWRSR, + 0, + [_mI, _bo, _cT, _ac, _tr, _gIu, _gV, _pCL, _sTe, _rM], + [[0, 1], [() => Body, 16], [0, { [_hH]: _CT_ }], [0, { [_hH]: _XABA }], [0, { [_hH]: _XABT }], [0, { [_hH]: _XABG }], [0, { [_hH]: _XABG_ }], [0, { [_hH]: _XABPL }], [0, { [_hH]: _XABST }], [() => RequestMetadataJson, { [_hH]: _XABRM }]], 1 +]; +var InvokeModelWithResponseStreamResponse$ = [3, n0, _IMWRSRn, + 0, + [_bo, _cT, _pCL, _sTe], + [[() => ResponseStream$, 16], [0, { [_hH]: _XABCT }], [0, { [_hH]: _XABPL }], [0, { [_hH]: _XABST }]], 2 +]; +var JsonSchemaDefinition$ = [3, n0, _JSD, + 0, + [_sch, _n, _des], + [0, 0, 0], 1 +]; +var ListAsyncInvokesRequest$ = [3, n0, _LAIR, + 0, + [_sTA, _sTB, _sE, _mR, _nT, _sB, _sO], + [[5, { [_hQ]: _sTA }], [5, { [_hQ]: _sTB }], [0, { [_hQ]: _sE }], [1, { [_hQ]: _mR }], [0, { [_hQ]: _nT }], [0, { [_hQ]: _sB }], [0, { [_hQ]: _sO }]] +]; +var ListAsyncInvokesResponse$ = [3, n0, _LAIRi, + 0, + [_nT, _aIS], + [0, [() => AsyncInvokeSummaries, 0]] +]; +var Message$ = [3, n0, _M, + 0, + [_ro, _co], + [0, [() => ContentBlocks, 0]], 2 +]; +var MessageStartEvent$ = [3, n0, _MSE, + 0, + [_ro], + [0], 1 +]; +var MessageStopEvent$ = [3, n0, _MSEe, + 0, + [_sR, _aMRFd], + [0, 15], 1 +]; +var OutputConfig$ = [3, n0, _OC, + 0, + [_tF, _ef], + [[() => OutputFormat$, 0], 0] +]; +var OutputFormat$ = [3, n0, _OF, + 0, + [_ty, _stru], + [0, [() => OutputFormatStructure$, 0]], 2 +]; +var PayloadPart$ = [3, n0, _PP, + 8, + [_b], + [[() => PartBody, 0]] +]; +var PerformanceConfiguration$ = [3, n0, _PC, + 0, + [_la], + [0] +]; +var PromptRouterTrace$ = [3, n0, _PRT, + 0, + [_iMI], + [0] +]; +var ReasoningTextBlock$ = [3, n0, _RTB, + 8, + [_te, _si], + [0, 0], 1 +]; +var S3Location$ = [3, n0, _SL, + 0, + [_ur, _bO], + [0, 0], 1 +]; +var SearchResultBlock$ = [3, n0, _SRB, + 0, + [_so, _ti, _co, _ci], + [0, 0, () => SearchResultContentBlocks, () => CitationsConfig$], 3 +]; +var SearchResultContentBlock$ = [3, n0, _SRCB, + 0, + [_te], + [0], 1 +]; +var SearchResultLocation$ = [3, n0, _SRL, + 0, + [_sRI, _sta, _end], + [1, 1, 1] +]; +var ServiceTier$ = [3, n0, _ST, + 0, + [_ty], + [0], 1 +]; +var SpecificToolChoice$ = [3, n0, _STC, + 0, + [_n], + [0], 1 +]; +var StartAsyncInvokeRequest$ = [3, n0, _SAIR, + 0, + [_mI, _mIo, _oDC, _cRT, _ta], + [0, [() => ModelInputPayload, 0], () => AsyncInvokeOutputDataConfig$, [0, 4], () => TagList], 3 +]; +var StartAsyncInvokeResponse$ = [3, n0, _SAIRt, + 0, + [_iA], + [0], 1 +]; +var SystemTool$ = [3, n0, _STy, + 0, + [_n], + [0], 1 +]; +var Tag$ = [3, n0, _T, + 0, + [_k, _v], + [0, 0], 2 +]; +var TokenUsage$ = [3, n0, _TU, + 0, + [_iT, _oT, _tT, _cRIT, _cWIT, _cD], + [1, 1, 1, 1, 1, () => CacheDetailsList], 3 +]; +var ToolAdditionBlock$ = [3, n0, _TAB, + 0, + [_too], + [() => ToolReference$], 1 +]; +var ToolConfiguration$ = [3, n0, _TC, + 0, + [_tool, _tCo], + [() => Tools, () => ToolChoice$], 1 +]; +var ToolReference$ = [3, n0, _TR, + 0, + [_ty, _n, _sN], + [0, 0, 0] +]; +var ToolRemovalBlock$ = [3, n0, _TRB, + 0, + [_too], + [() => ToolReference$], 1 +]; +var ToolResultBlock$ = [3, n0, _TRBo, + 0, + [_tUI, _co, _st, _ty], + [0, [() => ToolResultContentBlocks, 0], 0, 0], 2 +]; +var ToolResultBlockStart$ = [3, n0, _TRBS, + 0, + [_tUI, _ty, _st], + [0, 0, 0], 1 +]; +var ToolSpecification$ = [3, n0, _TS, + 0, + [_n, _iS, _des, _stri], + [0, () => ToolInputSchema$, 0, 2], 2 +]; +var ToolUseBlock$ = [3, n0, _TUB, + 0, + [_tUI, _n, _i, _ty], + [0, 0, 15, 0], 3 +]; +var ToolUseBlockDelta$ = [3, n0, _TUBD, + 0, + [_i], + [0], 1 +]; +var ToolUseBlockStart$ = [3, n0, _TUBS, + 0, + [_tUI, _n, _ty], + [0, 0, 0], 2 +]; +var VideoBlock$ = [3, n0, _VB, + 0, + [_f, _so], + [0, () => VideoSource$], 2 +]; +var WebLocation$ = [3, n0, _WL, + 0, + [_url, _do], + [0, 0] +]; +var AsyncInvokeSummaries = [1, n0, _AISs, + 0, [() => AsyncInvokeSummary$, + 0] +]; +var CacheDetailsList = [1, n0, _CDL, + 0, () => CacheDetail$ +]; +var CitationGeneratedContentList = [1, n0, _CGCL, + 0, () => CitationGeneratedContent$ +]; +var Citations = [1, n0, _Ci, + 0, () => Citation$ +]; +var CitationSourceContentList = [1, n0, _CSCL, + 0, () => CitationSourceContent$ +]; +var CitationSourceContentListDelta = [1, n0, _CSCLD, + 0, () => CitationSourceContentDelta$ +]; +var ContentBlocks = [1, n0, _CB, + 0, [() => ContentBlock$, + 0] +]; +var DocumentContentBlocks = [1, n0, _DCB, + 0, () => DocumentContentBlock$ +]; +var GuardrailAssessmentList = [1, n0, _GAL, + 0, [() => GuardrailAssessment$, + 0] +]; +var GuardrailAutomatedReasoningDifferenceScenarioList = [1, n0, _GARDSL, + 0, [() => GuardrailAutomatedReasoningScenario$, + 0] +]; +var GuardrailAutomatedReasoningFindingList = [1, n0, _GARFL, + 0, [() => GuardrailAutomatedReasoningFinding$, + 0] +]; +var GuardrailAutomatedReasoningInputTextReferenceList = [1, n0, _GARITRL, + 0, [() => GuardrailAutomatedReasoningInputTextReference$, + 0] +]; +var GuardrailAutomatedReasoningRuleList = [1, n0, _GARRL, + 0, () => GuardrailAutomatedReasoningRule$ +]; +var GuardrailAutomatedReasoningStatementList = [1, n0, _GARSL, + 0, [() => GuardrailAutomatedReasoningStatement$, + 0] +]; +var GuardrailAutomatedReasoningTranslationList = [1, n0, _GARTL, + 0, [() => GuardrailAutomatedReasoningTranslation$, + 0] +]; +var GuardrailAutomatedReasoningTranslationOptionList = [1, n0, _GARTOL, + 0, [() => GuardrailAutomatedReasoningTranslationOption$, + 0] +]; +var GuardrailChecksContentBlockList = [1, n0, _GCCBL, + 0, [() => GuardrailChecksContentBlock$, + 0] +]; +var GuardrailChecksContentFilterCategoryConfigList = [1, n0, _GCCFCCL, + 0, () => GuardrailChecksContentFilterCategoryConfig$ +]; +var GuardrailChecksContentFilterResultList = [1, n0, _GCCFRL, + 0, () => GuardrailChecksContentFilterResultEntry$ +]; +var GuardrailChecksMessageList = [1, n0, _GCML, + 0, [() => GuardrailChecksMessage$, + 0] +]; +var GuardrailChecksPromptAttackCategoryConfigList = [1, n0, _GCPACCL, + 0, () => GuardrailChecksPromptAttackCategoryConfig$ +]; +var GuardrailChecksPromptAttackResultList = [1, n0, _GCPARL, + 0, () => GuardrailChecksPromptAttackResultEntry$ +]; +var GuardrailChecksSensitiveInformationEntityConfigList = [1, n0, _GCSIECL, + 0, () => GuardrailChecksSensitiveInformationEntityConfig$ +]; +var GuardrailChecksSensitiveInformationResultList = [1, n0, _GCSIRL, + 0, () => GuardrailChecksSensitiveInformationResultEntry$ +]; +var GuardrailContentBlockList = [1, n0, _GCBL, + 0, [() => GuardrailContentBlock$, + 0] +]; +var GuardrailContentFilterList = [1, n0, _GCFL, + 0, () => GuardrailContentFilter$ +]; +var GuardrailContextualGroundingFilters = [1, n0, _GCGFu, + 0, () => GuardrailContextualGroundingFilter$ +]; +var GuardrailCustomWordList = [1, n0, _GCWL, + 0, () => GuardrailCustomWord$ +]; +var GuardrailManagedWordList = [1, n0, _GMWL, + 0, () => GuardrailManagedWord$ +]; +var GuardrailOutputContentList = [1, n0, _GOCL, + 0, () => GuardrailOutputContent$ +]; +var GuardrailPiiEntityFilterList = [1, n0, _GPEFL, + 0, () => GuardrailPiiEntityFilter$ +]; +var GuardrailRegexFilterList = [1, n0, _GRFL, + 0, () => GuardrailRegexFilter$ +]; +var GuardrailTopicList = [1, n0, _GTL, + 0, () => GuardrailTopic$ +]; +var Messages = [1, n0, _Me, + 0, [() => Message$, + 0] +]; +var SearchResultContentBlocks = [1, n0, _SRCBe, + 0, () => SearchResultContentBlock$ +]; +var SystemContentBlocks = [1, n0, _SCB, + 0, [() => SystemContentBlock$, + 0] +]; +var TagList = [1, n0, _TL, + 0, () => Tag$ +]; +var ToolResultBlocksDelta = [1, n0, _TRBD, + 0, () => ToolResultBlockDelta$ +]; +var ToolResultContentBlocks = [1, n0, _TRCB, + 0, [() => ToolResultContentBlock$, + 0] +]; +var Tools = [1, n0, _To, + 0, () => Tool$ +]; +var GuardrailAssessmentListMap = [2, n0, _GALM, + 0, [0, + 0], + [() => GuardrailAssessmentList, + 0] +]; +var GuardrailAssessmentMap = [2, n0, _GAM, + 0, [0, + 0], + [() => GuardrailAssessment$, + 0] +]; +var PromptVariableMap = [2, n0, _PVM, + 8, 0, () => PromptVariableValues$ +]; +var RequestMetadata = [2, n0, _RM, + 8, 0, 0 +]; +var AsyncInvokeOutputDataConfig$ = [4, n0, _AIODC, + 0, + [_sODC], + [() => AsyncInvokeS3OutputDataConfig$] +]; +var AudioSource$ = [4, n0, _AS, + 8, + [_b, _sL], + [21, () => S3Location$] +]; +var CitationGeneratedContent$ = [4, n0, _CGC, + 0, + [_te], + [0] +]; +var CitationLocation$ = [4, n0, _CL, + 0, + [_w, _dC, _dP, _dCo, _sRL], + [() => WebLocation$, () => DocumentCharLocation$, () => DocumentPageLocation$, () => DocumentChunkLocation$, () => SearchResultLocation$] +]; +var CitationSourceContent$ = [4, n0, _CSC, + 0, + [_te], + [0] +]; +var ContentBlock$ = [4, n0, _CBo, + 0, + [_te, _ima, _doc, _vi, _au, _tUo, _tR, _gCua, _cPa, _rC, _cC, _sRe, _tA, _tRo], + [0, [() => ImageBlock$, 0], () => DocumentBlock$, () => VideoBlock$, [() => AudioBlock$, 0], () => ToolUseBlock$, [() => ToolResultBlock$, 0], [() => GuardrailConverseContentBlock$, 0], () => CachePointBlock$, [() => ReasoningContentBlock$, 0], () => CitationsContentBlock$, () => SearchResultBlock$, () => ToolAdditionBlock$, () => ToolRemovalBlock$] +]; +var ContentBlockDelta$ = [4, n0, _CBD, + 0, + [_te, _tUo, _tR, _rC, _cit, _ima], + [0, () => ToolUseBlockDelta$, () => ToolResultBlocksDelta, [() => ReasoningContentBlockDelta$, 0], () => CitationsDelta$, [() => ImageBlockDelta$, 0]] +]; +var ContentBlockStart$ = [4, n0, _CBS, + 0, + [_tUo, _tR, _ima], + [() => ToolUseBlockStart$, () => ToolResultBlockStart$, () => ImageBlockStart$] +]; +var ConverseOutput$ = [4, n0, _CO, + 0, + [_m], + [[() => Message$, 0]] +]; +var ConverseStreamOutput$ = [4, n0, _CSO, + { [_stre]: 1 }, + [_mS, _cBS, _cBD, _cBSo, _mSe, _meta, _iSE, _mSEE, _vE, _tE, _sUE], + [() => MessageStartEvent$, () => ContentBlockStartEvent$, [() => ContentBlockDeltaEvent$, 0], () => ContentBlockStopEvent$, () => MessageStopEvent$, [() => ConverseStreamMetadataEvent$, 0], [() => InternalServerException$, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$, 0], [() => ThrottlingException$, 0], [() => ServiceUnavailableException$, 0]] +]; +var CountTokensInput$ = [4, n0, _CTI, + 0, + [_iMn, _conv], + [[() => InvokeModelTokensRequest$, 0], [() => ConverseTokensRequest$, 0]] +]; +var DocumentContentBlock$ = [4, n0, _DCBo, + 0, + [_te], + [0] +]; +var DocumentSource$ = [4, n0, _DS, + 0, + [_b, _sL, _te, _co], + [21, () => S3Location$, 0, () => DocumentContentBlocks] +]; +var GuardrailAutomatedReasoningFinding$ = [4, n0, _GARF, + 0, + [_va, _in, _sa, _imp, _tAr, _tCoo, _nTo], + [[() => GuardrailAutomatedReasoningValidFinding$, 0], [() => GuardrailAutomatedReasoningInvalidFinding$, 0], [() => GuardrailAutomatedReasoningSatisfiableFinding$, 0], [() => GuardrailAutomatedReasoningImpossibleFinding$, 0], [() => GuardrailAutomatedReasoningTranslationAmbiguousFinding$, 0], () => GuardrailAutomatedReasoningTooComplexFinding$, () => GuardrailAutomatedReasoningNoTranslationsFinding$] +]; +var GuardrailChecksContentBlock$ = [4, n0, _GCCB, + 0, + [_te], + [[() => GuardrailChecksTextContent, 0]] +]; +var GuardrailContentBlock$ = [4, n0, _GCB, + 0, + [_te, _ima], + [() => GuardrailTextBlock$, [() => GuardrailImageBlock$, 0]] +]; +var GuardrailConverseContentBlock$ = [4, n0, _GCCBu, + 0, + [_te, _ima], + [() => GuardrailConverseTextBlock$, [() => GuardrailConverseImageBlock$, 0]] +]; +var GuardrailConverseImageSource$ = [4, n0, _GCIS, + 8, + [_b], + [21] +]; +var GuardrailImageSource$ = [4, n0, _GIS, + 8, + [_b], + [21] +]; +var ImageSource$ = [4, n0, _IS, + 8, + [_b, _sL], + [21, () => S3Location$] +]; +var InvokeModelWithBidirectionalStreamInput$ = [4, n0, _IMWBSI, + { [_stre]: 1 }, + [_chu], + [[() => BidirectionalInputPayloadPart$, 0]] +]; +var InvokeModelWithBidirectionalStreamOutput$ = [4, n0, _IMWBSO, + { [_stre]: 1 }, + [_chu, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], + [[() => BidirectionalOutputPayloadPart$, 0], [() => InternalServerException$, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$, 0], [() => ThrottlingException$, 0], [() => ModelTimeoutException$, 0], [() => ServiceUnavailableException$, 0]] +]; +var OutputFormatStructure$ = [4, n0, _OFS, + 8, + [_jS], + [() => JsonSchemaDefinition$] +]; +var PromptVariableValues$ = [4, n0, _PVV, + 0, + [_te], + [0] +]; +var ReasoningContentBlock$ = [4, n0, _RCB, + 8, + [_rT, _rCe], + [[() => ReasoningTextBlock$, 0], 21] +]; +var ReasoningContentBlockDelta$ = [4, n0, _RCBD, + 8, + [_te, _rCe, _si], + [0, 21, 0] +]; +var ResponseStream$ = [4, n0, _RS, + { [_stre]: 1 }, + [_chu, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], + [[() => PayloadPart$, 0], [() => InternalServerException$, 0], [() => ModelStreamErrorException$, 0], [() => ValidationException$, 0], [() => ThrottlingException$, 0], [() => ModelTimeoutException$, 0], [() => ServiceUnavailableException$, 0]] +]; +var SystemContentBlock$ = [4, n0, _SCBy, + 0, + [_te, _gCua, _cPa], + [0, [() => GuardrailConverseContentBlock$, 0], () => CachePointBlock$] +]; +var Tool$ = [4, n0, _Too, + 0, + [_tS, _sTy, _cPa], + [() => ToolSpecification$, () => SystemTool$, () => CachePointBlock$] +]; +var ToolChoice$ = [4, n0, _TCo, + 0, + [_aut, _an, _too], + [() => AutoToolChoice$, () => AnyToolChoice$, () => SpecificToolChoice$] +]; +var ToolInputSchema$ = [4, n0, _TIS, + 0, + [_j], + [15] +]; +var ToolResultBlockDelta$ = [4, n0, _TRBDo, + 0, + [_te, _j], + [0, 15] +]; +var ToolResultContentBlock$ = [4, n0, _TRCBo, + 0, + [_j, _te, _ima, _doc, _vi, _sRe], + [15, 0, [() => ImageBlock$, 0], () => DocumentBlock$, () => VideoBlock$, () => SearchResultBlock$] +]; +var VideoSource$ = [4, n0, _VS, + 0, + [_b, _sL], + [21, () => S3Location$] +]; +var ApplyGuardrail$ = [9, n0, _AG, + { [_h]: ["POST", "/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply", 200] }, () => ApplyGuardrailRequest$, () => ApplyGuardrailResponse$ +]; +var Converse$ = [9, n0, _Co, + { [_h]: ["POST", "/model/{modelId}/converse", 200] }, () => ConverseRequest$, () => ConverseResponse$ +]; +var ConverseStream$ = [9, n0, _CS, + { [_h]: ["POST", "/model/{modelId}/converse-stream", 200] }, () => ConverseStreamRequest$, () => ConverseStreamResponse$ +]; +var CountTokens$ = [9, n0, _CTo, + { [_h]: ["POST", "/model/{modelId}/count-tokens", 200] }, () => CountTokensRequest$, () => CountTokensResponse$ +]; +var GetAsyncInvoke$ = [9, n0, _GAI, + { [_h]: ["GET", "/async-invoke/{invocationArn}", 200] }, () => GetAsyncInvokeRequest$, () => GetAsyncInvokeResponse$ +]; +var InvokeGuardrailChecks$ = [9, n0, _IGC, + { [_h]: ["POST", "/guardrail-checks/invoke", 200] }, () => InvokeGuardrailChecksRequest$, () => InvokeGuardrailChecksResponse$ +]; +var InvokeModel$ = [9, n0, _IM, + { [_h]: ["POST", "/model/{modelId}/invoke", 200] }, () => InvokeModelRequest$, () => InvokeModelResponse$ +]; +var InvokeModelWithBidirectionalStream$ = [9, n0, _IMWBS, + { [_h]: ["POST", "/model/{modelId}/invoke-with-bidirectional-stream", 200] }, () => InvokeModelWithBidirectionalStreamRequest$, () => InvokeModelWithBidirectionalStreamResponse$ +]; +var InvokeModelWithResponseStream$ = [9, n0, _IMWRS, + { [_h]: ["POST", "/model/{modelId}/invoke-with-response-stream", 200] }, () => InvokeModelWithResponseStreamRequest$, () => InvokeModelWithResponseStreamResponse$ +]; +var ListAsyncInvokes$ = [9, n0, _LAI, + { [_h]: ["GET", "/async-invoke", 200] }, () => ListAsyncInvokesRequest$, () => ListAsyncInvokesResponse$ +]; +var StartAsyncInvoke$ = [9, n0, _SAI, + { [_h]: ["POST", "/async-invoke", 200] }, () => StartAsyncInvokeRequest$, () => StartAsyncInvokeResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2023-09-30", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultBedrockRuntimeHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"), + signer: new HttpBearerAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.bedrockruntime", + errorTypeRegistries, + version: "2023-09-30", + serviceTarget: "AmazonBedrockFrontendService", + }, + serviceId: config?.serviceId ?? "Bedrock Runtime", + sha256: config?.sha256 ?? Sha256, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + signingName: "bedrock", + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + eventStreamPayloadHandlerProvider: config?.eventStreamPayloadHandlerProvider ?? eventStreamPayloadHandlerProvider, + eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#httpBearerAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") || (async (idProps) => { + try { + return await fromEnvSigningName({ signingName: "bedrock" })(); + } + catch (error) { + return await nodeProvider(idProps)(idProps); + } + }), + signer: new HttpBearerAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttp2Handler.create(config?.requestHandler ?? (async () => ({ + ...await defaultConfigProvider(), + disableConcurrentStreams: true + }))), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + let _token = runtimeConfig.token; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + setToken(token) { + _token = token; + }, + token() { + return _token; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + token: config.token(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class BedrockRuntimeClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveEventStreamSerdeConfig(_config_6); + const _config_8 = resolveHttpAuthSchemeConfig(_config_7); + const _config_9 = resolveEventStreamConfig(_config_8); + const _config_10 = resolveWebSocketConfig(_config_9); + const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []); + this.config = _config_11; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultBedrockRuntimeHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + "smithy.api#httpBearerAuth": config.token, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "AmazonBedrockFrontendService", "BedrockRuntimeClient", getEndpointPlugin); +const _ep0 = {}; +const _mw0 = (Command, cs, config, o) => []; +const _mw1 = (Command, cs, config, o) => [ + getEventStreamPlugin(config), + getWebSocketPlugin(config, { + headerPrefix: "x-amz-bedrock-", + }), +]; + +class ApplyGuardrailCommand extends command(_ep0, _mw0, "ApplyGuardrail", ApplyGuardrail$) { +} + +class ConverseCommand extends command(_ep0, _mw0, "Converse", Converse$) { +} + +class ConverseStreamCommand extends command(_ep0, _mw0, "ConverseStream", ConverseStream$) { +} + +class CountTokensCommand extends command(_ep0, _mw0, "CountTokens", CountTokens$) { +} + +class GetAsyncInvokeCommand extends command(_ep0, _mw0, "GetAsyncInvoke", GetAsyncInvoke$) { +} + +class InvokeGuardrailChecksCommand extends command(_ep0, _mw0, "InvokeGuardrailChecks", InvokeGuardrailChecks$) { +} + +class InvokeModelCommand extends command(_ep0, _mw0, "InvokeModel", InvokeModel$) { +} + +class InvokeModelWithBidirectionalStreamCommand extends command(_ep0, _mw1, "InvokeModelWithBidirectionalStream", InvokeModelWithBidirectionalStream$) { +} + +class InvokeModelWithResponseStreamCommand extends command(_ep0, _mw0, "InvokeModelWithResponseStream", InvokeModelWithResponseStream$) { +} + +class ListAsyncInvokesCommand extends command(_ep0, _mw0, "ListAsyncInvokes", ListAsyncInvokes$) { +} + +class StartAsyncInvokeCommand extends command(_ep0, _mw0, "StartAsyncInvoke", StartAsyncInvoke$) { +} + +const paginateListAsyncInvokes = createPaginator(BedrockRuntimeClient, ListAsyncInvokesCommand, "nextToken", "nextToken", "maxResults"); + +const commands = { + ApplyGuardrailCommand, + ConverseCommand, + ConverseStreamCommand, + CountTokensCommand, + GetAsyncInvokeCommand, + InvokeGuardrailChecksCommand, + InvokeModelCommand, + InvokeModelWithBidirectionalStreamCommand, + InvokeModelWithResponseStreamCommand, + ListAsyncInvokesCommand, + StartAsyncInvokeCommand, +}; +const paginators = { + paginateListAsyncInvokes, +}; +class BedrockRuntime extends BedrockRuntimeClient { +} +createAggregatedClient(commands, BedrockRuntime, { paginators }); + +const AsyncInvokeStatus = { + COMPLETED: "Completed", + FAILED: "Failed", + IN_PROGRESS: "InProgress", +}; +const SortAsyncInvocationBy = { + SUBMISSION_TIME: "SubmissionTime", +}; +const SortOrder = { + ASCENDING: "Ascending", + DESCENDING: "Descending", +}; +const GuardrailImageFormat = { + JPEG: "jpeg", + PNG: "png", +}; +const GuardrailContentQualifier = { + GROUNDING_SOURCE: "grounding_source", + GUARD_CONTENT: "guard_content", + QUERY: "query", +}; +const GuardrailOutputScope = { + FULL: "FULL", + INTERVENTIONS: "INTERVENTIONS", +}; +const GuardrailContentSource = { + INPUT: "INPUT", + OUTPUT: "OUTPUT", +}; +const GuardrailAction = { + GUARDRAIL_INTERVENED: "GUARDRAIL_INTERVENED", + NONE: "NONE", +}; +const GuardrailOrigin = { + ACCOUNT_ENFORCED: "ACCOUNT_ENFORCED", + ORGANIZATION_ENFORCED: "ORGANIZATION_ENFORCED", + REQUEST: "REQUEST", +}; +const GuardrailOwnership = { + CROSS_ACCOUNT: "CROSS_ACCOUNT", + SELF: "SELF", +}; +const GuardrailAutomatedReasoningLogicWarningType = { + ALWAYS_FALSE: "ALWAYS_FALSE", + ALWAYS_TRUE: "ALWAYS_TRUE", +}; +const GuardrailContentPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailContentFilterConfidence = { + HIGH: "HIGH", + LOW: "LOW", + MEDIUM: "MEDIUM", + NONE: "NONE", +}; +const GuardrailContentFilterStrength = { + HIGH: "HIGH", + LOW: "LOW", + MEDIUM: "MEDIUM", + NONE: "NONE", +}; +const GuardrailContentFilterType = { + HATE: "HATE", + INSULTS: "INSULTS", + MISCONDUCT: "MISCONDUCT", + PROMPT_ATTACK: "PROMPT_ATTACK", + SEXUAL: "SEXUAL", + VIOLENCE: "VIOLENCE", +}; +const GuardrailContextualGroundingPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailContextualGroundingFilterType = { + GROUNDING: "GROUNDING", + RELEVANCE: "RELEVANCE", +}; +const GuardrailSensitiveInformationPolicyAction = { + ANONYMIZED: "ANONYMIZED", + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailPiiEntityType = { + ADDRESS: "ADDRESS", + AGE: "AGE", + AWS_ACCESS_KEY: "AWS_ACCESS_KEY", + AWS_SECRET_KEY: "AWS_SECRET_KEY", + CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", + CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", + CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", + CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", + CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", + DRIVER_ID: "DRIVER_ID", + EMAIL: "EMAIL", + INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", + IP_ADDRESS: "IP_ADDRESS", + LICENSE_PLATE: "LICENSE_PLATE", + MAC_ADDRESS: "MAC_ADDRESS", + NAME: "NAME", + PASSWORD: "PASSWORD", + PHONE: "PHONE", + PIN: "PIN", + SWIFT_CODE: "SWIFT_CODE", + UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", + UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", + UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", + URL: "URL", + USERNAME: "USERNAME", + US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", + US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", + US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", + US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", + US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", + VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", +}; +const GuardrailTopicPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailTopicType = { + DENY: "DENY", +}; +const GuardrailWordPolicyAction = { + BLOCKED: "BLOCKED", + NONE: "NONE", +}; +const GuardrailManagedWordType = { + PROFANITY: "PROFANITY", +}; +const GuardrailChecksContentFilterCategory = { + HATE: "HATE", + INSULTS: "INSULTS", + MISCONDUCT: "MISCONDUCT", + SEXUAL: "SEXUAL", + VIOLENCE: "VIOLENCE", +}; +const GuardrailChecksPromptAttackCategory = { + JAILBREAK: "JAILBREAK", + PROMPT_INJECTION: "PROMPT_INJECTION", + PROMPT_LEAKAGE: "PROMPT_LEAKAGE", +}; +const GuardrailChecksSensitiveInformationEntityType = { + ADDRESS: "ADDRESS", + AGE: "AGE", + AWS_ACCESS_KEY: "AWS_ACCESS_KEY", + AWS_SECRET_KEY: "AWS_SECRET_KEY", + CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", + CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", + CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", + CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", + CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", + DRIVER_ID: "DRIVER_ID", + EMAIL: "EMAIL", + INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", + IP_ADDRESS: "IP_ADDRESS", + LICENSE_PLATE: "LICENSE_PLATE", + MAC_ADDRESS: "MAC_ADDRESS", + NAME: "NAME", + PASSWORD: "PASSWORD", + PHONE: "PHONE", + PIN: "PIN", + SWIFT_CODE: "SWIFT_CODE", + UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", + UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", + UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", + URL: "URL", + USERNAME: "USERNAME", + US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", + US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", + US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", + US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", + US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", + VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", +}; +const GuardrailChecksRole = { + ASSISTANT: "assistant", + SYSTEM: "system", + USER: "user", +}; +const GuardrailTrace = { + DISABLED: "disabled", + ENABLED: "enabled", + ENABLED_FULL: "enabled_full", +}; +const AudioFormat = { + AAC: "aac", + FLAC: "flac", + M4A: "m4a", + MKA: "mka", + MKV: "mkv", + MP3: "mp3", + MP4: "mp4", + MPEG: "mpeg", + MPGA: "mpga", + OGG: "ogg", + OPUS: "opus", + PCM: "pcm", + WAV: "wav", + WEBM: "webm", + X_AAC: "x-aac", +}; +const CacheTTL = { + FIVE_MINUTES: "5m", + ONE_HOUR: "1h", +}; +const CachePointType = { + DEFAULT: "default", +}; +const DocumentFormat = { + CSV: "csv", + DOC: "doc", + DOCX: "docx", + HTML: "html", + MD: "md", + PDF: "pdf", + TXT: "txt", + XLS: "xls", + XLSX: "xlsx", +}; +const GuardrailConverseImageFormat = { + JPEG: "jpeg", + PNG: "png", +}; +const GuardrailConverseContentQualifier = { + GROUNDING_SOURCE: "grounding_source", + GUARD_CONTENT: "guard_content", + QUERY: "query", +}; +const ImageFormat = { + GIF: "gif", + JPEG: "jpeg", + PNG: "png", + WEBP: "webp", +}; +const VideoFormat = { + FLV: "flv", + MKV: "mkv", + MOV: "mov", + MP4: "mp4", + MPEG: "mpeg", + MPG: "mpg", + THREE_GP: "three_gp", + WEBM: "webm", + WMV: "wmv", +}; +const ToolResultStatus = { + ERROR: "error", + SUCCESS: "success", +}; +const ToolUseType = { + SERVER_TOOL_USE: "server_tool_use", +}; +const ConversationRole = { + ASSISTANT: "assistant", + SYSTEM: "system", + USER: "user", +}; +const OutputFormatType = { + JSON_SCHEMA: "json_schema", +}; +const PerformanceConfigLatency = { + OPTIMIZED: "optimized", + STANDARD: "standard", +}; +const ServiceTierType = { + DEFAULT: "default", + FLEX: "flex", + PRIORITY: "priority", + RESERVED: "reserved", +}; +const StopReason = { + CONTENT_FILTERED: "content_filtered", + END_TURN: "end_turn", + GUARDRAIL_INTERVENED: "guardrail_intervened", + MALFORMED_MODEL_OUTPUT: "malformed_model_output", + MALFORMED_TOOL_USE: "malformed_tool_use", + MAX_TOKENS: "max_tokens", + MODEL_CONTEXT_WINDOW_EXCEEDED: "model_context_window_exceeded", + STOP_SEQUENCE: "stop_sequence", + TOOL_USE: "tool_use", +}; +const GuardrailStreamProcessingMode = { + ASYNC: "async", + SYNC: "sync", +}; +const Trace = { + DISABLED: "DISABLED", + ENABLED: "ENABLED", + ENABLED_FULL: "ENABLED_FULL", +}; + +__webpack_unused_export__ = AccessDeniedException; +__webpack_unused_export__ = AccessDeniedException$; +__webpack_unused_export__ = AnyToolChoice$; +__webpack_unused_export__ = AppliedGuardrailDetails$; +__webpack_unused_export__ = ApplyGuardrail$; +__webpack_unused_export__ = ApplyGuardrailCommand; +__webpack_unused_export__ = ApplyGuardrailRequest$; +__webpack_unused_export__ = ApplyGuardrailResponse$; +__webpack_unused_export__ = AsyncInvokeOutputDataConfig$; +__webpack_unused_export__ = AsyncInvokeS3OutputDataConfig$; +__webpack_unused_export__ = AsyncInvokeStatus; +__webpack_unused_export__ = AsyncInvokeSummary$; +__webpack_unused_export__ = AudioBlock$; +__webpack_unused_export__ = AudioFormat; +__webpack_unused_export__ = AudioSource$; +__webpack_unused_export__ = AutoToolChoice$; +__webpack_unused_export__ = BedrockRuntime; +exports.mam = BedrockRuntimeClient; +exports.bY6 = BedrockRuntimeServiceException; +__webpack_unused_export__ = BedrockRuntimeServiceException$; +__webpack_unused_export__ = BidirectionalInputPayloadPart$; +__webpack_unused_export__ = BidirectionalOutputPayloadPart$; +__webpack_unused_export__ = CacheDetail$; +__webpack_unused_export__ = CachePointBlock$; +exports.zRl = CachePointType; +exports.xN0 = CacheTTL; +__webpack_unused_export__ = Citation$; +__webpack_unused_export__ = CitationGeneratedContent$; +__webpack_unused_export__ = CitationLocation$; +__webpack_unused_export__ = CitationSourceContent$; +__webpack_unused_export__ = CitationSourceContentDelta$; +__webpack_unused_export__ = CitationsConfig$; +__webpack_unused_export__ = CitationsContentBlock$; +__webpack_unused_export__ = CitationsDelta$; +__webpack_unused_export__ = ConflictException; +__webpack_unused_export__ = ConflictException$; +__webpack_unused_export__ = ContentBlock$; +__webpack_unused_export__ = ContentBlockDelta$; +__webpack_unused_export__ = ContentBlockDeltaEvent$; +__webpack_unused_export__ = ContentBlockStart$; +__webpack_unused_export__ = ContentBlockStartEvent$; +__webpack_unused_export__ = ContentBlockStopEvent$; +exports.sCr = ConversationRole; +__webpack_unused_export__ = Converse$; +__webpack_unused_export__ = ConverseCommand; +__webpack_unused_export__ = ConverseMetrics$; +__webpack_unused_export__ = ConverseOutput$; +__webpack_unused_export__ = ConverseRequest$; +__webpack_unused_export__ = ConverseResponse$; +__webpack_unused_export__ = ConverseStream$; +exports.vDc = ConverseStreamCommand; +__webpack_unused_export__ = ConverseStreamMetadataEvent$; +__webpack_unused_export__ = ConverseStreamMetrics$; +__webpack_unused_export__ = ConverseStreamOutput$; +__webpack_unused_export__ = ConverseStreamRequest$; +__webpack_unused_export__ = ConverseStreamResponse$; +__webpack_unused_export__ = ConverseStreamTrace$; +__webpack_unused_export__ = ConverseTokensRequest$; +__webpack_unused_export__ = ConverseTrace$; +__webpack_unused_export__ = CountTokens$; +__webpack_unused_export__ = CountTokensCommand; +__webpack_unused_export__ = CountTokensInput$; +__webpack_unused_export__ = CountTokensRequest$; +__webpack_unused_export__ = CountTokensResponse$; +__webpack_unused_export__ = DocumentBlock$; +__webpack_unused_export__ = DocumentCharLocation$; +__webpack_unused_export__ = DocumentChunkLocation$; +__webpack_unused_export__ = DocumentContentBlock$; +__webpack_unused_export__ = DocumentFormat; +__webpack_unused_export__ = DocumentPageLocation$; +__webpack_unused_export__ = DocumentSource$; +__webpack_unused_export__ = ErrorBlock$; +__webpack_unused_export__ = GetAsyncInvoke$; +__webpack_unused_export__ = GetAsyncInvokeCommand; +__webpack_unused_export__ = GetAsyncInvokeRequest$; +__webpack_unused_export__ = GetAsyncInvokeResponse$; +__webpack_unused_export__ = GuardrailAction; +__webpack_unused_export__ = GuardrailAssessment$; +__webpack_unused_export__ = GuardrailAutomatedReasoningFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningImpossibleFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningInputTextReference$; +__webpack_unused_export__ = GuardrailAutomatedReasoningInvalidFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningLogicWarning$; +__webpack_unused_export__ = GuardrailAutomatedReasoningLogicWarningType; +__webpack_unused_export__ = GuardrailAutomatedReasoningNoTranslationsFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningPolicyAssessment$; +__webpack_unused_export__ = GuardrailAutomatedReasoningRule$; +__webpack_unused_export__ = GuardrailAutomatedReasoningSatisfiableFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningScenario$; +__webpack_unused_export__ = GuardrailAutomatedReasoningStatement$; +__webpack_unused_export__ = GuardrailAutomatedReasoningTooComplexFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningTranslation$; +__webpack_unused_export__ = GuardrailAutomatedReasoningTranslationAmbiguousFinding$; +__webpack_unused_export__ = GuardrailAutomatedReasoningTranslationOption$; +__webpack_unused_export__ = GuardrailAutomatedReasoningValidFinding$; +__webpack_unused_export__ = GuardrailChecksConfig$; +__webpack_unused_export__ = GuardrailChecksContentBlock$; +__webpack_unused_export__ = GuardrailChecksContentFilterCategory; +__webpack_unused_export__ = GuardrailChecksContentFilterCategoryConfig$; +__webpack_unused_export__ = GuardrailChecksContentFilterConfig$; +__webpack_unused_export__ = GuardrailChecksContentFilterResult$; +__webpack_unused_export__ = GuardrailChecksContentFilterResultEntry$; +__webpack_unused_export__ = GuardrailChecksContentFilterUsage$; +__webpack_unused_export__ = GuardrailChecksMessage$; +__webpack_unused_export__ = GuardrailChecksPromptAttackCategory; +__webpack_unused_export__ = GuardrailChecksPromptAttackCategoryConfig$; +__webpack_unused_export__ = GuardrailChecksPromptAttackConfig$; +__webpack_unused_export__ = GuardrailChecksPromptAttackResult$; +__webpack_unused_export__ = GuardrailChecksPromptAttackResultEntry$; +__webpack_unused_export__ = GuardrailChecksPromptAttackUsage$; +__webpack_unused_export__ = GuardrailChecksResults$; +__webpack_unused_export__ = GuardrailChecksRole; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationConfig$; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationEntityConfig$; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationEntityType; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationResult$; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationResultEntry$; +__webpack_unused_export__ = GuardrailChecksSensitiveInformationUsage$; +__webpack_unused_export__ = GuardrailChecksUsageResults$; +__webpack_unused_export__ = GuardrailConfiguration$; +__webpack_unused_export__ = GuardrailContentBlock$; +__webpack_unused_export__ = GuardrailContentFilter$; +__webpack_unused_export__ = GuardrailContentFilterConfidence; +__webpack_unused_export__ = GuardrailContentFilterStrength; +__webpack_unused_export__ = GuardrailContentFilterType; +__webpack_unused_export__ = GuardrailContentPolicyAction; +__webpack_unused_export__ = GuardrailContentPolicyAssessment$; +__webpack_unused_export__ = GuardrailContentQualifier; +__webpack_unused_export__ = GuardrailContentSource; +__webpack_unused_export__ = GuardrailContextualGroundingFilter$; +__webpack_unused_export__ = GuardrailContextualGroundingFilterType; +__webpack_unused_export__ = GuardrailContextualGroundingPolicyAction; +__webpack_unused_export__ = GuardrailContextualGroundingPolicyAssessment$; +__webpack_unused_export__ = GuardrailConverseContentBlock$; +__webpack_unused_export__ = GuardrailConverseContentQualifier; +__webpack_unused_export__ = GuardrailConverseImageBlock$; +__webpack_unused_export__ = GuardrailConverseImageFormat; +__webpack_unused_export__ = GuardrailConverseImageSource$; +__webpack_unused_export__ = GuardrailConverseTextBlock$; +__webpack_unused_export__ = GuardrailCoverage$; +__webpack_unused_export__ = GuardrailCustomWord$; +__webpack_unused_export__ = GuardrailImageBlock$; +__webpack_unused_export__ = GuardrailImageCoverage$; +__webpack_unused_export__ = GuardrailImageFormat; +__webpack_unused_export__ = GuardrailImageSource$; +__webpack_unused_export__ = GuardrailInvocationMetrics$; +__webpack_unused_export__ = GuardrailManagedWord$; +__webpack_unused_export__ = GuardrailManagedWordType; +__webpack_unused_export__ = GuardrailOrigin; +__webpack_unused_export__ = GuardrailOutputContent$; +__webpack_unused_export__ = GuardrailOutputScope; +__webpack_unused_export__ = GuardrailOwnership; +__webpack_unused_export__ = GuardrailPiiEntityFilter$; +__webpack_unused_export__ = GuardrailPiiEntityType; +__webpack_unused_export__ = GuardrailRegexFilter$; +__webpack_unused_export__ = GuardrailSensitiveInformationPolicyAction; +__webpack_unused_export__ = GuardrailSensitiveInformationPolicyAssessment$; +__webpack_unused_export__ = GuardrailStreamConfiguration$; +__webpack_unused_export__ = GuardrailStreamProcessingMode; +__webpack_unused_export__ = GuardrailTextBlock$; +__webpack_unused_export__ = GuardrailTextCharactersCoverage$; +__webpack_unused_export__ = GuardrailTopic$; +__webpack_unused_export__ = GuardrailTopicPolicyAction; +__webpack_unused_export__ = GuardrailTopicPolicyAssessment$; +__webpack_unused_export__ = GuardrailTopicType; +__webpack_unused_export__ = GuardrailTrace; +__webpack_unused_export__ = GuardrailTraceAssessment$; +__webpack_unused_export__ = GuardrailUsage$; +__webpack_unused_export__ = GuardrailWordPolicyAction; +__webpack_unused_export__ = GuardrailWordPolicyAssessment$; +__webpack_unused_export__ = ImageBlock$; +__webpack_unused_export__ = ImageBlockDelta$; +__webpack_unused_export__ = ImageBlockStart$; +exports.f5W = ImageFormat; +__webpack_unused_export__ = ImageSource$; +__webpack_unused_export__ = InferenceConfiguration$; +__webpack_unused_export__ = InternalServerException; +__webpack_unused_export__ = InternalServerException$; +__webpack_unused_export__ = InvokeGuardrailChecks$; +__webpack_unused_export__ = InvokeGuardrailChecksCommand; +__webpack_unused_export__ = InvokeGuardrailChecksRequest$; +__webpack_unused_export__ = InvokeGuardrailChecksResponse$; +__webpack_unused_export__ = InvokeModel$; +__webpack_unused_export__ = InvokeModelCommand; +__webpack_unused_export__ = InvokeModelRequest$; +__webpack_unused_export__ = InvokeModelResponse$; +__webpack_unused_export__ = InvokeModelTokensRequest$; +__webpack_unused_export__ = InvokeModelWithBidirectionalStream$; +__webpack_unused_export__ = InvokeModelWithBidirectionalStreamCommand; +__webpack_unused_export__ = InvokeModelWithBidirectionalStreamInput$; +__webpack_unused_export__ = InvokeModelWithBidirectionalStreamOutput$; +__webpack_unused_export__ = InvokeModelWithBidirectionalStreamRequest$; +__webpack_unused_export__ = InvokeModelWithBidirectionalStreamResponse$; +__webpack_unused_export__ = InvokeModelWithResponseStream$; +__webpack_unused_export__ = InvokeModelWithResponseStreamCommand; +__webpack_unused_export__ = InvokeModelWithResponseStreamRequest$; +__webpack_unused_export__ = InvokeModelWithResponseStreamResponse$; +__webpack_unused_export__ = JsonSchemaDefinition$; +__webpack_unused_export__ = ListAsyncInvokes$; +__webpack_unused_export__ = ListAsyncInvokesCommand; +__webpack_unused_export__ = ListAsyncInvokesRequest$; +__webpack_unused_export__ = ListAsyncInvokesResponse$; +__webpack_unused_export__ = Message$; +__webpack_unused_export__ = MessageStartEvent$; +__webpack_unused_export__ = MessageStopEvent$; +__webpack_unused_export__ = ModelErrorException; +__webpack_unused_export__ = ModelErrorException$; +__webpack_unused_export__ = ModelNotReadyException; +__webpack_unused_export__ = ModelNotReadyException$; +__webpack_unused_export__ = ModelStreamErrorException; +__webpack_unused_export__ = ModelStreamErrorException$; +__webpack_unused_export__ = ModelTimeoutException; +__webpack_unused_export__ = ModelTimeoutException$; +__webpack_unused_export__ = OutputConfig$; +__webpack_unused_export__ = OutputFormat$; +__webpack_unused_export__ = OutputFormatStructure$; +__webpack_unused_export__ = OutputFormatType; +__webpack_unused_export__ = PayloadPart$; +__webpack_unused_export__ = PerformanceConfigLatency; +__webpack_unused_export__ = PerformanceConfiguration$; +__webpack_unused_export__ = PromptRouterTrace$; +__webpack_unused_export__ = PromptVariableValues$; +__webpack_unused_export__ = ReasoningContentBlock$; +__webpack_unused_export__ = ReasoningContentBlockDelta$; +__webpack_unused_export__ = ReasoningTextBlock$; +__webpack_unused_export__ = ResourceNotFoundException; +__webpack_unused_export__ = ResourceNotFoundException$; +__webpack_unused_export__ = ResponseStream$; +__webpack_unused_export__ = S3Location$; +__webpack_unused_export__ = SearchResultBlock$; +__webpack_unused_export__ = SearchResultContentBlock$; +__webpack_unused_export__ = SearchResultLocation$; +__webpack_unused_export__ = ServiceQuotaExceededException; +__webpack_unused_export__ = ServiceQuotaExceededException$; +__webpack_unused_export__ = ServiceTier$; +__webpack_unused_export__ = ServiceTierType; +__webpack_unused_export__ = ServiceUnavailableException; +__webpack_unused_export__ = ServiceUnavailableException$; +__webpack_unused_export__ = SortAsyncInvocationBy; +__webpack_unused_export__ = SortOrder; +__webpack_unused_export__ = SpecificToolChoice$; +__webpack_unused_export__ = StartAsyncInvoke$; +__webpack_unused_export__ = StartAsyncInvokeCommand; +__webpack_unused_export__ = StartAsyncInvokeRequest$; +__webpack_unused_export__ = StartAsyncInvokeResponse$; +exports.TnC = StopReason; +__webpack_unused_export__ = SystemContentBlock$; +__webpack_unused_export__ = SystemTool$; +__webpack_unused_export__ = Tag$; +__webpack_unused_export__ = ThrottlingException; +__webpack_unused_export__ = ThrottlingException$; +__webpack_unused_export__ = TokenUsage$; +__webpack_unused_export__ = Tool$; +__webpack_unused_export__ = ToolAdditionBlock$; +__webpack_unused_export__ = ToolChoice$; +__webpack_unused_export__ = ToolConfiguration$; +__webpack_unused_export__ = ToolInputSchema$; +__webpack_unused_export__ = ToolReference$; +__webpack_unused_export__ = ToolRemovalBlock$; +__webpack_unused_export__ = ToolResultBlock$; +__webpack_unused_export__ = ToolResultBlockDelta$; +__webpack_unused_export__ = ToolResultBlockStart$; +__webpack_unused_export__ = ToolResultContentBlock$; +exports.kz_ = ToolResultStatus; +__webpack_unused_export__ = ToolSpecification$; +__webpack_unused_export__ = ToolUseBlock$; +__webpack_unused_export__ = ToolUseBlockDelta$; +__webpack_unused_export__ = ToolUseBlockStart$; +__webpack_unused_export__ = ToolUseType; +__webpack_unused_export__ = Trace; +__webpack_unused_export__ = ValidationException; +__webpack_unused_export__ = ValidationException$; +__webpack_unused_export__ = VideoBlock$; +__webpack_unused_export__ = VideoFormat; +__webpack_unused_export__ = VideoSource$; +__webpack_unused_export__ = WebLocation$; +__webpack_unused_export__ = errorTypeRegistries; +__webpack_unused_export__ = paginateListAsyncInvokes; + + +/***/ }), + +/***/ 82172: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Retry, RETRY_MODES } = __webpack_require__(89368); +const { HttpRequest, parseUrl } = __webpack_require__(37015); +const { InvokeStore } = __webpack_require__(31934); +const { normalizeProvider } = __webpack_require__(89273); +const { platform, release } = __webpack_require__(48161); +const { versions, env } = __webpack_require__(1708); +const { isValidHostLabel, isIpAddress, customEndpointFunctions } = __webpack_require__(19564); +const { EndpointError, resolveEndpoint } = __webpack_require__(19564); +exports.EndpointError = EndpointError; +exports.isIpAddress = isIpAddress; +exports.resolveEndpoint = resolveEndpoint; +const { loadConfig, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS } = __webpack_require__(48132); +const { REGION_ENV_NAME, REGION_INI_NAME, resolveRegionConfig } = __webpack_require__(48132); +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.resolveRegionConfig = resolveRegionConfig; + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted) { + if (process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED === "true") { + state.warningEmitted = true; + return; + } + const userMajorVersion = parseInt(version.substring(1, version.indexOf("."))); + const vv = 22; + if (userMajorVersion < vv) { + state.warningEmitted = true; + process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3) +versions published after the first week of January 2027 +will require node >=${vv}. You are running node ${version}. + +To continue receiving updates to AWS services, bug fixes, +and security updates please upgrade to node >=${vv}. + +More information can be found at: https://a.co/c895JFp`); + } + } +}; + +const longPollMiddleware = () => (next, context) => async (args) => { + context.__retryLongPoll = true; + return next(args); +}; +const longPollMiddlewareOptions = { + name: "longPollMiddleware", + tags: ["RETRY"], + step: "initialize", + override: true, +}; +const getLongPollPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(longPollMiddleware(), longPollMiddlewareOptions); + }, +}); + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +Retry.v2026 ||= typeof process === "object" && process.env?.AWS_NEW_RETRIES_2026 === "true"; +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +function resolveHostHeaderConfig(input) { + return input; +} +const hostHeaderMiddleware = (options) => (next) => async (args) => { + if (!HttpRequest.isInstance(args.request)) + return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } + else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) + host += `:${request.port}`; + request.headers["host"] = host; + } + return next(args); +}; +const hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true, +}; +const getHostHeaderPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, +}); + +const loggerMiddleware = () => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata, + }); + return response; + } + catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata, + }); + throw error; + } +}; +const loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true, +}; +const getLoggerPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, +}); + +const recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION", "TRACE_CONTEXT_PROPAGATION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low", +}; + +const AWS_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +const _X_AMZN_TRACE_ID = "_X_AMZN_TRACE_ID"; +const X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"; +const TRACEPARENT = "traceparent"; +const TRACESTATE = "tracestate"; +const BAGGAGE = "baggage"; +const recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) { + return next(args); + } + let invokeStore; + { + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === X_AMZN_TRACE_ID.toLowerCase()) ?? + X_AMZN_TRACE_ID; + if (!request.headers.hasOwnProperty(traceIdHeader)) { + const functionName = process.env[AWS_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[_X_AMZN_TRACE_ID]; + invokeStore ??= await InvokeStore.getInstanceAsync(); + const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[X_AMZN_TRACE_ID] = traceId; + } + } + } + { + sanitizeTraceHeaders(request.headers); + const existingTraceparent = request.headers[TRACEPARENT]; + if (!existingTraceparent) { + const traceparent = (invokeStore ??= await InvokeStore.getInstanceAsync())?.getTraceparent?.(); + if (traceparent) { + request.headers[TRACEPARENT] = traceparent; + const tracestate = invokeStore?.getTracestate?.(); + if (tracestate) { + request.headers[TRACESTATE] = tracestate; + } + const baggage = invokeStore?.getBaggage?.(); + if (baggage) { + request.headers[BAGGAGE] = baggage; + } + } + } + } + return next(args); +}; +function sanitizeTraceHeaders(headers) { + for (const header of Object.keys(headers)) { + const lower = header.toLowerCase(); + if (header !== lower && (lower === TRACEPARENT || lower === TRACESTATE || lower === BAGGAGE)) { + headers[lower] = headers[header]; + delete headers[header]; + } + } +} + +const getRecursionDetectionPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); + }, +}); + +const DEFAULT_UA_APP_ID = undefined; +function isValidUserAgentAppId(appId) { + if (appId === undefined) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } + else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, + }); +} + +const partitionsInfo = { + "partitions": [ + { + "id": "aws", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "implicitGlobalRegion": "us-east-1", + "name": "aws", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + "regions": { + "af-south-1": { + "description": "Africa (Cape Town)" + }, + "ap-east-1": { + "description": "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + "description": "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + "description": "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + "description": "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + "description": "Asia Pacific (Osaka)" + }, + "ap-south-1": { + "description": "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + "description": "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + "description": "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + "description": "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + "description": "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + "description": "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + "description": "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + "description": "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + "description": "Asia Pacific (Thailand)" + }, + "aws-global": { + "description": "aws global region" + }, + "ca-central-1": { + "description": "Canada (Central)" + }, + "ca-west-1": { + "description": "Canada West (Calgary)" + }, + "eu-central-1": { + "description": "Europe (Frankfurt)" + }, + "eu-central-2": { + "description": "Europe (Zurich)" + }, + "eu-north-1": { + "description": "Europe (Stockholm)" + }, + "eu-south-1": { + "description": "Europe (Milan)" + }, + "eu-south-2": { + "description": "Europe (Spain)" + }, + "eu-west-1": { + "description": "Europe (Ireland)" + }, + "eu-west-2": { + "description": "Europe (London)" + }, + "eu-west-3": { + "description": "Europe (Paris)" + }, + "il-central-1": { + "description": "Israel (Tel Aviv)" + }, + "me-central-1": { + "description": "Middle East (UAE)" + }, + "me-south-1": { + "description": "Middle East (Bahrain)" + }, + "mx-central-1": { + "description": "Mexico (Central)" + }, + "sa-east-1": { + "description": "South America (Sao Paulo)" + }, + "us-east-1": { + "description": "US East (N. Virginia)" + }, + "us-east-2": { + "description": "US East (Ohio)" + }, + "us-west-1": { + "description": "US West (N. California)" + }, + "us-west-2": { + "description": "US West (Oregon)" + } + } + }, + { + "id": "aws-cn", + "outputs": { + "dnsSuffix": "amazonaws.com.cn", + "dualStackDnsSuffix": "api.amazonwebservices.com.cn", + "implicitGlobalRegion": "cn-northwest-1", + "name": "aws-cn", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^cn\\-\\w+\\-\\d+$", + "regions": { + "aws-cn-global": { + "description": "aws-cn global region" + }, + "cn-north-1": { + "description": "China (Beijing)" + }, + "cn-northwest-1": { + "description": "China (Ningxia)" + } + } + }, + { + "id": "aws-eusc", + "outputs": { + "dnsSuffix": "amazonaws.eu", + "dualStackDnsSuffix": "api.amazonwebservices.eu", + "implicitGlobalRegion": "eusc-de-east-1", + "name": "aws-eusc", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^eusc\\-(de)\\-\\w+\\-\\d+$", + "regions": { + "eusc-de-east-1": { + "description": "AWS European Sovereign Cloud (Germany)" + } + } + }, + { + "id": "aws-iso", + "outputs": { + "dnsSuffix": "c2s.ic.gov", + "dualStackDnsSuffix": "api.aws.ic.gov", + "implicitGlobalRegion": "us-iso-east-1", + "name": "aws-iso", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-iso\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-global": { + "description": "aws-iso global region" + }, + "us-iso-east-1": { + "description": "US ISO East" + }, + "us-iso-west-1": { + "description": "US ISO WEST" + } + } + }, + { + "id": "aws-iso-b", + "outputs": { + "dnsSuffix": "sc2s.sgov.gov", + "dualStackDnsSuffix": "api.aws.scloud", + "implicitGlobalRegion": "us-isob-east-1", + "name": "aws-iso-b", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-isob\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-b-global": { + "description": "aws-iso-b global region" + }, + "us-isob-east-1": { + "description": "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + "description": "US ISOB West" + } + } + }, + { + "id": "aws-iso-e", + "outputs": { + "dnsSuffix": "cloud.adc-e.uk", + "dualStackDnsSuffix": "api.cloud-aws.adc-e.uk", + "implicitGlobalRegion": "eu-isoe-west-1", + "name": "aws-iso-e", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^eu\\-isoe\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-e-global": { + "description": "aws-iso-e global region" + }, + "eu-isoe-west-1": { + "description": "EU ISOE West" + } + } + }, + { + "id": "aws-iso-f", + "outputs": { + "dnsSuffix": "csp.hci.ic.gov", + "dualStackDnsSuffix": "api.aws.hci.ic.gov", + "implicitGlobalRegion": "us-isof-south-1", + "name": "aws-iso-f", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-isof\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-f-global": { + "description": "aws-iso-f global region" + }, + "us-isof-east-1": { + "description": "US ISOF EAST" + }, + "us-isof-south-1": { + "description": "US ISOF SOUTH" + } + } + }, + { + "id": "aws-us-gov", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "implicitGlobalRegion": "us-gov-west-1", + "name": "aws-us-gov", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-gov\\-\\w+\\-\\d+$", + "regions": { + "aws-us-gov-global": { + "description": "aws-us-gov global region" + }, + "us-gov-east-1": { + "description": "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + "description": "AWS GovCloud (US-West)" + } + } + } + ], + "version": "1.1" +}; + +let selectedPartitionsInfo = partitionsInfo; +let selectedUserAgentPrefix = ""; +const partition = (value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition of partitions) { + const { regions, outputs } = partition; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData, + }; + } + } + } + for (const partition of partitions) { + const { regionRegex, outputs } = partition; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs, + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex," + + " and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs, + }; +}; +const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}; +const useDefaultPartitionInfo = () => { + setPartitionInfo(partitionsInfo, ""); +}; +const getUserAgentPrefix = () => selectedUserAgentPrefix; + +const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.mode === "string") { + switch (retryStrategy.mode) { + case RETRY_MODES.ADAPTIVE: + setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); + break; + case RETRY_MODES.STANDARD: + setFeature(context, "RETRY_MODE_STANDARD", "E"); + break; + } + } + } + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + setFeature(context, key, value); + } + } +} + +const USER_AGENT = "user-agent"; +const X_AMZ_USER_AGENT = "x-amz-user-agent"; +const SPACE = " "; +const UA_NAME_SEPARATOR = "/"; +const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; +const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; +const UA_ESCAPE_CHAR = "-"; + +const BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; + } + else { + buffer += val; + } + continue; + } + break; + } + return buffer; +} + +const userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); + } + const prefix = getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []) + .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) + .join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent, + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] + ? `${headers[USER_AGENT]} ${normalUAValue}` + : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; + } + else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request, + }); +}; +const escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0] + .split(UA_NAME_SEPARATOR) + .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)) + .join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version] + .filter((item) => item && item.length > 0) + .reduce((acc, item, index) => { + switch (index) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); +}; +const getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true, +}; +const getUserAgentPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, +}); + +const getRuntimeUserAgentPair = () => { + const runtimesToCheck = ["deno", "bun", "llrt"]; + for (const runtime of runtimesToCheck) { + if (versions[runtime]) { + return [`md/${runtime}`, versions[runtime]]; + } + } + return ["md/nodejs", versions.node]; +}; + +const crtAvailability = { + isCrtAvailable: false, +}; + +const isCrtAvailable = () => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}; + +const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => { + const runtimeUserAgentPair = getRuntimeUserAgentPair(); + return async (config) => { + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${platform()}`, release()], + ["lang/js"], + runtimeUserAgentPair, + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); + } + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${env.AWS_EXECUTION_ENV}`]); + } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; +}; +const defaultUserAgent = createDefaultUserAgentProvider; + +const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +const UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +const NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME], + configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], + default: DEFAULT_UA_APP_ID, +}; + +const createUserAgentStringParsingProvider = ({ serviceId, clientVersion }) => async (config) => { + const module = __webpack_require__(97458); + const parse = module.parse ?? module.default.parse ?? (() => ""); + const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? parse(window.navigator.userAgent) : undefined; + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${parsedUA?.os?.name || "other"}`, parsedUA?.os?.version], + ["lang/js"], + ["md/browser", `${parsedUA?.browser?.name ?? "unknown"}_${parsedUA?.browser?.version ?? "unknown"}`], + ]; + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + const appId = await config?.userAgentAppId?.(); + if (appId) { + sections.push([`app/${appId}`]); + } + return sections; +}; + +const fallback = { + os(ua) { + if (/iPhone|iPad|iPod/.test(ua)) + return "iOS"; + if (/Macintosh|Mac OS X/.test(ua)) + return "macOS"; + if (/Windows NT/.test(ua)) + return "Windows"; + if (/Android/.test(ua)) + return "Android"; + if (/Linux/.test(ua)) + return "Linux"; + return undefined; + }, + browser(ua) { + if (/EdgiOS|EdgA|Edg\//.test(ua)) + return "Microsoft Edge"; + if (/Firefox\//.test(ua)) + return "Firefox"; + if (/Chrome\//.test(ua)) + return "Chrome"; + if (/Safari\//.test(ua)) + return "Safari"; + return undefined; + }, +}; + +const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; + } + if (!isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (isIpAddress(value)) { + return false; + } + return true; +}; + +const ARN_DELIMITER = ":"; +const RESOURCE_DELIMITER = "/"; +const parseArn = (value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) + return null; + const [arn, partition, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition, + service, + region, + accountId, + resourceId, + }; +}; + +const awsEndpointFunctions = { + isVirtualHostableS3Bucket: isVirtualHostableS3Bucket, + parseArn: parseArn, + partition: partition, +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +const resolveDefaultAwsRegionalEndpointsConfig = (input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); + } + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + return toEndpointV1(input.endpointProvider({ + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" + ? await input.useDualstackEndpoint() + : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: undefined, + }, { logger: input.logger })); + }; + } + return input; +}; +const toEndpointV1 = (endpoint) => parseUrl(endpoint.url); + +function stsRegionDefaultResolver(loaderConfig = {}) { + return loadConfig({ + ...NODE_REGION_CONFIG_OPTIONS, + async default() { + if (!warning.silence) { + console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); + } + return "us-east-1"; + }, + }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); +} +const warning = { + silence: false, +}; + +const getAwsRegionExtensionConfiguration = (runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + }, + }; +}; +const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region(), + }; +}; + +exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; +exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS; +exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; +exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; +exports.awsEndpointFunctions = awsEndpointFunctions; +exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider; +exports.createUserAgentStringParsingProvider = createUserAgentStringParsingProvider; +exports.crtAvailability = crtAvailability; +exports.defaultUserAgent = defaultUserAgent; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.fallback = fallback; +exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration; +exports.getHostHeaderPlugin = getHostHeaderPlugin; +exports.getLoggerPlugin = getLoggerPlugin; +exports.getLongPollPlugin = getLongPollPlugin; +exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin; +exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; +exports.getUserAgentPlugin = getUserAgentPlugin; +exports.getUserAgentPrefix = getUserAgentPrefix; +exports.hostHeaderMiddleware = hostHeaderMiddleware; +exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; +exports.isVirtualHostableS3Bucket = isVirtualHostableS3Bucket; +exports.loggerMiddleware = loggerMiddleware; +exports.loggerMiddlewareOptions = loggerMiddlewareOptions; +exports.parseArn = parseArn; +exports.partition = partition; +exports.recursionDetectionMiddleware = recursionDetectionMiddleware; +exports.recursionDetectionMiddlewareOptions = recursionDetectionMiddlewareOptions; +exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration; +exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; +exports.resolveHostHeaderConfig = resolveHostHeaderConfig; +exports.resolveUserAgentConfig = resolveUserAgentConfig; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setPartitionInfo = setPartitionInfo; +exports.setTokenFeature = setTokenFeature; +exports.state = state; +exports.stsRegionDefaultResolver = stsRegionDefaultResolver; +exports.stsRegionWarning = warning; +exports.toEndpointV1 = toEndpointV1; +exports.useDefaultPartitionInfo = useDefaultPartitionInfo; +exports.userAgentMiddleware = userAgentMiddleware; + + +/***/ }), + +/***/ 17727: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { ProviderError, booleanSelector, SelectorType, loadConfig } = __webpack_require__(48132); +const { setCredentialFeature } = __webpack_require__(82172); +const { normalizeProvider, memoizeIdentityProvider, isIdentityExpired, doesIdentityRequireRefresh } = __webpack_require__(89273); +const { SignatureV4 } = __webpack_require__(10262); +const { HttpResponse, HttpRequest } = __webpack_require__(37015); + +const getDateHeader = (response) => HttpResponse.isInstance(response) ? (response.headers?.date ?? response.headers?.Date) : undefined; +const getAgeHeader = (response) => HttpResponse.isInstance(response) ? (response.headers?.age ?? response.headers?.Age) : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset, timeRequestSent, ageHeader) => { + if (ageHeader !== undefined) { + return currentSystemClockOffset; + } + const serverTime = Date.parse(clockTime); + const timeResponseReceived = Date.now(); + if (timeRequestSent !== undefined && timeResponseReceived - timeRequestSent > 900_000) { + return currentSystemClockOffset; + } + const candidateSkew = timeRequestSent !== undefined + ? serverTime - (timeRequestSent + timeResponseReceived) / 2 + : serverTime - timeResponseReceived; + return candidateSkew; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const noSkewCorrection = (await config.disableClockSkewCorrection?.()) === true; + signingProperties._disableClockSkewCorrection = noSkewCorrection; + if (!noSkewCorrection) { + signingProperties._preRequestSystemClockOffset = config.systemClockOffset; + signingProperties._requestSentAt = Date.now(); + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: noSkewCorrection ? new Date() : getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const errorException = error; + if (!signingProperties._disableClockSkewCorrection) { + const serverTime = errorException.ServerTime ?? getDateHeader(errorException.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const preRequestOffset = signingProperties._preRequestSystemClockOffset; + const timeRequestSent = signingProperties._requestSentAt; + const ageHeader = getAgeHeader(errorException.$response); + const newOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset, timeRequestSent, ageHeader); + config.systemClockOffset = newOffset; + const skewExceedsThreshold = Math.abs(newOffset) >= 240_000; + const isLocalCorrection = newOffset !== preRequestOffset; + const isConcurrentCorrection = preRequestOffset !== undefined && preRequestOffset !== newOffset; + if (skewExceedsThreshold && (isLocalCorrection || isConcurrentCorrection) && errorException.$metadata) { + errorException.$metadata.clockSkewCorrected = true; + } + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + if (signingProperties._disableClockSkewCorrection) { + return; + } + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + const timeRequestSent = signingProperties._requestSentAt; + const ageHeader = getAgeHeader(httpResponse); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset, timeRequestSent, ageHeader); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const noSkewCorrection = (await config.disableClockSkewCorrection?.()) === true; + signingProperties._disableClockSkewCorrection = noSkewCorrection; + if (!noSkewCorrection) { + signingProperties._preRequestSystemClockOffset = config.systemClockOffset; + signingProperties._requestSentAt = Date.now(); + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: noSkewCorrection ? new Date() : getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const bindResolveAwsSdkSigV4Config = (defaultDisableClockSkewCorrection) => (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null; + resolvedCredentials = async (options) => { + const creds = await boundProvider(options); + const attributedCreds = creds; + if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) { + return setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e"); + } + return attributedCreds; + }; + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + disableClockSkewCorrection: normalizeProvider(config.disableClockSkewCorrection ?? defaultDisableClockSkewCorrection), + }); + return resolvedConfig; +}; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +const ENV_DISABLE_CLOCK_SKEW_CORRECTION = "AWS_DISABLE_CLOCK_SKEW_CORRECTION"; +const CONFIG_DISABLE_CLOCK_SKEW_CORRECTION = "disable_clock_skew_correction"; +const NODE_DISABLE_CLOCK_SKEW_CORRECTION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_DISABLE_CLOCK_SKEW_CORRECTION, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_DISABLE_CLOCK_SKEW_CORRECTION, SelectorType.CONFIG), + default: false, +}; + +const DEFAULT_DISABLE_CLOCK_SKEW_CORRECTION = loadConfig(NODE_DISABLE_CLOCK_SKEW_CORRECTION_CONFIG_OPTIONS); + +const resolveAwsSdkSigV4Config = bindResolveAwsSdkSigV4Config(DEFAULT_DISABLE_CLOCK_SKEW_CORRECTION); +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.validateSigningProperties = validateSigningProperties; + + +/***/ }), + +/***/ 37828: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { SmithyRpcV2CborProtocol, loadSmithyRpcV2CborErrorCode } = __webpack_require__(76798); +const { TypeRegistry, NormalizedSchema, deref } = __webpack_require__(31829); +const { decorateServiceException, getValueFromTextNode } = __webpack_require__(40417); +const { collectBody, determineTimestampFormat, RpcProtocol, HttpBindingProtocol, HttpInterceptingShapeSerializer, HttpInterceptingShapeDeserializer, FromStringShapeDeserializer, extendedEncodeURIComponent } = __webpack_require__(37015); +const { NumericValue, toUtf8, fromBase64, LazyJsonString, parseEpochTimestamp, parseRfc7231DateTime, parseRfc3339DateTimeWithOffset, generateIdempotencyToken, toBase64, dateToUtcString, expectUnion } = __webpack_require__(26591); +const { parseXML, XmlNode, XmlText } = __webpack_require__(46158); + +class ProtocolLib { + queryCompat; + errorRegistry; + constructor(queryCompat = false) { + this.queryCompat = queryCompat; + } + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } + else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } + else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } + else { + return defaultContentType; + } + } + else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server", + }; + if (!this.errorRegistry) { + throw new Error("@aws-sdk/core/protocols - error handler not initialized."); + } + try { + const errorSchema = getErrorSchema?.(this.errorRegistry, errorName) ?? + this.errorRegistry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } + catch (e) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = this.errorRegistry; + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); + } + const d = dataObject; + const message = d?.message ?? d?.Message ?? d?.Error?.Message ?? d?.Error?.message; + throw this.decorateServiceException(Object.assign(new Error(message), { + name: errorName, + }, errorMetadata), dataObject); + } + } + compose(composite, errorIdentifier, defaultNamespace) { + let namespace = defaultNamespace; + if (errorIdentifier.includes("#")) { + [namespace] = errorIdentifier.split("#"); + } + const staticRegistry = TypeRegistry.for(namespace); + const defaultSyntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + defaultNamespace); + composite.copyFrom(staticRegistry); + composite.copyFrom(defaultSyntheticRegistry); + this.errorRegistry = composite; + } + decorateServiceException(exception, additions = {}) { + if (this.queryCompat) { + const msg = exception.Message ?? additions.Message; + const error = decorateServiceException(exception, additions); + if (msg) { + error.message = msg; + } + const errorObj = error.Error ?? {}; + errorObj.Type = error.Error?.Type; + errorObj.Code = error.Error?.Code; + errorObj.Message = error.Error?.message ?? error.Error?.Message ?? msg; + error.Error = errorObj; + const reqId = error.$metadata.requestId; + if (reqId) { + error.RequestId = reqId; + } + return error; + } + return decorateServiceException(exception, additions); + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== undefined && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const keys = Object.keys(output); + const Error = { + Code, + Type, + }; + output.Code = Code; + output.Type = Type; + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + Error[k === "message" ? "Message" : k] = output[k]; + } + delete Error.__type; + output.Error = Error; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } + findQueryCompatibleError(registry, errorName) { + try { + return registry.getSchema(errorName); + } + catch (e) { + return registry.find((schema) => NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName); + } + } +} + +class AwsSmithyRpcV2CborProtocol extends SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin; + constructor({ defaultNamespace, errorTypeRegistries, awsQueryCompatible, }) { + super({ defaultNamespace, errorTypeRegistries }); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = (() => { + const compatHeader = response.headers["x-amzn-query-error"]; + if (compatHeader && this.awsQueryCompatible) { + return compatHeader.split(";")[0]; + } + return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + })(); + this.mixin.compose(this.compositeErrorRegistry, errorName, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = {}; + for (const [name, member] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class UnionSerde { + from; + to; + keys; + constructor(from, to) { + this.from = from; + this.to = to; + const keys = Object.keys(this.from); + const set = new Set(keys); + set.delete("__type"); + this.keys = set; + } + mark(key) { + this.keys.delete(key); + } + hasUnknown() { + return this.keys.size === 1 && Object.keys(this.to).length === 0; + } + writeUnknown() { + if (this.hasUnknown()) { + const k = this.keys.values().next().value; + const v = this.from[k]; + this.to.$unknown = [k, v]; + } + } +} + +let canParseBuffer; +function detectBufferParsing() { + if (canParseBuffer === undefined) { + try { + if (typeof Buffer !== "function") { + canParseBuffer = false; + } + else { + const result = JSON.parse(Buffer.from([0x7b, 0x7d])); + canParseBuffer = result !== null && typeof result === "object"; + } + } + catch { + canParseBuffer = false; + } + } + return canParseBuffer; +} + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + const inSafeRange = value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER; + if (inSafeRange) { + if (isRepresentable(numericString, value)) { + return value; + } + return new NumericValue(numericString, "bigDecimal"); + } + else { + if (isFractionalBigNumeric(numericString)) { + return new NumericValue(numericString, "bigDecimal"); + } + if (/[eE]/.test(numericString)) { + return expandExponentToBigInt(numericString); + } + return BigInt(numericString); + } + } + } + return value; +} +function isFractionalBigNumeric(s) { + const dotIndex = s.indexOf("."); + if (dotIndex === -1) { + return false; + } + const eIndex = s.search(/[eE]/); + if (eIndex === -1) { + return true; + } + const fracDigits = eIndex - dotIndex - 1; + const exp = parseInt(s.slice(eIndex + 1), 10); + return exp < fracDigits; +} +function isRepresentable(numericString, value) { + if (numericString === String(value)) { + return true; + } + if (Object.is(value, -0)) { + return true; + } + if (/[eE]/.test(numericString)) { + return expandToDecimal(numericString) === expandToDecimal(String(value)); + } + const normalized = numericString.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + const canonical = String(value); + if (normalized === canonical) { + return true; + } + if (/[eE]/.test(canonical)) { + return normalized === expandToDecimal(canonical); + } + return false; +} +function expandToDecimal(s) { + const negative = s.startsWith("-"); + const abs = negative ? s.slice(1) : s; + const eIndex = abs.search(/[eE]/); + let result; + if (eIndex === -1) { + result = abs; + } + else { + const exp = parseInt(abs.slice(eIndex + 1), 10); + const mantissa = abs.slice(0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let intLen; + if (dotIndex === -1) { + digits = mantissa; + intLen = mantissa.length; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + intLen = dotIndex; + } + digits = digits.replace(/0+$/, "") || "0"; + const newDotPos = intLen + exp; + if (digits === "0") { + result = "0"; + } + else if (newDotPos <= 0) { + result = "0." + "0".repeat(-newDotPos) + digits; + } + else if (newDotPos >= digits.length) { + result = digits + "0".repeat(newDotPos - digits.length); + } + else { + result = digits.slice(0, newDotPos) + "." + digits.slice(newDotPos); + } + } + if (result.includes(".")) { + result = result.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + } + return (negative ? "-" : "") + result; +} +function expandExponentToBigInt(s) { + const eIndex = s.search(/[eE]/); + const exp = parseInt(s.slice(eIndex + 1), 10); + const negative = s.startsWith("-"); + const mantissa = s.slice(negative ? 1 : 0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let shift; + if (dotIndex === -1) { + digits = mantissa; + shift = exp; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + const fracDigits = mantissa.length - dotIndex - 1; + shift = exp - fracDigits; + } + digits = digits.replace(/0+$/, "") || "0"; + const result = BigInt(digits) * 10n ** BigInt(shift + (mantissa.replace(".", "").length - digits.length)); + return negative ? -result : result; +} + +const REVIVER_SYMBOL = Symbol.for("@aws-sdk/reviver"); +function needsReviver(schema) { + const ns = NormalizedSchema.of(schema); + const raw = ns.getSchema(); + if (Array.isArray(raw) && ns.isStructSchema()) { + if (REVIVER_SYMBOL in raw) { + return raw[REVIVER_SYMBOL]; + } + const result = _check(ns, new Set()); + raw[REVIVER_SYMBOL] = result; + return result; + } + return _check(ns, new Set()); +} +function _check(ns, seen) { + const raw = ns.getSchema(); + if (seen.has(raw)) { + return false; + } + seen.add(raw); + if (ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + return true; + } + if (ns.isStructSchema()) { + for (const [, memberSchema] of ns.structIterator()) { + if (_check(memberSchema, seen)) { + return true; + } + } + } + else if (ns.isListSchema() || ns.isMapSchema()) { + if (_check(ns.getValueSchema(), seen)) { + return true; + } + } + else if (ns.isDocumentSchema()) { + return true; + } + return false; +} + +const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? toUtf8)(body)); + +async function parseJsonBody(streamBody, context, schema) { + let parsingInput; + if (detectBufferParsing() && typeof streamBody?.[Symbol.asyncIterator] === "function") { + const buffer = await collectBody(streamBody, context); + if (typeof Buffer === "function") { + if (Buffer.isBuffer(buffer)) { + parsingInput = buffer; + } + else { + parsingInput = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + } + } + if (!parsingInput) { + parsingInput = await collectBodyString(streamBody, context); + } + if (parsingInput.length === 0) { + return {}; + } + const reviver = schema && needsReviver(schema) ? jsonReviver : undefined; + try { + return JSON.parse(parsingInput, reviver); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: typeof parsingInput === "string" ? parsingInput : parsingInput.toString("utf8"), + }); + } + throw e; + } +} +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); +const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; +}; +const loadRestJsonErrorCode = (output, data) => { + return loadErrorCode(output, data, ["header", "code", "type"]); +}; +const loadJsonRpcErrorCode = (output, data, queryCompat = false) => { + return loadErrorCode(output, data, queryCompat ? ["code", "header", "type"] : ["type", "code", "header"]); +}; +const loadErrorCode = ({ headers }, data, order) => { + while (order.length > 0) { + const location = order.shift(); + switch (location) { + case "header": + const headerKey = findKey(headers ?? {}, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(headers[headerKey]); + } + break; + case "code": + const codeKey = findKey(data ?? {}, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + break; + case "type": + if (data?.__type !== undefined) { + return sanitizeErrorCode(data.__type); + } + break; + } + } +}; + +function writeKey(obj) { + Object.defineProperty(obj, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true }); +} + +class JsonShapeDeserializer2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + let parsed; + if (typeof data === "string") { + if (data.length === 0) { + return {}; + } + parsed = JSON.parse(data, reviver); + } + else if (data instanceof Uint8Array && detectBufferParsing()) { + if (data.byteLength === 0) { + return {}; + } + const buf = Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + parsed = JSON.parse(buf, reviver); + } + else { + parsed = await parseJsonBody(data, this.serdeContext, schema); + } + return this._read(schema, parsed); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + return this._readStruct(ns, value); + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + if (this.needsTransform(listMember)) { + for (let i = 0; i < value.length; ++i) { + value[i] = this._read(listMember, value[i]); + } + } + return value; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const map = value; + if (this.needsTransform(mapMember)) { + for (const k in map) { + if (k === "__proto__") { + writeKey(map); + } + map[k] = this._read(mapMember, map[k]); + } + } + return map; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (!(v instanceof NumericValue)) { + value[i] = this._read(ns, v); + } + } + } + else { + const doc = value; + for (const k in doc) { + if (k === "__proto__") { + writeKey(doc); + } + const v = doc[k]; + if (!(v instanceof NumericValue)) { + doc[k] = this._read(ns, v); + } + } + } + } + } + return value; + } + _readStruct(ns, record) { + const union = ns.isUnionSchema(); + const out = {}; + let nameMap; + const hasType = typeof record.__type === "string"; + const { jsonName } = this.settings; + if (jsonName && hasType) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + if (hasType) { + nameMap[fromKey] = memberName; + } + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (hasType) { + for (const k in record) { + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + needsTransform(ns) { + if (ns.isBlobSchema() || ns.isTimestampSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + return true; + } + if (ns.isDocumentSchema() || ns.isStructSchema() || ns.isListSchema() || ns.isMapSchema()) { + return true; + } + if (ns.isStringSchema() && ns.getMergedTraits().mediaType) { + return true; + } + return false; + } +} + +class JsonBytesStringAdapter extends Uint8Array { + string = null; + static allocUnsafe(bytes) { + if (typeof Buffer === "function") { + const buffer = Buffer.allocUnsafe(bytes); + return new JsonBytesStringAdapter(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + return new JsonBytesStringAdapter(bytes); + } + toString() { + return this.s(); + } + valueOf() { + return this.s(); + } + includes(searchString, position) { + if (typeof searchString === "string") { + return this.s().includes(searchString, position); + } + return Uint8Array.prototype.includes.call(this, searchString, position); + } + indexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().indexOf(searchString, position); + } + return Uint8Array.prototype.indexOf.call(this, searchString, position); + } + lastIndexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().lastIndexOf(searchString, position); + } + const fn = Uint8Array.prototype.lastIndexOf; + if (position !== undefined) { + return fn.call(this, searchString, position); + } + return fn.call(this, searchString); + } + startsWith(searchString, position) { + return this.s().startsWith(searchString, position); + } + endsWith(searchString, endPosition) { + return this.s().endsWith(searchString, endPosition); + } + match(regexp) { + return this.s().match(regexp); + } + replace(searchValue, replaceValue) { + return this.s().replace(searchValue, replaceValue); + } + search(regexp) { + return this.s().search(regexp); + } + split(separator, limit) { + return this.s().split(separator, limit); + } + substring(start, end) { + return this.s().substring(start, end); + } + trim() { + return this.s().trim(); + } + trimStart() { + return this.s().trimStart(); + } + trimEnd() { + return this.s().trimEnd(); + } + charAt(pos) { + return this.s().charAt(pos); + } + charCodeAt(index) { + return this.s().charCodeAt(index); + } + padStart(maxLength, fillString) { + return this.s().padStart(maxLength, fillString); + } + padEnd(maxLength, fillString) { + return this.s().padEnd(maxLength, fillString); + } + repeat(count) { + return this.s().repeat(count); + } + toUpperCase() { + return this.s().toUpperCase(); + } + toLowerCase() { + return this.s().toLowerCase(); + } + s() { + if (this.string == null) { + const n = Date.now(); + if (n > warned + 60_000) { + console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. " + + "It has been automatically converted to string. In a future version this will throw an error."); + warned = n; + } + this.string = toUtf8(this); + } + return this.string; + } +} +var warned = 0; + +const encoder = new TextEncoder(); +const OPEN_BRACE = 0x7b; +const CLOSE_BRACE = 0x7d; +const OPEN_BRACKET = 0x5b; +const CLOSE_BRACKET = 0x5d; +const QUOTE = 0x22; +const COLON = 0x3a; +const COMMA = 0x2c; +const BACKSLASH = 0x5c; +const TRUE = new Uint8Array([0x74, 0x72, 0x75, 0x65]); +const FALSE = new Uint8Array([0x66, 0x61, 0x6c, 0x73, 0x65]); +const NULL = new Uint8Array([0x6e, 0x75, 0x6c, 0x6c]); +const ESCAPE_TABLE = new Array(128).fill(null); +ESCAPE_TABLE[0x08] = "b"; +ESCAPE_TABLE[0x09] = "t"; +ESCAPE_TABLE[0x0a] = "n"; +ESCAPE_TABLE[0x0c] = "f"; +ESCAPE_TABLE[0x0d] = "r"; +ESCAPE_TABLE[0x22] = '"'; +ESCAPE_TABLE[0x5c] = "\\"; +for (let i = 0; i < 0x20; i++) { + if (ESCAPE_TABLE[i] === null) { + ESCAPE_TABLE[i] = "u00" + i.toString(16).padStart(2, "0"); + } +} +const INITIAL_BUFFER_SIZE = 2048; +function alloc(size) { + return JsonBytesStringAdapter.allocUnsafe(size); +} +class JsonShapeSerializer2 extends SerdeContextConfig { + settings; + json; + i = 0; + rootSchema; + rawValue; + passthrough = false; + constructor(settings) { + super(); + this.settings = settings; + this.json = alloc(INITIAL_BUFFER_SIZE); + } + write(schema, value) { + this.i = 0; + this.rawValue = value; + this.rootSchema = NormalizedSchema.of(schema); + this.passthrough = this.rootSchema.isBlobSchema() || this.rootSchema.isStringSchema(); + if (!this.passthrough) { + this.writeValue(this.rootSchema, value, undefined); + } + } + writeDiscriminatedDocument(schema, value) { + this.i = 0; + this.rootSchema = NormalizedSchema.of(schema); + const ns = this.rootSchema; + if (ns.isStructSchema() && value != null && typeof value === "object") { + this.writeValue(ns, value, undefined); + const prefix = `"__type":"${ns.getName(true) ?? "Unknown"}",`; + const z = prefix.length; + this.ensure(z); + this.json.copyWithin(1 + z, 1, this.i); + encoder.encodeInto(prefix, this.json.subarray(1)); + this.i += z; + } + else { + this.writeValue(ns, value, undefined); + } + } + flush() { + this.rootSchema = undefined; + const finalPosition = this.i; + this.i = 0; + const raw = this.rawValue; + this.rawValue = undefined; + if (finalPosition === 0) { + return raw; + } + const result = this.json.subarray(0, finalPosition); + this.json = alloc(INITIAL_BUFFER_SIZE); + return result; + } + ensure(byteCount) { + const { i, json } = this; + if (i + byteCount > json.length) { + let newSize = json.length * 2; + while (newSize < i + byteCount) { + newSize *= 2; + } + const next = alloc(newSize); + next.set(this.json); + this.json = next; + } + } + writeAscii(s) { + const z = s.length; + this.ensure(z); + let { i, json } = this; + for (let j = 0; j < z; ++j) { + json[i] = s.charCodeAt(j); + i += 1; + } + this.i = i; + } + writeAsciiQuoted(s) { + const z = s.length; + this.ensure(z + 4); + let { json, i } = this; + json[i++] = QUOTE; + for (let j = 0; j < z; ++j) { + json[i++] = s.charCodeAt(j); + } + json[i++] = QUOTE; + this.i = i; + } + writeJsonString(s) { + this.ensure(s.length * 3 + 2); + this.json[this.i++] = QUOTE; + const z = s.length; + for (let j = 0; j < z; ++j) { + const c = s.charCodeAt(j); + if (c > 0x22 && c < 0x5c) { + this.json[this.i++] = c; + } + else if (c < 0x80) { + const esc = ESCAPE_TABLE[c]; + if (esc !== null) { + this.ensure(esc.length + 1); + this.json[this.i++] = BACKSLASH; + for (let k = 0; k < esc.length; k++) { + this.json[this.i++] = esc.charCodeAt(k); + } + } + else { + this.json[this.i++] = c; + } + } + else if (c >= 0xd800 && c <= 0xdbff) { + const next = j + 1 < z ? s.charCodeAt(j + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + this.ensure(4); + const { written } = encoder.encodeInto(s.substring(j, j + 2), this.json.subarray(this.i)); + this.i += written; + ++j; + } + else { + this.ensure(6); + this.writeUnicodeEscape(c); + } + } + else if (c >= 0xdc00 && c <= 0xdfff) { + this.ensure(6); + this.writeUnicodeEscape(c); + } + else { + let { i, json } = this; + if (c < 0x800) { + json[i++] = 0xc0 | (c >> 6); + json[i++] = 0x80 | (c & 0x3f); + } + else { + json[i++] = 0xe0 | (c >> 12); + json[i++] = 0x80 | ((c >> 6) & 0x3f); + json[i++] = 0x80 | (c & 0x3f); + } + this.i = i; + } + } + this.json[this.i++] = QUOTE; + } + writeUnicodeEscape(code) { + let { json, i } = this; + json[i++] = BACKSLASH; + json[i++] = 0x75; + const hex = code.toString(16).padStart(4, "0"); + for (let j = 0; j < 4; ++j) { + json[i++] = hex.charCodeAt(j); + } + this.i = i; + } + static B64 = (() => { + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const table = new Uint8Array(64); + for (let i = 0; i < 64; ++i) { + table[i] = chars.charCodeAt(i); + } + return table; + })(); + writeBase64(data) { + const b64Len = Math.ceil(data.length / 3) * 4; + this.ensure(b64Len + 2); + const json = this.json; + const B64 = JsonShapeSerializer2.B64; + let i = this.i; + json[i++] = QUOTE; + const len = data.length; + const remainder = len % 3; + const mainLen = len - remainder; + for (let j = 0; j < mainLen; j += 3) { + const a = data[j]; + const b = data[j + 1]; + const c = data[j + 2]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[((b & 0x0f) << 2) | (c >> 6)]; + json[i++] = B64[c & 0x3f]; + } + if (remainder === 2) { + const a = data[mainLen]; + const b = data[mainLen + 1]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[(b & 0x0f) << 2]; + json[i++] = 0x3d; + } + else if (remainder === 1) { + const a = data[mainLen]; + json[i++] = B64[a >> 2]; + json[i++] = B64[(a & 0x03) << 4]; + json[i++] = 0x3d; + json[i++] = 0x3d; + } + json[i++] = QUOTE; + this.i = i; + } + writeValue(schema, value, container) { + if (value == null) { + if (container?.isStructSchema()) { + if (value === undefined) { + const ns = NormalizedSchema.of(schema); + if (ns.isIdempotencyToken()) { + this.writeAsciiQuoted(generateIdempotencyToken()); + return; + } + } + return; + } + this.ensure(4); + this.json.set(NULL, this.i); + this.i += 4; + return; + } + const ns = NormalizedSchema.of(schema); + const isObject = typeof value === "object"; + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + this.writeJsonString(LazyJsonString.from(value).toString()); + return; + } + } + } + if (isObject) { + if (ns.isStructSchema()) { + this.writeStruct(ns, value); + return; + } + if (Array.isArray(value) && (ns.isListSchema() || ns.isDocumentSchema())) { + this.writeList(ns, value, ns.isDocumentSchema()); + return; + } + if (ns.isMapSchema()) { + this.writeMap(ns, value, false); + return; + } + if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { + this.writeBase64(value); + return; + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + this.writeTimestamp(ns, value); + return; + } + if (value instanceof NumericValue) { + this.writeAscii(value.string); + return; + } + if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.writeList(ns, value, true); + } + else { + this.writeMap(ns, value, true); + } + return; + } + const json = JSON.stringify(value); + this.writeAscii(json); + return; + } + if (typeof value === "string") { + if (ns.isBlobSchema()) { + const b64 = (this.serdeContext?.base64Encoder ?? toBase64)(value); + this.writeAsciiQuoted(b64); + return; + } + this.writeJsonString(value); + return; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || Number.isNaN(value)) { + this.writeAsciiQuoted(String(value)); + return; + } + const numStr = String(value); + this.writeAscii(numStr); + return; + } + if (typeof value === "boolean") { + this.ensure(5); + let { i, json } = this; + if (value) { + json.set(TRUE, i); + i += 4; + } + else { + json.set(FALSE, i); + i += 5; + } + this.i = i; + return; + } + if (typeof value === "bigint") { + this.writeAscii(value.toString()); + return; + } + this.writeAscii(String(value)); + } + writeStruct(ns, value) { + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let wroteAny = false; + const hasType = typeof value.__type === "string"; + let writtenKeys; + if (hasType) { + writtenKeys = new Set(); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const item = value[memberName]; + if (item == null && !memberSchema.isIdempotencyToken()) { + continue; + } + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + const targetKey = this.settings.jsonName ? (memberSchema.getMergedTraits().jsonName ?? memberName) : memberName; + if (writtenKeys) { + writtenKeys.add(memberName); + writtenKeys.add(targetKey); + } + this.writeAsciiQuoted(targetKey); + this.json[this.i++] = COLON; + this.writeValue(memberSchema, item, ns); + } + if (!wroteAny && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, ns); + } + } + else if (hasType) { + for (const k in value) { + if (writtenKeys.has(k)) { + continue; + } + writtenKeys.add(k); + const v = value[k]; + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, undefined); + } + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeList(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let hasSpecials = false; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity || (v == null && !sparse)) { + hasSpecials = true; + break; + } + } + let json; + if (!hasSpecials) { + json = JSON.stringify(value); + } + else { + const out = []; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (v == null && !sparse) + continue; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + out.push(String(v)); + } + else { + out.push(v); + } + } + json = JSON.stringify(out); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACKET; + let wroteFirstItem = false; + for (let i = 0; i < value.length; ++i) { + const item = value[i]; + if (isDocument ? item === undefined : item == null && !sparse) { + continue; + } + if (wroteFirstItem) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + this.writeValue(valueSchema, item, undefined); + wroteFirstItem = true; + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACKET; + } + writeMap(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let modifications; + for (const k in value) { + const v = value[k]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + (modifications ??= {})[k] = v; + value[k] = String(v); + } + else if (v === null && !sparse) { + (modifications ??= {})[k] = null; + value[k] = undefined; + } + } + const json = JSON.stringify(value); + if (modifications) { + Object.assign(value, modifications); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let first = true; + for (const k in value) { + const v = value[k]; + if (isDocument ? v === undefined : v == null && !sparse) { + continue; + } + if (!first) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + first = false; + this.writeJsonString(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(valueSchema, v, undefined); + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeTimestamp(ns, value) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: { + const iso = value.toISOString().replace(".000Z", "Z"); + this.writeAsciiQuoted(iso); + return; + } + case 6: { + this.writeAsciiQuoted(dateToUtcString(value)); + return; + } + case 7: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + default: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + } + } +} + +class JsonCodec2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer2(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer2(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsJsonRpcProtocol extends RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin; + awsQueryCompatible; + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + }); + this.serviceTarget = serviceTarget; + this.codec = + jsonCodec ?? + new JsonCodec2({ + timestampFormat: { + useTrait: true, + default: 7, + }, + jsonName: false, + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + request.headers["content-type"] = `application/x-amz-json-${this.getJsonRpcVersion()}`; + request.headers["x-amz-target"] = `${this.serviceTarget}.${operationSchema.name}`; + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const { awsQueryCompatible } = this; + if (awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadJsonRpcErrorCode(response, dataObject, awsQueryCompatible) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = errorDeserializer.readObject(member, dataObject[name]); + } + } + if (awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class AwsJson1_0Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + serviceTarget, + awsQueryCompatible, + jsonCodec, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } +} + +class AwsJson1_1Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + serviceTarget, + awsQueryCompatible, + jsonCodec, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; + } +} + +class AwsRestJsonProtocol extends HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace, errorTypeRegistries, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7, + }, + httpBindings: true, + jsonName: true, + }; + this.codec = jsonCodec ?? new JsonCodec2(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { + request.body = "{}"; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const output = await super.deserializeResponse(operationSchema, context, response); + const outputSchema = NormalizedSchema.of(operationSchema.output); + for (const [name, member] of outputSchema.structIterator()) { + if (member.getMemberTraits().httpPayload && !(name in output)) { + output[name] = null; + } + } + return output; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = errorDeserializer.readObject(member, dataObject[target]); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/json"; + } +} + +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + return this._read(schema, typeof data === "string" ? JSON.parse(data, reviver) : await parseJsonBody(data, this.serdeContext, schema)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const union = ns.isUnionSchema(); + const out = {}; + let nameMap = void 0; + const { jsonName } = this.settings; + if (jsonName) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + nameMap[fromKey] = memberName; + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (typeof record.__type === "string") { + for (const k in record) { + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(this._read(listMember, item)); + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + for (const _k in value) { + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._read(mapMember, value[_k]); + } + return out; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + if (k === "__proto__") { + writeKey(out); + } + const v = value[k]; + if (v instanceof NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} + +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + useReplacer = false; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + this.rootSchema = NormalizedSchema.of(schema); + this.buffer = this._write(this.rootSchema, value); + } + flush() { + const { rootSchema, useReplacer } = this; + this.rootSchema = undefined; + this.useReplacer = false; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + if (!useReplacer) { + return JSON.stringify(this.buffer); + } + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + writeDiscriminatedDocument(schema, value) { + this.write(schema, value); + if (typeof this.buffer === "object") { + this.buffer.__type = NormalizedSchema.of(schema).getName(true); + } + } + _write(schema, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const out = {}; + const { jsonName } = this.settings; + let nameMap = void 0; + if (jsonName) { + nameMap = {}; + } + let outCount = 0; + for (const [memberName, memberSchema] of ns.structIterator()) { + const serializableValue = this._write(memberSchema, record[memberName], ns); + if (serializableValue !== undefined) { + let targetKey = memberName; + if (jsonName) { + targetKey = memberSchema.getMergedTraits().jsonName ?? memberName; + nameMap[memberName] = targetKey; + } + out[targetKey] = serializableValue; + outCount++; + } + } + if (ns.isUnionSchema() && outCount === 0) { + const { $unknown } = record; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + if (k === "__proto__") { + writeKey(out); + } + out[k] = this._write(15, v); + } + } + else if (typeof record.__type === "string") { + for (const k in record) { + const v = record[k]; + const targetKey = jsonName ? (nameMap[k] ?? k) : k; + if (!(targetKey in out)) { + out[targetKey] = this._write(15, v); + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const _k in value) { + const _v = value[_k]; + if (sparse || _v != null) { + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + if (value instanceof Uint8Array && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (value instanceof NumericValue) { + this.useReplacer = true; + } + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + } + return value; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + return value; + } + if (typeof value === "string" && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (typeof value === "bigint") { + this.useReplacer = true; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (value instanceof Uint8Array) { + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + const v = value[k]; + if (k === "__proto__") { + writeKey(out); + } + if (v instanceof NumericValue) { + this.useReplacer = true; + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class XmlShapeDeserializer extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema, bytes, key) { + const ns = NormalizedSchema.of(schema); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && + ns.isMemberSchema() && + !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } + else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + if (source == null) { + return buffer; + } + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + buffer.push(this.readSchema(listValue, v)); + } + return buffer; + } + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } + else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value = entry[valueProperty]; + if (key === "__proto__") { + writeKey(buffer); + } + buffer[key] = this.readSchema(memberNs, value); + } + return buffer; + } + if (ns.isStructSchema()) { + const union = ns.isUnionSchema(); + let unionSerde; + if (union) { + unionSerde = new UnionSerde(value, buffer); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload + ? (memberSchema.getMemberTraits().xmlName ?? memberName) + : (memberTraits.xmlName ?? memberSchema.getName()); + if (union) { + unionSerde.mark(xmlObjectKey); + } + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + let parsedObj; + try { + parsedObj = parseXML(xml); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return getValueFromTextNode(parsedObjToReturn); + } + return {}; + } +} + +class QueryShapeSerializer extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value, prefix = "") { + if (this.buffer === undefined) { + this.buffer = ""; + } + const ns = NormalizedSchema.of(schema); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? toBase64)(value)); + } + } + else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue(generateIdempotencyToken()); + } + } + else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof NumericValue ? value.string : String(value)); + } + } + else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue(dateToUtcString(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1000)); + break; + } + } + } + else if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.write(64 | 15, value, prefix); + } + else if (value instanceof Date) { + this.write(4, value, prefix); + } + else if (value instanceof Uint8Array) { + this.write(21, value, prefix); + } + else if (value && typeof value === "object") { + this.write(128 | 15, value, prefix); + } + else { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } + else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const traits = member.getMergedTraits(); + const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } + else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const k in value) { + const v = value[k]; + if (v == null) { + continue; + } + const keyTraits = keySchema.getMergedTraits(); + const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valTraits = memberSchema.getMergedTraits(); + const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } + else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + let didWriteMember = false; + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const traits = member.getMergedTraits(); + const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct"); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + didWriteMember = true; + } + if (!didWriteMember && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + const key = `${prefix}${k}`; + this.write(15, v, key); + } + } + } + } + else if (ns.isUnitSchema()) ; + else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } + } + flush() { + if (this.buffer === undefined) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; + } + getKey(memberName, xmlName, ec2QueryName, keySource) { + const { ec2, capitalizeKeys } = this.settings; + if (ec2 && ec2QueryName) { + return ec2QueryName; + } + const key = xmlName ?? memberName; + if (capitalizeKeys && keySource === "struct") { + return key[0].toUpperCase() + key.slice(1); + } + return key; + } + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${extendedEncodeURIComponent(key)}=`; + } + writeValue(value) { + this.buffer += extendedEncodeURIComponent(value); + } +} + +class AwsQueryProtocol extends RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + errorTypeRegistries: options.errorTypeRegistries, + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true, + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); + } + getShapeId() { + return "aws.protocols#awsQuery"; + } + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + } + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + request.headers["content-type"] = "application/x-www-form-urlencoded"; + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + useNestedResult() { + return true; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const errorData = this.loadQueryError(dataObject) ?? {}; + const message = this.loadQueryErrorMessage(dataObject); + errorData.message = message; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message, + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError); + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = { + Type: errorData.Error.Type, + Code: errorData.Error.Code, + Error: errorData.Error, + }; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== undefined) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } +} + +class AwsEc2QueryProtocol extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + ec2: true, + }; + Object.assign(this.serializer.settings, ec2Settings); + } + getShapeId() { + return "aws.protocols#ec2Query"; + } + useNestedResult() { + return false; + } +} + +const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = parseXML(encoded); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return getValueFromTextNode(parsedObjToReturn); + } + return {}; +}); +const parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; +}; +const loadRestXmlErrorCode = (output, data) => { + if (data?.Error?.Code !== undefined) { + return data.Error.Code; + } + if (data?.Code !== undefined) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}; + +class XmlShapeSerializer extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } + else if (ns.isBlobSchema()) { + this.byteBuffer = + "byteLength" in value + ? value + : (this.serdeContext?.base64Decoder ?? fromBase64)(value); + } + else { + this.buffer = this.writeStruct(ns, value, undefined); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== undefined) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== undefined) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload + ? (ns.getMemberTraits().xmlName ?? ns.getMemberName()) + : (traits.xmlName ?? ns.getName()); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } + else { + const memberNode = XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + const { $unknown } = value; + if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { + const [k, v] = $unknown; + const node = XmlNode.of(k); + if (typeof v !== "string") { + if (value instanceof XmlNode || value instanceof XmlText) { + structXmlNode.addChildNode(value); + } + else { + throw new Error(`@aws-sdk - $unknown union member in XML requires ` + + `value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`); + } + } + this.writeSimpleInto(0, v, node, xmlns); + structXmlNode.addChildNode(node); + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); + } + else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container, xmlns); + } + else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container.addChildNode(struct.withName(flat ? (listTraits.xmlName ?? listMember.getMemberName()) : (listValueTraits.xmlName ?? "member"))); + } + else { + const listItemNode = XmlNode.of(flat ? (listTraits.xmlName ?? listMember.getMemberName()) : (listValueTraits.xmlName ?? "member")); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container.addChildNode(listItemNode); + } + }; + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } + else { + const listNode = XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } + else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } + else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } + else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }; + if (flat) { + for (const key in map) { + const val = map[key]; + if (sparse || val != null) { + const entry = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } + else { + let mapNode; + if (!containerIsMap) { + mapNode = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const key in map) { + const val = map[key]; + if (sparse || val != null) { + const entry = XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + else if (ns.isTimestampSchema() && value instanceof Date) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = dateToUtcString(value); + break; + case 7: + nodeContents = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = dateToUtcString(value); + break; + } + } + else if (ns.isBigDecimalSchema() && value) { + if (value instanceof NumericValue) { + return value.string; + } + return String(value); + } + else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } + else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === undefined && ns.isIdempotencyToken()) { + nodeContents = generateIdempotencyToken(); + } + else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = NormalizedSchema.of(_schema); + const content = new XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } +} + +class XmlCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsRestXmlProtocol extends HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + }; + this.codec = new XmlCodec(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (typeof request.body === "string" && + request.headers["content-type"] === this.getDefaultContentType() && + !request.body.startsWith("' + request.body; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + if (dataObject.Error && typeof dataObject.Error === "object") { + for (const key of Object.keys(dataObject.Error)) { + dataObject[key] = dataObject.Error[key]; + if (key.toLowerCase() === "message") { + dataObject.message = dataObject.Error[key]; + } + } + } + if (dataObject.RequestId && !metadata.requestId) { + metadata.requestId = dataObject.RequestId; + } + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? + dataObject.Error?.Message ?? + dataObject.message ?? + dataObject.Message ?? + "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = errorDeserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/xml"; + } + hasUnstructuredPayloadBinding(ns) { + for (const [, member] of ns.structIterator()) { + if (member.getMergedTraits().httpPayload) { + return !(member.isStructSchema() || member.isMapSchema() || member.isListSchema()); + } + } + return false; + } +} + +const awsExpectUnion = (value) => { + if (value == null) { + return undefined; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return expectUnion(value); +}; + +const _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; +}; +const _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase !== "false"; + } + return val; +}; +const _toNum = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; + } + return val; +}; + +exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; +exports.AwsJson1_0Protocol = AwsJson1_0Protocol; +exports.AwsJson1_1Protocol = AwsJson1_1Protocol; +exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; +exports.AwsQueryProtocol = AwsQueryProtocol; +exports.AwsRestJsonProtocol = AwsRestJsonProtocol; +exports.AwsRestXmlProtocol = AwsRestXmlProtocol; +exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonCodec2 = JsonCodec2; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeDeserializer2 = JsonShapeDeserializer2; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.JsonShapeSerializer2 = JsonShapeSerializer2; +exports.QueryShapeSerializer = QueryShapeSerializer; +exports.XmlCodec = XmlCodec; +exports.XmlShapeDeserializer = XmlShapeDeserializer; +exports.XmlShapeSerializer = XmlShapeSerializer; +exports._toBool = _toBool; +exports._toNum = _toNum; +exports._toStr = _toStr; +exports.awsExpectUnion = awsExpectUnion; +exports.loadJsonRpcErrorCode = loadJsonRpcErrorCode; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadRestXmlErrorCode = loadRestXmlErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.parseXmlBody = parseXmlBody; +exports.parseXmlErrorBody = parseXmlErrorBody; + + +/***/ }), + +/***/ 34699: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { buildQueryString } = __webpack_require__(37015); + +const validate = (str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6; +const parse = (arn) => { + const segments = arn.split(":"); + if (segments.length < 6 || segments[0] !== "arn") + throw new Error("Malformed ARN"); + const [, partition, service, region, accountId, ...resource] = segments; + return { + partition, + service, + region, + accountId, + resource: resource.join(":"), + }; +}; +const build = (arnObject) => { + const { partition = "aws", service, region, accountId, resource } = arnObject; + if ([service, region, accountId, resource].some((segment) => typeof segment !== "string")) { + throw new Error("Input ARN object is invalid"); + } + return `arn:${partition}:${service}:${region}:${accountId}:${resource}`; +}; + +function formatUrl(request) { + const { port, query } = request; + let { protocol, path, hostname } = request; + if (protocol && protocol.slice(-1) !== ":") { + protocol += ":"; + } + if (port) { + hostname += `:${port}`; + } + if (path && path.charAt(0) !== "/") { + path = `/${path}`; + } + let queryString = query ? buildQueryString(query) : ""; + if (queryString && queryString[0] !== "?") { + queryString = `?${queryString}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + let fragment = ""; + if (request.fragment) { + fragment = `#${request.fragment}`; + } + return `${protocol}//${auth}${hostname}${path}${queryString}${fragment}`; +} + +exports.build = build; +exports.formatUrl = formatUrl; +exports.parse = parse; +exports.validate = validate; + + +/***/ }), + +/***/ 24491: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Retry, RETRY_MODES } = __webpack_require__(26266); +const { HttpRequest, parseUrl } = __webpack_require__(62049); +const { InvokeStore } = __webpack_require__(31934); +const { normalizeProvider } = __webpack_require__(57255); +const { platform, release } = __webpack_require__(48161); +const { versions, env } = __webpack_require__(1708); +const { isValidHostLabel, isIpAddress, customEndpointFunctions } = __webpack_require__(93846); +const { EndpointError, resolveEndpoint } = __webpack_require__(93846); +exports.EndpointError = EndpointError; +exports.isIpAddress = isIpAddress; +exports.resolveEndpoint = resolveEndpoint; +const { loadConfig, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS } = __webpack_require__(68702); +const { REGION_ENV_NAME, REGION_INI_NAME, resolveRegionConfig } = __webpack_require__(68702); +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.resolveRegionConfig = resolveRegionConfig; + +const state = { + warningEmitted: false, +}; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !state.warningEmitted) { + if (process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED === "true") { + state.warningEmitted = true; + return; + } + const userMajorVersion = parseInt(version.substring(1, version.indexOf("."))); + const vv = 22; + if (userMajorVersion < vv) { + state.warningEmitted = true; + process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3) +versions published after the first week of January 2027 +will require node >=${vv}. You are running node ${version}. + +To continue receiving updates to AWS services, bug fixes, +and security updates please upgrade to node >=${vv}. + +More information can be found at: https://a.co/c895JFp`); + } + } +}; + +const longPollMiddleware = () => (next, context) => async (args) => { + context.__retryLongPoll = true; + return next(args); +}; +const longPollMiddlewareOptions = { + name: "longPollMiddleware", + tags: ["RETRY"], + step: "initialize", + override: true, +}; +const getLongPollPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(longPollMiddleware(), longPollMiddlewareOptions); + }, +}); + +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} + +Retry.v2026 ||= typeof process === "object" && process.env?.AWS_NEW_RETRIES_2026 === "true"; +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {}, + }; + } + else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} + +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} + +function resolveHostHeaderConfig(input) { + return input; +} +const hostHeaderMiddleware = (options) => (next) => async (args) => { + if (!HttpRequest.isInstance(args.request)) + return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } + else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) + host += `:${request.port}`; + request.headers["host"] = host; + } + return next(args); +}; +const hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true, +}; +const getHostHeaderPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, +}); + +const loggerMiddleware = () => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata, + }); + return response; + } + catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata, + }); + throw error; + } +}; +const loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true, +}; +const getLoggerPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, +}); + +const recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION", "TRACE_CONTEXT_PROPAGATION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low", +}; + +const AWS_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +const _X_AMZN_TRACE_ID = "_X_AMZN_TRACE_ID"; +const X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"; +const TRACEPARENT = "traceparent"; +const TRACESTATE = "tracestate"; +const BAGGAGE = "baggage"; +const recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) { + return next(args); + } + let invokeStore; + { + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === X_AMZN_TRACE_ID.toLowerCase()) ?? + X_AMZN_TRACE_ID; + if (!request.headers.hasOwnProperty(traceIdHeader)) { + const functionName = process.env[AWS_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[_X_AMZN_TRACE_ID]; + invokeStore ??= await InvokeStore.getInstanceAsync(); + const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[X_AMZN_TRACE_ID] = traceId; + } + } + } + { + sanitizeTraceHeaders(request.headers); + const existingTraceparent = request.headers[TRACEPARENT]; + if (!existingTraceparent) { + const traceparent = (invokeStore ??= await InvokeStore.getInstanceAsync())?.getTraceparent?.(); + if (traceparent) { + request.headers[TRACEPARENT] = traceparent; + const tracestate = invokeStore?.getTracestate?.(); + if (tracestate) { + request.headers[TRACESTATE] = tracestate; + } + const baggage = invokeStore?.getBaggage?.(); + if (baggage) { + request.headers[BAGGAGE] = baggage; + } + } + } + } + return next(args); +}; +function sanitizeTraceHeaders(headers) { + for (const header of Object.keys(headers)) { + const lower = header.toLowerCase(); + if (header !== lower && (lower === TRACEPARENT || lower === TRACESTATE || lower === BAGGAGE)) { + headers[lower] = headers[header]; + delete headers[header]; + } + } +} + +const getRecursionDetectionPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); + }, +}); + +const DEFAULT_UA_APP_ID = undefined; +function isValidUserAgentAppId(appId) { + if (appId === undefined) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } + else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, + }); +} + +const partitionsInfo = { + "partitions": [ + { + "id": "aws", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "implicitGlobalRegion": "us-east-1", + "name": "aws", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + "regions": { + "af-south-1": { + "description": "Africa (Cape Town)" + }, + "ap-east-1": { + "description": "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + "description": "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + "description": "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + "description": "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + "description": "Asia Pacific (Osaka)" + }, + "ap-south-1": { + "description": "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + "description": "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + "description": "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + "description": "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + "description": "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + "description": "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + "description": "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + "description": "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + "description": "Asia Pacific (Thailand)" + }, + "aws-global": { + "description": "aws global region" + }, + "ca-central-1": { + "description": "Canada (Central)" + }, + "ca-west-1": { + "description": "Canada West (Calgary)" + }, + "eu-central-1": { + "description": "Europe (Frankfurt)" + }, + "eu-central-2": { + "description": "Europe (Zurich)" + }, + "eu-north-1": { + "description": "Europe (Stockholm)" + }, + "eu-south-1": { + "description": "Europe (Milan)" + }, + "eu-south-2": { + "description": "Europe (Spain)" + }, + "eu-west-1": { + "description": "Europe (Ireland)" + }, + "eu-west-2": { + "description": "Europe (London)" + }, + "eu-west-3": { + "description": "Europe (Paris)" + }, + "il-central-1": { + "description": "Israel (Tel Aviv)" + }, + "me-central-1": { + "description": "Middle East (UAE)" + }, + "me-south-1": { + "description": "Middle East (Bahrain)" + }, + "mx-central-1": { + "description": "Mexico (Central)" + }, + "sa-east-1": { + "description": "South America (Sao Paulo)" + }, + "us-east-1": { + "description": "US East (N. Virginia)" + }, + "us-east-2": { + "description": "US East (Ohio)" + }, + "us-west-1": { + "description": "US West (N. California)" + }, + "us-west-2": { + "description": "US West (Oregon)" + } + } + }, + { + "id": "aws-cn", + "outputs": { + "dnsSuffix": "amazonaws.com.cn", + "dualStackDnsSuffix": "api.amazonwebservices.com.cn", + "implicitGlobalRegion": "cn-northwest-1", + "name": "aws-cn", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^cn\\-\\w+\\-\\d+$", + "regions": { + "aws-cn-global": { + "description": "aws-cn global region" + }, + "cn-north-1": { + "description": "China (Beijing)" + }, + "cn-northwest-1": { + "description": "China (Ningxia)" + } + } + }, + { + "id": "aws-eusc", + "outputs": { + "dnsSuffix": "amazonaws.eu", + "dualStackDnsSuffix": "api.amazonwebservices.eu", + "implicitGlobalRegion": "eusc-de-east-1", + "name": "aws-eusc", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^eusc\\-(de)\\-\\w+\\-\\d+$", + "regions": { + "eusc-de-east-1": { + "description": "AWS European Sovereign Cloud (Germany)" + } + } + }, + { + "id": "aws-iso", + "outputs": { + "dnsSuffix": "c2s.ic.gov", + "dualStackDnsSuffix": "api.aws.ic.gov", + "implicitGlobalRegion": "us-iso-east-1", + "name": "aws-iso", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-iso\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-global": { + "description": "aws-iso global region" + }, + "us-iso-east-1": { + "description": "US ISO East" + }, + "us-iso-west-1": { + "description": "US ISO WEST" + } + } + }, + { + "id": "aws-iso-b", + "outputs": { + "dnsSuffix": "sc2s.sgov.gov", + "dualStackDnsSuffix": "api.aws.scloud", + "implicitGlobalRegion": "us-isob-east-1", + "name": "aws-iso-b", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-isob\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-b-global": { + "description": "aws-iso-b global region" + }, + "us-isob-east-1": { + "description": "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + "description": "US ISOB West" + } + } + }, + { + "id": "aws-iso-e", + "outputs": { + "dnsSuffix": "cloud.adc-e.uk", + "dualStackDnsSuffix": "api.cloud-aws.adc-e.uk", + "implicitGlobalRegion": "eu-isoe-west-1", + "name": "aws-iso-e", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^eu\\-isoe\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-e-global": { + "description": "aws-iso-e global region" + }, + "eu-isoe-west-1": { + "description": "EU ISOE West" + } + } + }, + { + "id": "aws-iso-f", + "outputs": { + "dnsSuffix": "csp.hci.ic.gov", + "dualStackDnsSuffix": "api.aws.hci.ic.gov", + "implicitGlobalRegion": "us-isof-south-1", + "name": "aws-iso-f", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-isof\\-\\w+\\-\\d+$", + "regions": { + "aws-iso-f-global": { + "description": "aws-iso-f global region" + }, + "us-isof-east-1": { + "description": "US ISOF EAST" + }, + "us-isof-south-1": { + "description": "US ISOF SOUTH" + } + } + }, + { + "id": "aws-us-gov", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "implicitGlobalRegion": "us-gov-west-1", + "name": "aws-us-gov", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-gov\\-\\w+\\-\\d+$", + "regions": { + "aws-us-gov-global": { + "description": "aws-us-gov global region" + }, + "us-gov-east-1": { + "description": "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + "description": "AWS GovCloud (US-West)" + } + } + } + ], + "version": "1.1" +}; + +let selectedPartitionsInfo = partitionsInfo; +let selectedUserAgentPrefix = ""; +const partition = (value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition of partitions) { + const { regions, outputs } = partition; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData, + }; + } + } + } + for (const partition of partitions) { + const { regionRegex, outputs } = partition; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs, + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex," + + " and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs, + }; +}; +const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}; +const useDefaultPartitionInfo = () => { + setPartitionInfo(partitionsInfo, ""); +}; +const getUserAgentPrefix = () => selectedUserAgentPrefix; + +const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.mode === "string") { + switch (retryStrategy.mode) { + case RETRY_MODES.ADAPTIVE: + setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); + break; + case RETRY_MODES.STANDARD: + setFeature(context, "RETRY_MODE_STANDARD", "E"); + break; + } + } + } + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + setFeature(context, key, value); + } + } +} + +const USER_AGENT = "user-agent"; +const X_AMZ_USER_AGENT = "x-amz-user-agent"; +const SPACE = " "; +const UA_NAME_SEPARATOR = "/"; +const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; +const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; +const UA_ESCAPE_CHAR = "-"; + +const BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; + } + else { + buffer += val; + } + continue; + } + break; + } + return buffer; +} + +const userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); + } + const prefix = getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []) + .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) + .join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent, + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] + ? `${headers[USER_AGENT]} ${normalUAValue}` + : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; + } + else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request, + }); +}; +const escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0] + .split(UA_NAME_SEPARATOR) + .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)) + .join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version] + .filter((item) => item && item.length > 0) + .reduce((acc, item, index) => { + switch (index) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); +}; +const getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true, +}; +const getUserAgentPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, +}); + +const getRuntimeUserAgentPair = () => { + const runtimesToCheck = ["deno", "bun", "llrt"]; + for (const runtime of runtimesToCheck) { + if (versions[runtime]) { + return [`md/${runtime}`, versions[runtime]]; + } + } + return ["md/nodejs", versions.node]; +}; + +const crtAvailability = { + isCrtAvailable: false, +}; + +const isCrtAvailable = () => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}; + +const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => { + const runtimeUserAgentPair = getRuntimeUserAgentPair(); + return async (config) => { + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${platform()}`, release()], + ["lang/js"], + runtimeUserAgentPair, + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); + } + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${env.AWS_EXECUTION_ENV}`]); + } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; +}; +const defaultUserAgent = createDefaultUserAgentProvider; + +const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +const UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +const NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME], + configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], + default: DEFAULT_UA_APP_ID, +}; + +const createUserAgentStringParsingProvider = ({ serviceId, clientVersion }) => async (config) => { + const module = __webpack_require__(97458); + const parse = module.parse ?? module.default.parse ?? (() => ""); + const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? parse(window.navigator.userAgent) : undefined; + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${parsedUA?.os?.name || "other"}`, parsedUA?.os?.version], + ["lang/js"], + ["md/browser", `${parsedUA?.browser?.name ?? "unknown"}_${parsedUA?.browser?.version ?? "unknown"}`], + ]; + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + const appId = await config?.userAgentAppId?.(); + if (appId) { + sections.push([`app/${appId}`]); + } + return sections; +}; + +const fallback = { + os(ua) { + if (/iPhone|iPad|iPod/.test(ua)) + return "iOS"; + if (/Macintosh|Mac OS X/.test(ua)) + return "macOS"; + if (/Windows NT/.test(ua)) + return "Windows"; + if (/Android/.test(ua)) + return "Android"; + if (/Linux/.test(ua)) + return "Linux"; + return undefined; + }, + browser(ua) { + if (/EdgiOS|EdgA|Edg\//.test(ua)) + return "Microsoft Edge"; + if (/Firefox\//.test(ua)) + return "Firefox"; + if (/Chrome\//.test(ua)) + return "Chrome"; + if (/Safari\//.test(ua)) + return "Safari"; + return undefined; + }, +}; + +const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; + } + if (!isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (isIpAddress(value)) { + return false; + } + return true; +}; + +const ARN_DELIMITER = ":"; +const RESOURCE_DELIMITER = "/"; +const parseArn = (value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) + return null; + const [arn, partition, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition, + service, + region, + accountId, + resourceId, + }; +}; + +const awsEndpointFunctions = { + isVirtualHostableS3Bucket: isVirtualHostableS3Bucket, + parseArn: parseArn, + partition: partition, +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +const resolveDefaultAwsRegionalEndpointsConfig = (input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); + } + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + return toEndpointV1(input.endpointProvider({ + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" + ? await input.useDualstackEndpoint() + : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: undefined, + }, { logger: input.logger })); + }; + } + return input; +}; +const toEndpointV1 = (endpoint) => parseUrl(endpoint.url); + +function stsRegionDefaultResolver(loaderConfig = {}) { + return loadConfig({ + ...NODE_REGION_CONFIG_OPTIONS, + async default() { + if (!warning.silence) { + console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); + } + return "us-east-1"; + }, + }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); +} +const warning = { + silence: false, +}; + +const getAwsRegionExtensionConfiguration = (runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + }, + }; +}; +const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region(), + }; +}; + +exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; +exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS; +exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; +exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; +exports.awsEndpointFunctions = awsEndpointFunctions; +exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider; +exports.createUserAgentStringParsingProvider = createUserAgentStringParsingProvider; +exports.crtAvailability = crtAvailability; +exports.defaultUserAgent = defaultUserAgent; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.fallback = fallback; +exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration; +exports.getHostHeaderPlugin = getHostHeaderPlugin; +exports.getLoggerPlugin = getLoggerPlugin; +exports.getLongPollPlugin = getLongPollPlugin; +exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin; +exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; +exports.getUserAgentPlugin = getUserAgentPlugin; +exports.getUserAgentPrefix = getUserAgentPrefix; +exports.hostHeaderMiddleware = hostHeaderMiddleware; +exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; +exports.isVirtualHostableS3Bucket = isVirtualHostableS3Bucket; +exports.loggerMiddleware = loggerMiddleware; +exports.loggerMiddlewareOptions = loggerMiddlewareOptions; +exports.parseArn = parseArn; +exports.partition = partition; +exports.recursionDetectionMiddleware = recursionDetectionMiddleware; +exports.recursionDetectionMiddlewareOptions = recursionDetectionMiddlewareOptions; +exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration; +exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; +exports.resolveHostHeaderConfig = resolveHostHeaderConfig; +exports.resolveUserAgentConfig = resolveUserAgentConfig; +exports.setCredentialFeature = setCredentialFeature; +exports.setFeature = setFeature; +exports.setPartitionInfo = setPartitionInfo; +exports.setTokenFeature = setTokenFeature; +exports.state = state; +exports.stsRegionDefaultResolver = stsRegionDefaultResolver; +exports.stsRegionWarning = warning; +exports.toEndpointV1 = toEndpointV1; +exports.useDefaultPartitionInfo = useDefaultPartitionInfo; +exports.userAgentMiddleware = userAgentMiddleware; + + +/***/ }), + +/***/ 15302: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { ProviderError, booleanSelector, SelectorType, loadConfig } = __webpack_require__(68702); +const { setCredentialFeature } = __webpack_require__(24491); +const { normalizeProvider, memoizeIdentityProvider, isIdentityExpired, doesIdentityRequireRefresh } = __webpack_require__(57255); +const { SignatureV4 } = __webpack_require__(82961); +const { HttpResponse, HttpRequest } = __webpack_require__(62049); +const { SMITHY_CONTEXT_KEY } = __webpack_require__(88867); + +const getDateHeader = (response) => HttpResponse.isInstance(response) ? (response.headers?.date ?? response.headers?.Date) : undefined; +const getAgeHeader = (response) => HttpResponse.isInstance(response) ? (response.headers?.age ?? response.headers?.Age) : undefined; + +const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + +const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset, timeRequestSent, ageHeader) => { + if (ageHeader !== undefined) { + return currentSystemClockOffset; + } + const serverTime = Date.parse(clockTime); + const timeResponseReceived = Date.now(); + if (timeRequestSent !== undefined && timeResponseReceived - timeRequestSent > 900_000) { + return currentSystemClockOffset; + } + const candidateSkew = timeRequestSent !== undefined + ? serverTime - (timeRequestSent + timeResponseReceived) / 2 + : serverTime - timeResponseReceived; + return candidateSkew; +}; + +const throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; +}; +const hasEventStreamOutput = (signingProperties) => { + const context = signingProperties.context; + const eventStream = context?.[SMITHY_CONTEXT_KEY] + ?.eventStream; + return eventStream?.output === true; +}; +const validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName, + }; +}; +class AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const noSkewCorrection = (await config.disableClockSkewCorrection?.()) === true; + signingProperties._disableClockSkewCorrection = noSkewCorrection; + const skipSkewSampling = noSkewCorrection || hasEventStreamOutput(signingProperties); + signingProperties._skipClockSkewSampling = skipSkewSampling; + if (!skipSkewSampling) { + signingProperties._preRequestSystemClockOffset = config.systemClockOffset; + signingProperties._requestSentAt = Date.now(); + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: noSkewCorrection ? new Date() : getSkewCorrectedDate(config.systemClockOffset), + signingRegion: signingRegion, + signingService: signingName, + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const errorException = error; + if (!signingProperties._skipClockSkewSampling && !signingProperties._disableClockSkewCorrection) { + const serverTime = errorException.ServerTime ?? getDateHeader(errorException.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const preRequestOffset = signingProperties._preRequestSystemClockOffset; + const timeRequestSent = signingProperties._requestSentAt; + const ageHeader = getAgeHeader(errorException.$response); + const newOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset, timeRequestSent, ageHeader); + config.systemClockOffset = newOffset; + const skewExceedsThreshold = Math.abs(newOffset) >= 240_000; + const isLocalCorrection = newOffset !== preRequestOffset; + const isConcurrentCorrection = preRequestOffset !== undefined && preRequestOffset !== newOffset; + if (skewExceedsThreshold && (isLocalCorrection || isConcurrentCorrection) && errorException.$metadata) { + errorException.$metadata.clockSkewCorrected = true; + } + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + if (signingProperties._skipClockSkewSampling || signingProperties._disableClockSkewCorrection) { + return; + } + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + const timeRequestSent = signingProperties._requestSentAt; + const ageHeader = getAgeHeader(httpResponse); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset, timeRequestSent, ageHeader); + } + } +} +const AWSSDKSigV4Signer = AwsSdkSigV4Signer; + +class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { + async sign(httpRequest, identity, signingProperties) { + if (!HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? + signingRegionSet ?? [signingRegion]).join(","); + const noSkewCorrection = (await config.disableClockSkewCorrection?.()) === true; + signingProperties._disableClockSkewCorrection = noSkewCorrection; + if (!noSkewCorrection) { + signingProperties._preRequestSystemClockOffset = config.systemClockOffset; + signingProperties._requestSentAt = Date.now(); + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: noSkewCorrection ? new Date() : getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName, + }); + return signedRequest; + } +} + +const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + +const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + +const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) + return undefined; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return undefined; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [], +}; + +const resolveAwsSdkSigV4AConfig = (config) => { + config.sigv4aSigningRegionSet = normalizeProvider(config.sigv4aSigningRegionSet); + return config; +}; +const NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true, + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true, + }); + }, + default: undefined, +}; + +const bindResolveAwsSdkSigV4Config = (defaultDisableClockSkewCorrection) => (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = undefined; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider, + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null; + resolvedCredentials = async (options) => { + const creds = await boundProvider(options); + const attributedCreds = creds; + if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) { + return setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e"); + } + return attributedCreds; + }; + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } + else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true, + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; + let signer; + if (config.signer) { + signer = normalizeProvider(config.signer); + } + else if (config.regionInfoProvider) { + signer = () => normalizeProvider(config.region)() + .then(async (region) => [ + (await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint(), + })) || {}, + region, + ]) + .then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }); + } + else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await normalizeProvider(config.region)(), + properties: {}, + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath, + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer, + disableClockSkewCorrection: normalizeProvider(config.disableClockSkewCorrection ?? defaultDisableClockSkewCorrection), + }); + return resolvedConfig; +}; +function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh); + } + else { + credentialsProvider = credentials; + } + } + else { + if (credentialDefaultProvider) { + credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config, + }))); + } + else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} + +const ENV_DISABLE_CLOCK_SKEW_CORRECTION = "AWS_DISABLE_CLOCK_SKEW_CORRECTION"; +const CONFIG_DISABLE_CLOCK_SKEW_CORRECTION = "disable_clock_skew_correction"; +const NODE_DISABLE_CLOCK_SKEW_CORRECTION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_DISABLE_CLOCK_SKEW_CORRECTION, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_DISABLE_CLOCK_SKEW_CORRECTION, SelectorType.CONFIG), + default: false, +}; + +const DEFAULT_DISABLE_CLOCK_SKEW_CORRECTION = loadConfig(NODE_DISABLE_CLOCK_SKEW_CORRECTION_CONFIG_OPTIONS); + +const resolveAwsSdkSigV4Config = bindResolveAwsSdkSigV4Config(DEFAULT_DISABLE_CLOCK_SKEW_CORRECTION); +const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; + +exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; +exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; +exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; +exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; +exports.getBearerTokenEnvKey = getBearerTokenEnvKey; +exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; +exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; +exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; +exports.validateSigningProperties = validateSigningProperties; + + +/***/ }), + +/***/ 54765: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { SmithyRpcV2CborProtocol, loadSmithyRpcV2CborErrorCode } = __webpack_require__(51260); +const { TypeRegistry, NormalizedSchema, deref } = __webpack_require__(39875); +const { decorateServiceException, getValueFromTextNode } = __webpack_require__(20895); +const { collectBody, determineTimestampFormat, RpcProtocol, HttpBindingProtocol, HttpInterceptingShapeSerializer, HttpInterceptingShapeDeserializer, FromStringShapeDeserializer, extendedEncodeURIComponent } = __webpack_require__(62049); +const { NumericValue, toUtf8, fromBase64, LazyJsonString, parseEpochTimestamp, parseRfc7231DateTime, parseRfc3339DateTimeWithOffset, generateIdempotencyToken, toBase64, dateToUtcString, expectUnion } = __webpack_require__(34129); +const { parseXML, XmlNode, XmlText } = __webpack_require__(80007); + +class ProtocolLib { + queryCompat; + errorRegistry; + constructor(queryCompat = false) { + this.queryCompat = queryCompat; + } + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } + else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } + else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } + else { + return defaultContentType; + } + } + else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server", + }; + if (!this.errorRegistry) { + throw new Error("@aws-sdk/core/protocols - error handler not initialized."); + } + try { + const errorSchema = getErrorSchema?.(this.errorRegistry, errorName) ?? + this.errorRegistry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } + catch (e) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = this.errorRegistry; + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); + } + const d = dataObject; + const message = d?.message ?? d?.Message ?? d?.Error?.Message ?? d?.Error?.message; + throw this.decorateServiceException(Object.assign(new Error(message), { + name: errorName, + }, errorMetadata), dataObject); + } + } + compose(composite, errorIdentifier, defaultNamespace) { + let namespace = defaultNamespace; + if (errorIdentifier.includes("#")) { + [namespace] = errorIdentifier.split("#"); + } + const staticRegistry = TypeRegistry.for(namespace); + const defaultSyntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + defaultNamespace); + composite.copyFrom(staticRegistry); + composite.copyFrom(defaultSyntheticRegistry); + this.errorRegistry = composite; + } + decorateServiceException(exception, additions = {}) { + if (this.queryCompat) { + const msg = exception.Message ?? additions.Message; + const error = decorateServiceException(exception, additions); + if (msg) { + error.message = msg; + } + const errorObj = error.Error ?? {}; + errorObj.Type = error.Error?.Type; + errorObj.Code = error.Error?.Code; + errorObj.Message = error.Error?.message ?? error.Error?.Message ?? msg; + error.Error = errorObj; + const reqId = error.$metadata.requestId; + if (reqId) { + error.RequestId = reqId; + } + return error; + } + return decorateServiceException(exception, additions); + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== undefined && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const keys = Object.keys(output); + const Error = { + Code, + Type, + }; + output.Code = Code; + output.Type = Type; + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + Error[k === "message" ? "Message" : k] = output[k]; + } + delete Error.__type; + output.Error = Error; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } + findQueryCompatibleError(registry, errorName) { + try { + return registry.getSchema(errorName); + } + catch (e) { + return registry.find((schema) => NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName); + } + } +} + +class AwsSmithyRpcV2CborProtocol extends SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin; + constructor({ defaultNamespace, errorTypeRegistries, awsQueryCompatible, }) { + super({ defaultNamespace, errorTypeRegistries }); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = (() => { + const compatHeader = response.headers["x-amzn-query-error"]; + if (compatHeader && this.awsQueryCompatible) { + return compatHeader.split(";")[0]; + } + return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + })(); + this.mixin.compose(this.compositeErrorRegistry, errorName, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = {}; + for (const [name, member] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class UnionSerde { + from; + to; + keys; + constructor(from, to) { + this.from = from; + this.to = to; + const keys = Object.keys(this.from); + const set = new Set(keys); + set.delete("__type"); + this.keys = set; + } + mark(key) { + this.keys.delete(key); + } + hasUnknown() { + return this.keys.size === 1 && Object.keys(this.to).length === 0; + } + writeUnknown() { + if (this.hasUnknown()) { + const k = this.keys.values().next().value; + const v = this.from[k]; + this.to.$unknown = [k, v]; + } + } +} + +let canParseBuffer; +function detectBufferParsing() { + if (canParseBuffer === undefined) { + try { + if (typeof Buffer !== "function") { + canParseBuffer = false; + } + else { + const result = JSON.parse(Buffer.from([0x7b, 0x7d])); + canParseBuffer = result !== null && typeof result === "object"; + } + } + catch { + canParseBuffer = false; + } + } + return canParseBuffer; +} + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + const inSafeRange = value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER; + if (inSafeRange) { + if (isRepresentable(numericString, value)) { + return value; + } + return new NumericValue(numericString, "bigDecimal"); + } + else { + if (isFractionalBigNumeric(numericString)) { + return new NumericValue(numericString, "bigDecimal"); + } + if (/[eE]/.test(numericString)) { + return expandExponentToBigInt(numericString); + } + return BigInt(numericString); + } + } + } + return value; +} +function isFractionalBigNumeric(s) { + const dotIndex = s.indexOf("."); + if (dotIndex === -1) { + return false; + } + const eIndex = s.search(/[eE]/); + if (eIndex === -1) { + return true; + } + const fracDigits = eIndex - dotIndex - 1; + const exp = parseInt(s.slice(eIndex + 1), 10); + return exp < fracDigits; +} +function isRepresentable(numericString, value) { + if (numericString === String(value)) { + return true; + } + if (Object.is(value, -0)) { + return true; + } + if (/[eE]/.test(numericString)) { + return expandToDecimal(numericString) === expandToDecimal(String(value)); + } + const normalized = numericString.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + const canonical = String(value); + if (normalized === canonical) { + return true; + } + if (/[eE]/.test(canonical)) { + return normalized === expandToDecimal(canonical); + } + return false; +} +function expandToDecimal(s) { + const negative = s.startsWith("-"); + const abs = negative ? s.slice(1) : s; + const eIndex = abs.search(/[eE]/); + let result; + if (eIndex === -1) { + result = abs; + } + else { + const exp = parseInt(abs.slice(eIndex + 1), 10); + const mantissa = abs.slice(0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let intLen; + if (dotIndex === -1) { + digits = mantissa; + intLen = mantissa.length; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + intLen = dotIndex; + } + digits = digits.replace(/0+$/, "") || "0"; + const newDotPos = intLen + exp; + if (digits === "0") { + result = "0"; + } + else if (newDotPos <= 0) { + result = "0." + "0".repeat(-newDotPos) + digits; + } + else if (newDotPos >= digits.length) { + result = digits + "0".repeat(newDotPos - digits.length); + } + else { + result = digits.slice(0, newDotPos) + "." + digits.slice(newDotPos); + } + } + if (result.includes(".")) { + result = result.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + } + return (negative ? "-" : "") + result; +} +function expandExponentToBigInt(s) { + const eIndex = s.search(/[eE]/); + const exp = parseInt(s.slice(eIndex + 1), 10); + const negative = s.startsWith("-"); + const mantissa = s.slice(negative ? 1 : 0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let shift; + if (dotIndex === -1) { + digits = mantissa; + shift = exp; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + const fracDigits = mantissa.length - dotIndex - 1; + shift = exp - fracDigits; + } + digits = digits.replace(/0+$/, "") || "0"; + const result = BigInt(digits) * 10n ** BigInt(shift + (mantissa.replace(".", "").length - digits.length)); + return negative ? -result : result; +} + +const REVIVER_SYMBOL = Symbol.for("@aws-sdk/reviver"); +function needsReviver(schema) { + const ns = NormalizedSchema.of(schema); + const raw = ns.getSchema(); + if (Array.isArray(raw) && ns.isStructSchema()) { + if (REVIVER_SYMBOL in raw) { + return raw[REVIVER_SYMBOL]; + } + const result = _check(ns, new Set()); + raw[REVIVER_SYMBOL] = result; + return result; + } + return _check(ns, new Set()); +} +function _check(ns, seen) { + const raw = ns.getSchema(); + if (seen.has(raw)) { + return false; + } + seen.add(raw); + if (ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + return true; + } + if (ns.isStructSchema()) { + for (const [, memberSchema] of ns.structIterator()) { + if (_check(memberSchema, seen)) { + return true; + } + } + } + else if (ns.isListSchema() || ns.isMapSchema()) { + if (_check(ns.getValueSchema(), seen)) { + return true; + } + } + else if (ns.isDocumentSchema()) { + return true; + } + return false; +} + +const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? toUtf8)(body)); + +async function parseJsonBody(streamBody, context, schema) { + let parsingInput; + if (detectBufferParsing() && typeof streamBody?.[Symbol.asyncIterator] === "function") { + const buffer = await collectBody(streamBody, context); + if (typeof Buffer === "function") { + if (Buffer.isBuffer(buffer)) { + parsingInput = buffer; + } + else { + parsingInput = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + } + } + if (!parsingInput) { + parsingInput = await collectBodyString(streamBody, context); + } + if (parsingInput.length === 0) { + return {}; + } + const reviver = schema && needsReviver(schema) ? jsonReviver : undefined; + try { + return JSON.parse(parsingInput, reviver); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: typeof parsingInput === "string" ? parsingInput : parsingInput.toString("utf8"), + }); + } + throw e; + } +} +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); +const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; +}; +const loadRestJsonErrorCode = (output, data) => { + return loadErrorCode(output, data, ["header", "code", "type"]); +}; +const loadJsonRpcErrorCode = (output, data, queryCompat = false) => { + return loadErrorCode(output, data, queryCompat ? ["code", "header", "type"] : ["type", "code", "header"]); +}; +const loadErrorCode = ({ headers }, data, order) => { + while (order.length > 0) { + const location = order.shift(); + switch (location) { + case "header": + const headerKey = findKey(headers ?? {}, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(headers[headerKey]); + } + break; + case "code": + const codeKey = findKey(data ?? {}, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + break; + case "type": + if (data?.__type !== undefined) { + return sanitizeErrorCode(data.__type); + } + break; + } + } +}; + +function writeKey(obj) { + Object.defineProperty(obj, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true }); +} + +class JsonShapeDeserializer2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + let parsed; + if (typeof data === "string") { + if (data.length === 0) { + return {}; + } + parsed = JSON.parse(data, reviver); + } + else if (data instanceof Uint8Array && detectBufferParsing()) { + if (data.byteLength === 0) { + return {}; + } + const buf = Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + parsed = JSON.parse(buf, reviver); + } + else { + parsed = await parseJsonBody(data, this.serdeContext, schema); + } + return this._read(schema, parsed); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + return this._readStruct(ns, value); + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + if (this.needsTransform(listMember)) { + for (let i = 0; i < value.length; ++i) { + value[i] = this._read(listMember, value[i]); + } + } + return value; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const map = value; + if (this.needsTransform(mapMember)) { + for (const k in map) { + if (k === "__proto__") { + writeKey(map); + } + map[k] = this._read(mapMember, map[k]); + } + } + return map; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (!(v instanceof NumericValue)) { + value[i] = this._read(ns, v); + } + } + } + else { + const doc = value; + for (const k in doc) { + if (k === "__proto__") { + writeKey(doc); + } + const v = doc[k]; + if (!(v instanceof NumericValue)) { + doc[k] = this._read(ns, v); + } + } + } + } + } + return value; + } + _readStruct(ns, record) { + const union = ns.isUnionSchema(); + const out = {}; + let nameMap; + const hasType = typeof record.__type === "string"; + const { jsonName } = this.settings; + if (jsonName && hasType) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + if (hasType) { + nameMap[fromKey] = memberName; + } + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (hasType) { + for (const k in record) { + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + needsTransform(ns) { + if (ns.isBlobSchema() || ns.isTimestampSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + return true; + } + if (ns.isDocumentSchema() || ns.isStructSchema() || ns.isListSchema() || ns.isMapSchema()) { + return true; + } + if (ns.isStringSchema() && ns.getMergedTraits().mediaType) { + return true; + } + return false; + } +} + +class JsonBytesStringAdapter extends Uint8Array { + string = null; + static allocUnsafe(bytes) { + if (typeof Buffer === "function") { + const buffer = Buffer.allocUnsafe(bytes); + return new JsonBytesStringAdapter(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + return new JsonBytesStringAdapter(bytes); + } + toString() { + return this.s(); + } + valueOf() { + return this.s(); + } + includes(searchString, position) { + if (typeof searchString === "string") { + return this.s().includes(searchString, position); + } + return Uint8Array.prototype.includes.call(this, searchString, position); + } + indexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().indexOf(searchString, position); + } + return Uint8Array.prototype.indexOf.call(this, searchString, position); + } + lastIndexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().lastIndexOf(searchString, position); + } + const fn = Uint8Array.prototype.lastIndexOf; + if (position !== undefined) { + return fn.call(this, searchString, position); + } + return fn.call(this, searchString); + } + startsWith(searchString, position) { + return this.s().startsWith(searchString, position); + } + endsWith(searchString, endPosition) { + return this.s().endsWith(searchString, endPosition); + } + match(regexp) { + return this.s().match(regexp); + } + replace(searchValue, replaceValue) { + return this.s().replace(searchValue, replaceValue); + } + search(regexp) { + return this.s().search(regexp); + } + split(separator, limit) { + return this.s().split(separator, limit); + } + substring(start, end) { + return this.s().substring(start, end); + } + trim() { + return this.s().trim(); + } + trimStart() { + return this.s().trimStart(); + } + trimEnd() { + return this.s().trimEnd(); + } + charAt(pos) { + return this.s().charAt(pos); + } + charCodeAt(index) { + return this.s().charCodeAt(index); + } + padStart(maxLength, fillString) { + return this.s().padStart(maxLength, fillString); + } + padEnd(maxLength, fillString) { + return this.s().padEnd(maxLength, fillString); + } + repeat(count) { + return this.s().repeat(count); + } + toUpperCase() { + return this.s().toUpperCase(); + } + toLowerCase() { + return this.s().toLowerCase(); + } + s() { + if (this.string == null) { + const n = Date.now(); + if (n > warned + 60_000) { + console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. " + + "It has been automatically converted to string. In a future version this will throw an error."); + warned = n; + } + this.string = toUtf8(this); + } + return this.string; + } +} +var warned = 0; + +const encoder = new TextEncoder(); +const OPEN_BRACE = 0x7b; +const CLOSE_BRACE = 0x7d; +const OPEN_BRACKET = 0x5b; +const CLOSE_BRACKET = 0x5d; +const QUOTE = 0x22; +const COLON = 0x3a; +const COMMA = 0x2c; +const BACKSLASH = 0x5c; +const TRUE = new Uint8Array([0x74, 0x72, 0x75, 0x65]); +const FALSE = new Uint8Array([0x66, 0x61, 0x6c, 0x73, 0x65]); +const NULL = new Uint8Array([0x6e, 0x75, 0x6c, 0x6c]); +const ESCAPE_TABLE = new Array(128).fill(null); +ESCAPE_TABLE[0x08] = "b"; +ESCAPE_TABLE[0x09] = "t"; +ESCAPE_TABLE[0x0a] = "n"; +ESCAPE_TABLE[0x0c] = "f"; +ESCAPE_TABLE[0x0d] = "r"; +ESCAPE_TABLE[0x22] = '"'; +ESCAPE_TABLE[0x5c] = "\\"; +for (let i = 0; i < 0x20; i++) { + if (ESCAPE_TABLE[i] === null) { + ESCAPE_TABLE[i] = "u00" + i.toString(16).padStart(2, "0"); + } +} +const INITIAL_BUFFER_SIZE = 2048; +function alloc(size) { + return JsonBytesStringAdapter.allocUnsafe(size); +} +class JsonShapeSerializer2 extends SerdeContextConfig { + settings; + json; + i = 0; + rootSchema; + rawValue; + passthrough = false; + constructor(settings) { + super(); + this.settings = settings; + this.json = alloc(INITIAL_BUFFER_SIZE); + } + write(schema, value) { + this.i = 0; + this.rawValue = value; + this.rootSchema = NormalizedSchema.of(schema); + this.passthrough = this.rootSchema.isBlobSchema() || this.rootSchema.isStringSchema(); + if (!this.passthrough) { + this.writeValue(this.rootSchema, value, undefined); + } + } + writeDiscriminatedDocument(schema, value) { + this.i = 0; + this.rootSchema = NormalizedSchema.of(schema); + const ns = this.rootSchema; + if (ns.isStructSchema() && value != null && typeof value === "object") { + this.writeValue(ns, value, undefined); + const prefix = `"__type":"${ns.getName(true) ?? "Unknown"}",`; + const z = prefix.length; + this.ensure(z); + this.json.copyWithin(1 + z, 1, this.i); + encoder.encodeInto(prefix, this.json.subarray(1)); + this.i += z; + } + else { + this.writeValue(ns, value, undefined); + } + } + flush() { + this.rootSchema = undefined; + const finalPosition = this.i; + this.i = 0; + const raw = this.rawValue; + this.rawValue = undefined; + if (finalPosition === 0) { + return raw; + } + const result = this.json.subarray(0, finalPosition); + this.json = alloc(INITIAL_BUFFER_SIZE); + return result; + } + ensure(byteCount) { + const { i, json } = this; + if (i + byteCount > json.length) { + let newSize = json.length * 2; + while (newSize < i + byteCount) { + newSize *= 2; + } + const next = alloc(newSize); + next.set(this.json); + this.json = next; + } + } + writeAscii(s) { + const z = s.length; + this.ensure(z); + let { i, json } = this; + for (let j = 0; j < z; ++j) { + json[i] = s.charCodeAt(j); + i += 1; + } + this.i = i; + } + writeAsciiQuoted(s) { + const z = s.length; + this.ensure(z + 4); + let { json, i } = this; + json[i++] = QUOTE; + for (let j = 0; j < z; ++j) { + json[i++] = s.charCodeAt(j); + } + json[i++] = QUOTE; + this.i = i; + } + writeJsonString(s) { + this.ensure(s.length * 3 + 2); + this.json[this.i++] = QUOTE; + const z = s.length; + for (let j = 0; j < z; ++j) { + const c = s.charCodeAt(j); + if (c > 0x22 && c < 0x5c) { + this.json[this.i++] = c; + } + else if (c < 0x80) { + const esc = ESCAPE_TABLE[c]; + if (esc !== null) { + this.ensure(esc.length + 1); + this.json[this.i++] = BACKSLASH; + for (let k = 0; k < esc.length; k++) { + this.json[this.i++] = esc.charCodeAt(k); + } + } + else { + this.json[this.i++] = c; + } + } + else if (c >= 0xd800 && c <= 0xdbff) { + const next = j + 1 < z ? s.charCodeAt(j + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + this.ensure(4); + const { written } = encoder.encodeInto(s.substring(j, j + 2), this.json.subarray(this.i)); + this.i += written; + ++j; + } + else { + this.ensure(6); + this.writeUnicodeEscape(c); + } + } + else if (c >= 0xdc00 && c <= 0xdfff) { + this.ensure(6); + this.writeUnicodeEscape(c); + } + else { + let { i, json } = this; + if (c < 0x800) { + json[i++] = 0xc0 | (c >> 6); + json[i++] = 0x80 | (c & 0x3f); + } + else { + json[i++] = 0xe0 | (c >> 12); + json[i++] = 0x80 | ((c >> 6) & 0x3f); + json[i++] = 0x80 | (c & 0x3f); + } + this.i = i; + } + } + this.json[this.i++] = QUOTE; + } + writeUnicodeEscape(code) { + let { json, i } = this; + json[i++] = BACKSLASH; + json[i++] = 0x75; + const hex = code.toString(16).padStart(4, "0"); + for (let j = 0; j < 4; ++j) { + json[i++] = hex.charCodeAt(j); + } + this.i = i; + } + static B64 = (() => { + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const table = new Uint8Array(64); + for (let i = 0; i < 64; ++i) { + table[i] = chars.charCodeAt(i); + } + return table; + })(); + writeBase64(data) { + const b64Len = Math.ceil(data.length / 3) * 4; + this.ensure(b64Len + 2); + const json = this.json; + const B64 = JsonShapeSerializer2.B64; + let i = this.i; + json[i++] = QUOTE; + const len = data.length; + const remainder = len % 3; + const mainLen = len - remainder; + for (let j = 0; j < mainLen; j += 3) { + const a = data[j]; + const b = data[j + 1]; + const c = data[j + 2]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[((b & 0x0f) << 2) | (c >> 6)]; + json[i++] = B64[c & 0x3f]; + } + if (remainder === 2) { + const a = data[mainLen]; + const b = data[mainLen + 1]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[(b & 0x0f) << 2]; + json[i++] = 0x3d; + } + else if (remainder === 1) { + const a = data[mainLen]; + json[i++] = B64[a >> 2]; + json[i++] = B64[(a & 0x03) << 4]; + json[i++] = 0x3d; + json[i++] = 0x3d; + } + json[i++] = QUOTE; + this.i = i; + } + writeValue(schema, value, container) { + if (value == null) { + if (container?.isStructSchema()) { + if (value === undefined) { + const ns = NormalizedSchema.of(schema); + if (ns.isIdempotencyToken()) { + this.writeAsciiQuoted(generateIdempotencyToken()); + return; + } + } + return; + } + this.ensure(4); + this.json.set(NULL, this.i); + this.i += 4; + return; + } + const ns = NormalizedSchema.of(schema); + const isObject = typeof value === "object"; + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + this.writeJsonString(LazyJsonString.from(value).toString()); + return; + } + } + } + if (isObject) { + if (ns.isStructSchema()) { + this.writeStruct(ns, value); + return; + } + if (Array.isArray(value) && (ns.isListSchema() || ns.isDocumentSchema())) { + this.writeList(ns, value, ns.isDocumentSchema()); + return; + } + if (ns.isMapSchema()) { + this.writeMap(ns, value, false); + return; + } + if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { + this.writeBase64(value); + return; + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + this.writeTimestamp(ns, value); + return; + } + if (value instanceof NumericValue) { + this.writeAscii(value.string); + return; + } + if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.writeList(ns, value, true); + } + else { + this.writeMap(ns, value, true); + } + return; + } + const json = JSON.stringify(value); + this.writeAscii(json); + return; + } + if (typeof value === "string") { + if (ns.isBlobSchema()) { + const b64 = (this.serdeContext?.base64Encoder ?? toBase64)(value); + this.writeAsciiQuoted(b64); + return; + } + this.writeJsonString(value); + return; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || Number.isNaN(value)) { + this.writeAsciiQuoted(String(value)); + return; + } + const numStr = String(value); + this.writeAscii(numStr); + return; + } + if (typeof value === "boolean") { + this.ensure(5); + let { i, json } = this; + if (value) { + json.set(TRUE, i); + i += 4; + } + else { + json.set(FALSE, i); + i += 5; + } + this.i = i; + return; + } + if (typeof value === "bigint") { + this.writeAscii(value.toString()); + return; + } + this.writeAscii(String(value)); + } + writeStruct(ns, value) { + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let wroteAny = false; + const hasType = typeof value.__type === "string"; + let writtenKeys; + if (hasType) { + writtenKeys = new Set(); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const item = value[memberName]; + if (item == null && !memberSchema.isIdempotencyToken()) { + continue; + } + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + const targetKey = this.settings.jsonName ? (memberSchema.getMergedTraits().jsonName ?? memberName) : memberName; + if (writtenKeys) { + writtenKeys.add(memberName); + writtenKeys.add(targetKey); + } + this.writeAsciiQuoted(targetKey); + this.json[this.i++] = COLON; + this.writeValue(memberSchema, item, ns); + } + if (!wroteAny && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, ns); + } + } + else if (hasType) { + for (const k in value) { + if (writtenKeys.has(k)) { + continue; + } + writtenKeys.add(k); + const v = value[k]; + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, undefined); + } + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeList(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let hasSpecials = false; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity || (v == null && !sparse)) { + hasSpecials = true; + break; + } + } + let json; + if (!hasSpecials) { + json = JSON.stringify(value); + } + else { + const out = []; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (v == null && !sparse) + continue; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + out.push(String(v)); + } + else { + out.push(v); + } + } + json = JSON.stringify(out); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACKET; + let wroteFirstItem = false; + for (let i = 0; i < value.length; ++i) { + const item = value[i]; + if (isDocument ? item === undefined : item == null && !sparse) { + continue; + } + if (wroteFirstItem) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + this.writeValue(valueSchema, item, undefined); + wroteFirstItem = true; + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACKET; + } + writeMap(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let modifications; + for (const k in value) { + const v = value[k]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + (modifications ??= {})[k] = v; + value[k] = String(v); + } + else if (v === null && !sparse) { + (modifications ??= {})[k] = null; + value[k] = undefined; + } + } + const json = JSON.stringify(value); + if (modifications) { + Object.assign(value, modifications); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let first = true; + for (const k in value) { + const v = value[k]; + if (isDocument ? v === undefined : v == null && !sparse) { + continue; + } + if (!first) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + first = false; + this.writeJsonString(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(valueSchema, v, undefined); + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeTimestamp(ns, value) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: { + const iso = value.toISOString().replace(".000Z", "Z"); + this.writeAsciiQuoted(iso); + return; + } + case 6: { + this.writeAsciiQuoted(dateToUtcString(value)); + return; + } + case 7: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + default: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + } + } +} + +class JsonCodec2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer2(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer2(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsJsonRpcProtocol extends RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin; + awsQueryCompatible; + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + }); + this.serviceTarget = serviceTarget; + this.codec = + jsonCodec ?? + new JsonCodec2({ + timestampFormat: { + useTrait: true, + default: 7, + }, + jsonName: false, + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + request.headers["content-type"] = `application/x-amz-json-${this.getJsonRpcVersion()}`; + request.headers["x-amz-target"] = `${this.serviceTarget}.${operationSchema.name}`; + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const { awsQueryCompatible } = this; + if (awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadJsonRpcErrorCode(response, dataObject, awsQueryCompatible) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = errorDeserializer.readObject(member, dataObject[name]); + } + } + if (awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } +} + +class AwsJson1_0Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + serviceTarget, + awsQueryCompatible, + jsonCodec, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } +} + +class AwsJson1_1Protocol extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries, serviceTarget, awsQueryCompatible, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + serviceTarget, + awsQueryCompatible, + jsonCodec, + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; + } +} + +class AwsRestJsonProtocol extends HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace, errorTypeRegistries, jsonCodec, }) { + super({ + defaultNamespace, + errorTypeRegistries, + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7, + }, + httpBindings: true, + jsonName: true, + }; + this.codec = jsonCodec ?? new JsonCodec2(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { + request.body = "{}"; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const output = await super.deserializeResponse(operationSchema, context, response); + const outputSchema = NormalizedSchema.of(operationSchema.output); + for (const [name, member] of outputSchema.structIterator()) { + if (member.getMemberTraits().httpPayload && !(name in output)) { + output[name] = null; + } + } + return output; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = errorDeserializer.readObject(member, dataObject[target]); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/json"; + } +} + +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + return this._read(schema, typeof data === "string" ? JSON.parse(data, reviver) : await parseJsonBody(data, this.serdeContext, schema)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const union = ns.isUnionSchema(); + const out = {}; + let nameMap = void 0; + const { jsonName } = this.settings; + if (jsonName) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + nameMap[fromKey] = memberName; + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (typeof record.__type === "string") { + for (const k in record) { + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(this._read(listMember, item)); + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + for (const _k in value) { + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._read(mapMember, value[_k]); + } + return out; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + if (k === "__proto__") { + writeKey(out); + } + const v = value[k]; + if (v instanceof NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} + +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + useReplacer = false; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + this.rootSchema = NormalizedSchema.of(schema); + this.buffer = this._write(this.rootSchema, value); + } + flush() { + const { rootSchema, useReplacer } = this; + this.rootSchema = undefined; + this.useReplacer = false; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + if (!useReplacer) { + return JSON.stringify(this.buffer); + } + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + writeDiscriminatedDocument(schema, value) { + this.write(schema, value); + if (typeof this.buffer === "object") { + this.buffer.__type = NormalizedSchema.of(schema).getName(true); + } + } + _write(schema, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const out = {}; + const { jsonName } = this.settings; + let nameMap = void 0; + if (jsonName) { + nameMap = {}; + } + let outCount = 0; + for (const [memberName, memberSchema] of ns.structIterator()) { + const serializableValue = this._write(memberSchema, record[memberName], ns); + if (serializableValue !== undefined) { + let targetKey = memberName; + if (jsonName) { + targetKey = memberSchema.getMergedTraits().jsonName ?? memberName; + nameMap[memberName] = targetKey; + } + out[targetKey] = serializableValue; + outCount++; + } + } + if (ns.isUnionSchema() && outCount === 0) { + const { $unknown } = record; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + if (k === "__proto__") { + writeKey(out); + } + out[k] = this._write(15, v); + } + } + else if (typeof record.__type === "string") { + for (const k in record) { + const v = record[k]; + const targetKey = jsonName ? (nameMap[k] ?? k) : k; + if (!(targetKey in out)) { + out[targetKey] = this._write(15, v); + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const _k in value) { + const _v = value[_k]; + if (sparse || _v != null) { + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + if (value instanceof Uint8Array && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (value instanceof NumericValue) { + this.useReplacer = true; + } + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + } + return value; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + return value; + } + if (typeof value === "string" && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (typeof value === "bigint") { + this.useReplacer = true; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (value instanceof Uint8Array) { + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + const v = value[k]; + if (k === "__proto__") { + writeKey(out); + } + if (v instanceof NumericValue) { + this.useReplacer = true; + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class XmlShapeDeserializer extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema, bytes, key) { + const ns = NormalizedSchema.of(schema); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && + ns.isMemberSchema() && + !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } + else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + if (source == null) { + return buffer; + } + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v of sourceArray) { + buffer.push(this.readSchema(listValue, v)); + } + return buffer; + } + const buffer = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries; + if (flat) { + entries = Array.isArray(value) ? value : [value]; + } + else { + entries = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries) { + const key = entry[keyProperty]; + const value = entry[valueProperty]; + if (key === "__proto__") { + writeKey(buffer); + } + buffer[key] = this.readSchema(memberNs, value); + } + return buffer; + } + if (ns.isStructSchema()) { + const union = ns.isUnionSchema(); + let unionSerde; + if (union) { + unionSerde = new UnionSerde(value, buffer); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload + ? (memberSchema.getMemberTraits().xmlName ?? memberName) + : (memberTraits.xmlName ?? memberSchema.getName()); + if (union) { + unionSerde.mark(xmlObjectKey); + } + if (value[xmlObjectKey] != null) { + buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + return buffer; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml) { + if (xml.length) { + let parsedObj; + try { + parsedObj = parseXML(xml); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: xml, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return getValueFromTextNode(parsedObjToReturn); + } + return {}; + } +} + +class QueryShapeSerializer extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value, prefix = "") { + if (this.buffer === undefined) { + this.buffer = ""; + } + const ns = NormalizedSchema.of(schema); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? toBase64)(value)); + } + } + else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue(generateIdempotencyToken()); + } + } + else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof NumericValue ? value.string : String(value)); + } + } + else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue(dateToUtcString(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1000)); + break; + } + } + } + else if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.write(64 | 15, value, prefix); + } + else if (value instanceof Date) { + this.write(4, value, prefix); + } + else if (value instanceof Uint8Array) { + this.write(21, value, prefix); + } + else if (value && typeof value === "object") { + this.write(128 | 15, value, prefix); + } + else { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } + else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } + else { + const member = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const item of value) { + if (item == null) { + continue; + } + const traits = member.getMergedTraits(); + const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName); + const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; + this.write(member, item, key); + ++i; + } + } + } + } + else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i = 1; + for (const k in value) { + const v = value[k]; + if (v == null) { + continue; + } + const keyTraits = keySchema.getMergedTraits(); + const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName); + const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; + const valTraits = memberSchema.getMergedTraits(); + const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName); + const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; + this.write(keySchema, k, key); + this.write(memberSchema, v, valueKey); + ++i; + } + } + } + else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + let didWriteMember = false; + for (const [memberName, member] of ns.structIterator()) { + if (value[memberName] == null && !member.isIdempotencyToken()) { + continue; + } + const traits = member.getMergedTraits(); + const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct"); + const key = `${prefix}${suffix}`; + this.write(member, value[memberName], key); + didWriteMember = true; + } + if (!didWriteMember && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + const key = `${prefix}${k}`; + this.write(15, v, key); + } + } + } + } + else if (ns.isUnitSchema()) ; + else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } + } + flush() { + if (this.buffer === undefined) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; + } + getKey(memberName, xmlName, ec2QueryName, keySource) { + const { ec2, capitalizeKeys } = this.settings; + if (ec2 && ec2QueryName) { + return ec2QueryName; + } + const key = xmlName ?? memberName; + if (capitalizeKeys && keySource === "struct") { + return key[0].toUpperCase() + key.slice(1); + } + return key; + } + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${extendedEncodeURIComponent(key)}=`; + } + writeValue(value) { + this.buffer += extendedEncodeURIComponent(value); + } +} + +class AwsQueryProtocol extends RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + errorTypeRegistries: options.errorTypeRegistries, + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true, + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); + } + getShapeId() { + return "aws.protocols#awsQuery"; + } + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + } + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + request.headers["content-type"] = "application/x-www-form-urlencoded"; + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + useNestedResult() { + return true; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const errorData = this.loadQueryError(dataObject) ?? {}; + const message = this.loadQueryErrorMessage(dataObject); + errorData.message = message; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message, + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError); + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + const output = { + Type: errorData.Error.Type, + Code: errorData.Error.Code, + Error: errorData.Error, + }; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + loadQueryErrorCode(output, data) { + const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; + if (code !== undefined) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data) { + return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + } + loadQueryErrorMessage(data) { + const errorData = this.loadQueryError(data); + return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } +} + +class AwsEc2QueryProtocol extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + ec2: true, + }; + Object.assign(this.serializer.settings, ec2Settings); + } + getShapeId() { + return "aws.protocols#ec2Query"; + } + useNestedResult() { + return false; + } +} + +const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = parseXML(encoded); + } + catch (e) { + if (e && typeof e === "object") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded, + }); + } + throw e; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return getValueFromTextNode(parsedObjToReturn); + } + return {}; +}); +const parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; +}; +const loadRestXmlErrorCode = (output, data) => { + if (data?.Error?.Code !== undefined) { + return data.Error.Code; + } + if (data?.Code !== undefined) { + return data.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}; + +class XmlShapeSerializer extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } + else if (ns.isBlobSchema()) { + this.byteBuffer = + "byteLength" in value + ? value + : (this.serdeContext?.base64Decoder ?? fromBase64)(value); + } + else { + this.buffer = this.writeStruct(ns, value, undefined); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== undefined) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== undefined) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer?.attributes?.["xmlns"]) { + buffer.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload + ? (ns.getMemberTraits().xmlName ?? ns.getMemberName()) + : (traits.xmlName ?? ns.getName()); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } + else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } + else { + const memberNode = XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + const { $unknown } = value; + if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { + const [k, v] = $unknown; + const node = XmlNode.of(k); + if (typeof v !== "string") { + if (value instanceof XmlNode || value instanceof XmlText) { + structXmlNode.addChildNode(value); + } + else { + throw new Error(`@aws-sdk - $unknown union member in XML requires ` + + `value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`); + } + } + this.writeSimpleInto(0, v, node, xmlns); + structXmlNode.addChildNode(node); + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); + } + else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container, xmlns); + } + else if (listValueSchema.isStructSchema()) { + const struct = this.writeStruct(listValueSchema, value, xmlns); + container.addChildNode(struct.withName(flat ? (listTraits.xmlName ?? listMember.getMemberName()) : (listValueTraits.xmlName ?? "member"))); + } + else { + const listItemNode = XmlNode.of(flat ? (listTraits.xmlName ?? listMember.getMemberName()) : (listValueTraits.xmlName ?? "member")); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container.addChildNode(listItemNode); + } + }; + if (flat) { + for (const value of array) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } + else { + const listNode = XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } + else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } + else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } + else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }; + if (flat) { + for (const key in map) { + const val = map[key]; + if (sparse || val != null) { + const entry = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } + else { + let mapNode; + if (!containerIsMap) { + mapNode = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const key in map) { + const val = map[key]; + if (sparse || val != null) { + const entry = XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + else if (ns.isTimestampSchema() && value instanceof Date) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = dateToUtcString(value); + break; + case 7: + nodeContents = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = dateToUtcString(value); + break; + } + } + else if (ns.isBigDecimalSchema() && value) { + if (value instanceof NumericValue) { + return value.string; + } + return String(value); + } + else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } + else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === undefined && ns.isIdempotencyToken()) { + nodeContents = generateIdempotencyToken(); + } + else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = NormalizedSchema.of(_schema); + const content = new XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } +} + +class XmlCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class AwsRestXmlProtocol extends HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5, + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + }; + this.codec = new XmlCodec(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (typeof request.body === "string" && + request.headers["content-type"] === this.getDefaultContentType() && + !request.body.startsWith("' + request.body; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + if (dataObject.Error && typeof dataObject.Error === "object") { + for (const key of Object.keys(dataObject.Error)) { + dataObject[key] = dataObject.Error[key]; + if (key.toLowerCase() === "message") { + dataObject.message = dataObject.Error[key]; + } + } + } + if (dataObject.RequestId && !metadata.requestId) { + metadata.requestId = dataObject.RequestId; + } + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.Error?.message ?? + dataObject.Error?.Message ?? + dataObject.message ?? + dataObject.Message ?? + "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor({}); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = errorDeserializer.readSchema(member, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output), dataObject); + } + getDefaultContentType() { + return "application/xml"; + } + hasUnstructuredPayloadBinding(ns) { + for (const [, member] of ns.structIterator()) { + if (member.getMergedTraits().httpPayload) { + return !(member.isStructSchema() || member.isMapSchema() || member.isListSchema()); + } + } + return false; + } +} + +const awsExpectUnion = (value) => { + if (value == null) { + return undefined; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return expectUnion(value); +}; + +const _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; +}; +const _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const lowercase = val.toLowerCase(); + if (val !== "" && lowercase !== "false" && lowercase !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase !== "false"; + } + return val; +}; +const _toNum = (val) => { + if (val == null) { + return val; + } + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; + } + return val; +}; + +exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; +exports.AwsJson1_0Protocol = AwsJson1_0Protocol; +exports.AwsJson1_1Protocol = AwsJson1_1Protocol; +exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; +exports.AwsQueryProtocol = AwsQueryProtocol; +exports.AwsRestJsonProtocol = AwsRestJsonProtocol; +exports.AwsRestXmlProtocol = AwsRestXmlProtocol; +exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonCodec2 = JsonCodec2; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeDeserializer2 = JsonShapeDeserializer2; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.JsonShapeSerializer2 = JsonShapeSerializer2; +exports.QueryShapeSerializer = QueryShapeSerializer; +exports.XmlCodec = XmlCodec; +exports.XmlShapeDeserializer = XmlShapeDeserializer; +exports.XmlShapeSerializer = XmlShapeSerializer; +exports._toBool = _toBool; +exports._toNum = _toNum; +exports._toStr = _toStr; +exports.awsExpectUnion = awsExpectUnion; +exports.loadJsonRpcErrorCode = loadJsonRpcErrorCode; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadRestXmlErrorCode = loadRestXmlErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.parseXmlBody = parseXmlBody; +exports.parseXmlErrorBody = parseXmlErrorBody; + + +/***/ }), + +/***/ 51275: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setCredentialFeature } = __webpack_require__(24491); +const { CredentialsProviderError } = __webpack_require__(68702); + +const ENV_KEY = "AWS_ACCESS_KEY_ID"; +const ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; +const ENV_SESSION = "AWS_SESSION_TOKEN"; +const ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; +const ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; +const ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; +const fromEnv = (init) => async () => { + init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...(sessionToken && { sessionToken }), + ...(expiry && { expiration: new Date(expiry) }), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; + } + throw new CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); +}; + +exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; +exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; +exports.ENV_EXPIRATION = ENV_EXPIRATION; +exports.ENV_KEY = ENV_KEY; +exports.ENV_SECRET = ENV_SECRET; +exports.ENV_SESSION = ENV_SESSION; +exports.fromEnv = fromEnv; + + +/***/ }), + +/***/ 93885: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setCredentialFeature } = __webpack_require__(24491); +const { CredentialsProviderError } = __webpack_require__(68702); +const { NodeHttpHandler } = __webpack_require__(60517); +const fs = __webpack_require__(51455); +const { HttpRequest } = __webpack_require__(62049); +const { sdkStreamMixin, parseRfc3339DateTime } = __webpack_require__(34129); + +const ECS_CONTAINER_HOST = "169.254.170.2"; +const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; +const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; +const checkUrl = (url, logger) => { + if (url.protocol === "https:") { + return; + } + if (url.hostname === ECS_CONTAINER_HOST || + url.hostname === EKS_CONTAINER_HOST_IPv4 || + url.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url.hostname.includes("[")) { + if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } + else { + if (url.hostname === "localhost") { + return; + } + const ipComponents = url.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && + inRange(ipComponents[1]) && + inRange(ipComponents[2]) && + inRange(ipComponents[3]) && + ipComponents.length === 4) { + return; + } + } + throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); +}; + +function createGetRequest(url) { + return new HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: Number(url.port), + path: url.pathname, + query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { + acc[k] = v; + return acc; + }, {}), + fragment: url.hash, + }); +} +async function getCredentials(response, logger) { + const stream = sdkStreamMixin(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || + typeof parsed.SecretAccessKey !== "string" || + typeof parsed.Token !== "string" || + typeof parsed.Expiration !== "string") { + throw new CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: parseRfc3339DateTime(parsed.Expiration), + }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } + catch (e) { } + throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { + Code: parsedBody.Code, + Message: parsedBody.Message, + }); + } + throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); +} + +const retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i = 0; i < maxRetries; ++i) { + try { + return await toRetry(); + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return await toRetry(); + }; +}; + +const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; +const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn + ? console.warn + : options.logger.warn.bind(options.logger); + if (relative && full) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsRelativeUri will take precedence."); + } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationTokenFile will take precedence."); + } + if (relative) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; + } + else if (full) { + host = full; + } + else { + throw new CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url = new URL(host); + checkUrl(url, options.logger); + const requestHandler = NodeHttpHandler.create({ connectionTimeout: options.timeout ?? 1000 }); + const requestTimeout = options.timeout ?? 1000; + const provider = retryWrapper(async () => { + const request = createGetRequest(url); + if (tokenFile) { + request.headers.Authorization = validateToken((await fs.readFile(tokenFile)).toString()); + } + else if (token) { + request.headers.Authorization = validateToken(token); + } + try { + const result = await requestHandler.handle(request, { requestTimeout }); + return getCredentials(result.response).then((creds) => setCredentialFeature(creds, "CREDENTIALS_HTTP", "z")); + } + catch (e) { + throw new CredentialsProviderError(String(e), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1000); + return async () => { + try { + return await provider(); + } + finally { + requestHandler.destroy?.(); + } + }; +}; +const validateToken = (token) => { + if (token.includes("\r\n")) { + throw new CredentialsProviderError("Authorization token contains invalid \\r\\n sequence."); + } + return token; +}; + +exports.fromHttp = fromHttp; + + +/***/ }), + +/***/ 74373: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { CredentialsProviderError, chain, getProfileName, parseKnownFiles } = __webpack_require__(68702); +const { setCredentialFeature } = __webpack_require__(24491); + +const resolveCredentialSource = (credentialSource, profileName, logger) => { + const sourceProvidersMap = { + EcsContainer: async (options) => { + const { fromHttp } = __webpack_require__(93885); + const { fromContainerMetadata } = __webpack_require__(99236); + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, + Ec2InstanceMetadata: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = __webpack_require__(99236); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, + Environment: async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = __webpack_require__(51275); + return async () => fromEnv(options)().then(setNamedProvider); + }, + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } + else { + throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` + + `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger }); + } +}; +const setNamedProvider = (creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); + +const isAssumeRoleProfile = (arg, { profile = "default", logger } = {}) => { + return (Boolean(arg) && + typeof arg === "object" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && + ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && + ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && + (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger }))); +}; +const isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + } + return withSourceProfile; +}; +const isCredentialSourceProfile = (arg, { profile, logger }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + } + return withProviderProfile; +}; +const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer } = __webpack_require__(18988); + options.roleAssumer = getDefaultRoleAssumer({ + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...callerClientConfig, + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region, + }, + }, options.clientPlugins); + } + if (source_profile && source_profile in visitedProfiles) { + throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` + + ` ${getProfileName(options)}. Profiles visited: ` + + Object.keys(visitedProfiles).join(", "), { logger: options.logger }); + } + options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); + const sourceCredsProvider = source_profile + ? resolveProfileData(source_profile, profiles, options, callerClientConfig, { + ...visitedProfiles, + [source_profile]: true, + }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) + : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } + else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10), + }; + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); + } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); + } + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } +}; +const isCredentialSourceWithoutRoleArn = (section) => { + return !section.role_arn && !!section.credential_source; +}; + +const isLoginProfile = (data) => { + return Boolean(data && data.login_session); +}; +const resolveLoginCredentials = async (profileName, options, callerClientConfig) => { + const { fromLoginCredentials } = __webpack_require__(25375); + const credentials = await fromLoginCredentials({ + ...options, + profile: profileName, + })({ callerClientConfig }); + return setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC"); +}; + +const isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; +const resolveProcessCredentials = async (options, profile) => { + const { fromProcess } = __webpack_require__(31283); + const credentials = await fromProcess({ + ...options, + profile, + })(); + return setCredentialFeature(credentials, "CREDENTIALS_PROFILE_PROCESS", "v"); +}; + +const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => { + const { fromSSO } = __webpack_require__(23382); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig, + })({ + callerClientConfig, + }).then((creds) => { + if (profileData.sso_session) { + return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } + else { + return setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + } + }); +}; +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const isStaticCredsProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.aws_access_key_id === "string" && + typeof arg.aws_secret_access_key === "string" && + ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && + ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; +const resolveStaticCredentials = async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }), + ...(profile.aws_account_id && { accountId: profile.aws_account_id }), + }; + return setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); +}; + +const isWebIdentityProfile = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.web_identity_token_file === "string" && + typeof arg.role_arn === "string" && + ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; +const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => { + const { fromTokenFile } = __webpack_require__(24244); + const credentials = await fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + })({ + callerClientConfig, + }); + return setCredentialFeature(credentials, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"); +}; + +const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData); + } + if (isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); + } + if (isWebIdentityProfile(data)) { + return resolveWebIdentityCredentials(data, options, callerClientConfig); + } + if (isProcessProfile(data)) { + return resolveProcessCredentials(options, profileName); + } + if (isSsoProfile(data)) { + return await resolveSsoCredentials(profileName, data, options, callerClientConfig); + } + if (isLoginProfile(data)) { + return resolveLoginCredentials(profileName, options, callerClientConfig); + } + throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); +}; + +const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await parseKnownFiles(init); + return resolveProfileData(getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }), profiles, init, callerClientConfig); +}; + +exports.fromIni = fromIni; + + +/***/ }), + +/***/ 25375: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setCredentialFeature } = __webpack_require__(24491); +const { CredentialsProviderError, parseKnownFiles, getProfileName } = __webpack_require__(68702); +const { HttpRequest } = __webpack_require__(62049); +const { createHash, createPrivateKey, createPublicKey, sign } = __webpack_require__(77598); +const { promises } = __webpack_require__(73024); +const { homedir } = __webpack_require__(48161); +const { dirname, join } = __webpack_require__(76760); + +class LoginCredentialsFetcher { + profileData; + init; + callerClientConfig; + static REFRESH_THRESHOLD = 5 * 60 * 1000; + constructor(profileData, init, callerClientConfig) { + this.profileData = profileData; + this.init = init; + this.callerClientConfig = callerClientConfig; + } + async loadCredentials() { + const token = await this.loadToken(); + if (!token) { + throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger }); + } + const accessToken = token.accessToken; + const now = Date.now(); + const expiryTime = new Date(accessToken.expiresAt).getTime(); + const timeUntilExpiry = expiryTime - now; + if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) { + return this.refresh(token); + } + return this.toCredentials(token.accessToken); + } + get logger() { + return this.init?.logger; + } + get loginSession() { + return this.profileData.login_session; + } + toCredentials(token) { + return { + accessKeyId: token.accessKeyId, + secretAccessKey: token.secretAccessKey, + sessionToken: token.sessionToken, + accountId: token.accountId, + expiration: new Date(token.expiresAt), + }; + } + async refresh(token) { + const diskToken = await this.loadToken().catch(() => token); + const now = Date.now(); + const diskExpiry = new Date(diskToken.accessToken.expiresAt).getTime(); + const tokenExpiry = new Date(token.accessToken.expiresAt).getTime(); + const freshToken = diskExpiry <= now && tokenExpiry > now ? token : diskToken; + const freshExpiry = new Date(freshToken.accessToken.expiresAt).getTime(); + if (freshExpiry - Date.now() > LoginCredentialsFetcher.REFRESH_THRESHOLD) { + return this.toCredentials(freshToken.accessToken); + } + const { SigninClient, CreateOAuth2TokenCommand } = __webpack_require__(32342); + const { logger, userAgentAppId } = this.callerClientConfig ?? {}; + const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; + }; + const requestHandler = isH2(this.callerClientConfig?.requestHandler) + ? undefined + : this.callerClientConfig?.requestHandler; + const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION; + const client = new SigninClient({ + credentials: { + accessKeyId: "", + secretAccessKey: "", + }, + region, + requestHandler, + logger, + userAgentAppId, + ...this.init?.clientConfig, + }); + this.createDPoPInterceptor(client.middlewareStack); + const commandInput = { + tokenInput: { + clientId: freshToken.clientId, + refreshToken: freshToken.refreshToken, + grantType: "refresh_token", + }, + }; + try { + const response = await client.send(new CreateOAuth2TokenCommand(commandInput)); + const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {}; + const { refreshToken, expiresIn } = response.tokenOutput ?? {}; + if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) { + throw new CredentialsProviderError("Token refresh response missing required fields", { + logger: this.logger, + tryNextLink: false, + }); + } + const expiresInMs = (expiresIn ?? 900) * 1000; + const expiration = new Date(Date.now() + expiresInMs); + const updatedToken = { + ...freshToken, + accessToken: { + ...freshToken.accessToken, + accessKeyId, + secretAccessKey, + sessionToken, + expiresAt: expiration.toISOString(), + }, + refreshToken, + }; + await this.saveToken(updatedToken); + return this.toCredentials(updatedToken.accessToken); + } + catch (error) { + if (error.name === "AccessDeniedException") { + const errorType = error.error; + let message; + switch (errorType) { + case "TOKEN_EXPIRED": + message = "Your session has expired. Please reauthenticate."; + break; + case "USER_CREDENTIALS_CHANGED": + message = + "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password."; + break; + case "INSUFFICIENT_PERMISSIONS": + message = + "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action."; + break; + default: + message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \`aws login\``; + } + throw new CredentialsProviderError(message, { + logger: this.logger, + tryNextLink: false, + }); + } + const tokenExpiry = new Date(freshToken.accessToken.expiresAt).getTime(); + if (tokenExpiry > Date.now()) { + this.logger?.warn?.(`Failed to refresh token: ${String(error)}. Using existing token until expiry.`); + return this.toCredentials(freshToken.accessToken); + } + throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger }); + } + } + async loadToken() { + const tokenFilePath = this.getTokenFilePath(); + try { + const tokenData = await promises.readFile(tokenFilePath, "utf8"); + const token = JSON.parse(tokenData); + const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k) => !token[k]); + if (!token.accessToken?.accountId) { + missingFields.push("accountId"); + } + if (missingFields.length > 0) { + throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, { + logger: this.logger, + tryNextLink: false, + }); + } + return token; + } + catch (error) { + throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, { + logger: this.logger, + tryNextLink: false, + }); + } + } + async saveToken(token) { + const tokenFilePath = this.getTokenFilePath(); + const directory = dirname(tokenFilePath); + try { + await promises.mkdir(directory, { recursive: true }); + } + catch (error) { + } + await promises.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8"); + } + getTokenFilePath() { + const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), ".aws", "login", "cache"); + const loginSessionBytes = Buffer.from(this.loginSession, "utf8"); + const loginSessionSha256 = createHash("sha256").update(loginSessionBytes).digest("hex"); + return join(directory, `${loginSessionSha256}.json`); + } + derToRawSignature(derSignature) { + let offset = 2; + if (derSignature[offset] !== 0x02) { + throw new Error("Invalid DER signature"); + } + offset++; + const rLength = derSignature[offset++]; + let r = derSignature.subarray(offset, offset + rLength); + offset += rLength; + if (derSignature[offset] !== 0x02) { + throw new Error("Invalid DER signature"); + } + offset++; + const sLength = derSignature[offset++]; + let s = derSignature.subarray(offset, offset + sLength); + r = r[0] === 0x00 ? r.subarray(1) : r; + s = s[0] === 0x00 ? s.subarray(1) : s; + const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]); + const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]); + return Buffer.concat([rPadded, sPadded]); + } + createDPoPInterceptor(middlewareStack) { + middlewareStack.add((next) => async (args) => { + if (HttpRequest.isInstance(args.request)) { + const request = args.request; + const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : ""}${request.path}`; + const dpop = await this.generateDpop(request.method, actualEndpoint); + request.headers = { + ...request.headers, + DPoP: dpop, + }; + } + return next(args); + }, { + step: "finalizeRequest", + name: "dpopInterceptor", + override: true, + }); + } + async generateDpop(method = "POST", endpoint) { + const token = await this.loadToken(); + try { + const privateKey = createPrivateKey({ + key: token.dpopKey, + format: "pem", + type: "sec1", + }); + const publicKey = createPublicKey(privateKey); + const publicDer = publicKey.export({ format: "der", type: "spki" }); + let pointStart = -1; + for (let i = 0; i < publicDer.length; i++) { + if (publicDer[i] === 0x04) { + pointStart = i; + break; + } + } + const x = publicDer.slice(pointStart + 1, pointStart + 33); + const y = publicDer.slice(pointStart + 33, pointStart + 65); + const header = { + alg: "ES256", + typ: "dpop+jwt", + jwk: { + kty: "EC", + crv: "P-256", + x: x.toString("base64url"), + y: y.toString("base64url"), + }, + }; + const payload = { + jti: crypto.randomUUID(), + htm: method, + htu: endpoint, + iat: Math.floor(Date.now() / 1000), + }; + const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const message = `${headerB64}.${payloadB64}`; + const asn1Signature = sign("sha256", Buffer.from(message), privateKey); + const rawSignature = this.derToRawSignature(asn1Signature); + const signatureB64 = rawSignature.toString("base64url"); + return `${message}.${signatureB64}`; + } + catch (error) { + throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false }); + } + } +} + +const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => { + init?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials"); + const profiles = await parseKnownFiles(init || {}); + const profileName = getProfileName({ + profile: init?.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile?.login_session) { + throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, { + tryNextLink: true, + logger: init?.logger, + }); + } + const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig); + const credentials = await fetcher.loadCredentials(); + return setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD"); +}; + +exports.fromLoginCredentials = fromLoginCredentials; + + +/***/ }), + +/***/ 83090: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { ENV_KEY, ENV_SECRET, fromEnv } = __webpack_require__(51275); +const { chain, CredentialsProviderError, ENV_PROFILE } = __webpack_require__(68702); + +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const remoteProvider = async (init) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = __webpack_require__(99236); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = __webpack_require__(93885); + return chain(fromHttp(init), fromContainerMetadata(init)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); + }; + } + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init); +}; + +function memoizeChain(providers, treatAsExpired) { + const chain = internalCreateChain(providers); + let activeLock; + let passiveLock; + let credentials; + let forceRefreshLock; + const provider = async (options) => { + if (options?.forceRefresh) { + if (!forceRefreshLock) { + forceRefreshLock = chain(options) + .then((c) => { + credentials = c; + }) + .finally(() => { + forceRefreshLock = undefined; + }); + } + await forceRefreshLock; + return credentials; + } + if (credentials?.expiration) { + if (credentials?.expiration?.getTime() < Date.now()) { + credentials = undefined; + } + } + if (activeLock) { + await activeLock; + } + else if (!credentials || treatAsExpired?.(credentials)) { + if (credentials) { + if (!passiveLock) { + passiveLock = chain(options) + .then((c) => { + credentials = c; + }) + .catch(() => { + }) + .finally(() => { + passiveLock = undefined; + }); + } + } + else { + activeLock = chain(options) + .then((c) => { + credentials = c; + }) + .finally(() => { + activeLock = undefined; + }); + return provider(options); + } + } + return credentials; + }; + return provider; +} +const internalCreateChain = (providers) => async (awsIdentityProperties) => { + let lastProviderError; + for (const provider of providers) { + try { + return await provider(awsIdentityProperties); + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +let multipleCredentialSourceWarningEmitted = false; +const defaultProvider = (init = {}) => memoizeChain([ + async () => { + const profile = init.profile ?? process.env[ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" + ? init.logger.warn.bind(init.logger) + : console.warn; + warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +`); + multipleCredentialSourceWarningEmitted = true; + } + } + throw new CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init.logger, + tryNextLink: true, + }); + } + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return fromEnv(init)(); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger }); + } + const { fromSSO } = __webpack_require__(23382); + return fromSSO(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = __webpack_require__(74373); + return fromIni(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = __webpack_require__(31283); + return fromProcess(init)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = __webpack_require__(24244); + return fromTokenFile(init)(awsIdentityProperties); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); + }, + async () => { + throw new CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger, + }); + }, +], credentialsTreatedAsExpired); +const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined; +const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; + +exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; +exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; +exports.defaultProvider = defaultProvider; + + +/***/ }), + +/***/ 31283: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { externalDataInterceptor, CredentialsProviderError, parseKnownFiles, getProfileName } = __webpack_require__(68702); +const { exec } = __webpack_require__(31421); +const { promisify } = __webpack_require__(57975); +const { setCredentialFeature } = __webpack_require__(24491); + +const getValidatedProcessCredentials = (profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); + } + if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data.Expiration) { + const currentTime = new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); + } + } + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; + } + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...(data.SessionToken && { sessionToken: data.SessionToken }), + ...(data.Expiration && { expiration: new Date(data.Expiration) }), + ...(data.CredentialScope && { credentialScope: data.CredentialScope }), + ...(accountId && { accountId }), + }; + setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}; + +const resolveProcessCredentials = async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== undefined) { + const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } + catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } + catch (error) { + throw new CredentialsProviderError(error.message, { logger }); + } + } + else { + throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + } + } + else { + throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger, + }); + } +}; + +const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await parseKnownFiles(init); + return resolveProcessCredentials(getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }), profiles, init.logger); +}; + +exports.fromProcess = fromProcess; + + +/***/ }), + +/***/ 23382: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { CredentialsProviderError, getSSOTokenFromFile, getProfileName, parseKnownFiles, loadSsoSessionData } = __webpack_require__(68702); +const { setCredentialFeature } = __webpack_require__(24491); +const { fromSso } = __webpack_require__(14119); + +const isSsoProfile = (arg) => arg && + (typeof arg.sso_start_url === "string" || + typeof arg.sso_account_id === "string" || + typeof arg.sso_session === "string" || + typeof arg.sso_region === "string" || + typeof arg.sso_role_name === "string"); + +const SHOULD_FAIL_CREDENTIAL_CHAIN = false; +const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await fromSso({ + profile, + filepath, + configFilepath, + ignoreCache, + clientConfig, + parentClientConfig, + logger, + })({ callerClientConfig }); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString(), + }; + } + catch (e) { + throw new CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + else { + try { + token = await getSSOTokenFromFile(ssoStartUrl); + } + catch (e) { + throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { accessToken } = token; + const { SSOClient, GetRoleCredentialsCommand } = __webpack_require__(61899); + const sso = ssoClient || + new SSOClient(Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion, + userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId, + })); + let ssoResp; + try { + ssoResp = await sso.send(new GetRoleCredentialsCommand({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken, + })); + } + catch (e) { + throw new CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger, + }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...(credentialScope && { credentialScope }), + ...(accountId && { accountId }), + }; + if (ssoSession) { + setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); + } + else { + setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + } + return credentials; +}; + +const validateSsoProfile = (profile, logger) => { + const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; + if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { + throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + + `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger }); + } + return profile; +}; + +const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await parseKnownFiles(init); + const profile = profiles[profileName]; + if (!profile) { + throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); + } + if (!isSsoProfile(profile)) { + throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger, + }); + } + if (profile?.sso_session) { + const ssoSessions = await loadSsoSessionData(init); + const session = ssoSessions[profile.sso_session]; + const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; + if (ssoRegion && ssoRegion !== session.sso_region) { + throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger, + }); + } + profile.sso_region = session.sso_region; + profile.sso_start_url = session.sso_start_url; + } + const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient: ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + callerClientConfig: init.callerClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } + else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + + '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init.logger }); + } + else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + callerClientConfig: init.callerClientConfig, + profile: profileName, + filepath: init.filepath, + configFilepath: init.configFilepath, + ignoreCache: init.ignoreCache, + logger: init.logger, + }); + } +}; + +exports.fromSSO = fromSSO; +exports.isSsoProfile = isSsoProfile; +exports.validateSsoProfile = validateSsoProfile; + + +/***/ }), + +/***/ 61899: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { GetRoleCredentialsCommand, SSOClient } = __webpack_require__(22207); +exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; +exports.SSOClient = SSOClient; + + +/***/ }), + +/***/ 24244: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setCredentialFeature } = __webpack_require__(24491); +const { CredentialsProviderError, externalDataInterceptor } = __webpack_require__(68702); +const { readFileSync } = __webpack_require__(73024); + +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = __webpack_require__(18988); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); +}; + +const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; +const ENV_ROLE_ARN = "AWS_ROLE_ARN"; +const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; +const fromTokenFile = (init = {}) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); + } + const credentials = await fromWebToken({ + ...init, + webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? + readFileSync(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(awsIdentityProperties); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + return credentials; +}; + +exports.fromTokenFile = fromTokenFile; +exports.fromWebToken = fromWebToken; + + +/***/ }), + +/***/ 31683: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { EventStreamCodec } = __webpack_require__(49458); +const { Transform, Readable, PassThrough, pipeline } = __webpack_require__(57075); + +class EventSigningTransformStream extends Transform { + priorSignature; + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + staticCredentials; + constructor(options) { + super({ + autoDestroy: true, + readableObjectMode: true, + writableObjectMode: true, + ...options, + }); + this.priorSignature = options.priorSignature; + this.eventStreamCodec = options.eventStreamCodec; + this.messageSigner = options.messageSigner; + this.systemClockOffsetProvider = options.systemClockOffsetProvider; + this.staticCredentials = options.credentials?.(); + } + async _transform(chunk, encoding, callback) { + try { + const now = new Date(Date.now() + (await this.systemClockOffsetProvider())); + const dateHeader = { + ":date": { type: "timestamp", value: now }, + }; + const signedMessage = await this.messageSigner.sign({ + message: { + body: chunk, + headers: dateHeader, + }, + priorSignature: this.priorSignature, + }, { + signingDate: now, + eventStreamCredentials: await this.staticCredentials, + }); + this.priorSignature = signedMessage.signature; + const serializedSigned = this.eventStreamCodec.encode({ + headers: { + ...dateHeader, + ":chunk-signature": { + type: "binary", + value: getSignatureBinary(signedMessage.signature), + }, + }, + body: chunk, + }); + this.push(serializedSigned); + return callback(); + } + catch (err) { + callback(err); + } + } +} +function getSignatureBinary(signature) { + const buf = Buffer.from(signature, "hex"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +} + +class EventStreamPayloadHandler { + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + credentials; + constructor(options) { + this.messageSigner = options.messageSigner; + this.eventStreamCodec = new EventStreamCodec(options.utf8Encoder, options.utf8Decoder); + this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; + this.credentials = options.credentials; + } + async handle(next, args, context = {}) { + const request = args.request; + const { body: payload, query } = request; + if (!(payload instanceof Readable)) { + throw new Error("Eventstream payload must be a Readable stream."); + } + request.body = new PassThrough({ + objectMode: true, + }); + const match = request.headers?.authorization?.match(/Signature=([\w]+)$/); + let priorSignature = match?.[1] ?? query?.["X-Amz-Signature"] ?? ""; + if (context.__staticSignature) { + priorSignature = ""; + } + const signingStream = new EventSigningTransformStream({ + priorSignature, + eventStreamCodec: this.eventStreamCodec, + messageSigner: await this.messageSigner(), + systemClockOffsetProvider: this.systemClockOffsetProvider, + credentials: this.credentials, + }); + let resolvePipeline; + const pipelineError = new Promise((resolve, reject) => { + resolvePipeline = () => resolve(undefined); + pipeline(payload, signingStream, request.body, (err) => { + if (err) { + reject(new Error(`Pipeline error in @aws-sdk/eventstream-handler-node: ${err.message}`, { cause: err })); + } + }); + }); + let result; + try { + result = await Promise.race([next(args), pipelineError]); + } + catch (e) { + request.body.end(); + throw e; + } + finally { + resolvePipeline(); + } + return result; + } +} + +const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); + +exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; + + +/***/ }), + +/***/ 72593: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { HttpRequest } = __webpack_require__(37015); + +function resolveEventStreamConfig(input) { + const eventSigner = input.signer; + const messageSigner = input.signer; + const newInput = Object.assign(input, { + eventSigner, + messageSigner, + }); + const eventStreamPayloadHandler = newInput.eventStreamPayloadHandlerProvider(newInput); + return Object.assign(newInput, { + eventStreamPayloadHandler, + }); +} + +const eventStreamHandlingMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) + return next(args); + return options.eventStreamPayloadHandler.handle(next, args, context); +}; +const eventStreamHandlingMiddlewareOptions = { + tags: ["EVENT_STREAM", "SIGNATURE", "HANDLE"], + name: "eventStreamHandlingMiddleware", + relation: "after", + toMiddleware: "awsAuthMiddleware", + override: true, +}; + +const eventStreamHeaderMiddleware = (next) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) + return next(args); + request.headers = { + ...request.headers, + "content-type": "application/vnd.amazon.eventstream", + "x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-EVENTS", + }; + return next({ + ...args, + request, + }); +}; +const eventStreamHeaderMiddlewareOptions = { + step: "build", + tags: ["EVENT_STREAM", "HEADER", "CONTENT_TYPE", "CONTENT_SHA256"], + name: "eventStreamHeaderMiddleware", + override: true, +}; + +const getEventStreamPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(eventStreamHandlingMiddleware(options), eventStreamHandlingMiddlewareOptions); + clientStack.add(eventStreamHeaderMiddleware, eventStreamHeaderMiddlewareOptions); + }, +}); + +exports.eventStreamHandlingMiddleware = eventStreamHandlingMiddleware; +exports.eventStreamHandlingMiddlewareOptions = eventStreamHandlingMiddlewareOptions; +exports.eventStreamHeaderMiddleware = eventStreamHeaderMiddleware; +exports.eventStreamHeaderMiddlewareOptions = eventStreamHeaderMiddlewareOptions; +exports.getEventStreamPlugin = getEventStreamPlugin; +exports.resolveEventStreamConfig = resolveEventStreamConfig; + + +/***/ }), + +/***/ 69779: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { formatUrl } = __webpack_require__(34699); +const { iterableToReadableStream, readableStreamToIterable, EventStreamCodec } = __webpack_require__(49458); +const { HttpResponse, HttpRequest } = __webpack_require__(37015); +const { fromBase64, fromHex } = __webpack_require__(26591); +const { FetchHttpHandler } = __webpack_require__(96363); + +const isWebSocketRequest = (request) => request.protocol === "ws:" || request.protocol === "wss:"; + +const DEFAULT_WS_CONNECTION_TIMEOUT_MS = 3000; +class WebSocketFetchHandler { + metadata = { + handlerProtocol: "websocket/h1.1", + }; + config = {}; + configPromise; + httpHandler; + sockets = {}; + static create(instanceOrOptions, httpHandler = new FetchHttpHandler()) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new WebSocketFetchHandler(instanceOrOptions, httpHandler); + } + constructor(options, httpHandler = new FetchHttpHandler()) { + this.httpHandler = httpHandler; + const setConfig = (opts) => { + this.config = { + ...(opts ?? {}), + }; + return this.config; + }; + if (typeof options === "function") { + this.config = {}; + this.configPromise = options().then((opts) => { + return setConfig(opts); + }); + } + else { + this.configPromise = Promise.resolve(setConfig(options)); + } + } + destroy() { + for (const [key, sockets] of Object.entries(this.sockets)) { + for (const socket of sockets) { + socket.close(1000, `Socket closed through destroy() call`); + } + delete this.sockets[key]; + } + } + async handle(request) { + this.config = await this.configPromise; + const { logger } = this.config; + if (!isWebSocketRequest(request)) { + logger?.debug?.(`@aws-sdk - ws fetching ${request.protocol}${request.hostname}${request.path}`); + return this.httpHandler.handle(request); + } + const url = formatUrl(request); + logger?.debug?.(`@aws-sdk - ws connecting ${url.split("?")[0]}`); + const socket = new WebSocket(url); + if (!this.sockets[url]) { + this.sockets[url] = []; + } + this.sockets[url].push(socket); + socket.binaryType = "arraybuffer"; + const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config; + await this.waitForReady(socket, connectionTimeout); + const { body } = request; + const bodyStream = getIterator(body); + const asyncIterable = this.connect(socket, bodyStream); + const outputPayload = toReadableStream(asyncIterable); + return { + response: new HttpResponse({ + statusCode: 200, + body: outputPayload, + }), + }; + } + updateHttpClientConfig(key, value) { + this.configPromise = this.configPromise.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + removeNotUsableSockets(url) { + this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState)); + } + waitForReady(socket, connectionTimeout) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + this.removeNotUsableSockets(socket.url); + reject({ + $metadata: { + httpStatusCode: 500, + websocketSynthetic500Error: true, + }, + }); + }, connectionTimeout); + socket.onopen = () => { + clearTimeout(timeout); + resolve(); + }; + }); + } + connect(socket, data) { + const messageQueue = []; + let pendingResolve = null; + let pendingReject = null; + const push = (item) => { + if (pendingResolve) { + if (item.error) { + pendingReject(item.error); + } + else { + pendingResolve({ done: item.done, value: item.value }); + } + pendingResolve = null; + pendingReject = null; + } + else { + messageQueue.push(item); + } + }; + socket.onmessage = (event) => { + const { data } = event; + if (typeof data === "string") { + push({ + done: false, + value: fromBase64(data), + }); + } + else { + push({ + done: false, + value: new Uint8Array(data), + }); + } + }; + socket.onerror = (event) => { + socket.close(); + push({ done: true, error: event }); + }; + socket.onclose = () => { + this.removeNotUsableSockets(socket.url); + push({ done: true }); + }; + const outputStream = { + [Symbol.asyncIterator]: () => ({ + async next() { + if (messageQueue.length > 0) { + const item = messageQueue.shift(); + if (item.error) { + throw item.error; + } + return { done: item.done, value: item.value }; + } + return new Promise((resolve, reject) => { + pendingResolve = resolve; + pendingReject = reject; + }); + }, + }), + }; + const send = async () => { + try { + for await (const chunk of data) { + if (socket.readyState >= WebSocket.CLOSING) { + break; + } + else { + socket.send(chunk); + } + } + } + catch (err) { + push({ + done: true, + error: err, + }); + } + finally { + socket.close(1000); + } + }; + send(); + return outputStream; + } +} +const getIterator = (stream) => { + if (stream[Symbol.asyncIterator]) { + return stream; + } + if (isReadableStream(stream)) { + return readableStreamToIterable(stream); + } + return { + [Symbol.asyncIterator]: async function* () { + yield stream; + }, + }; +}; +const toReadableStream = (asyncIterable) => typeof ReadableStream === "function" ? iterableToReadableStream(asyncIterable) : asyncIterable; +const isReadableStream = (payload) => typeof ReadableStream === "function" && payload instanceof ReadableStream; + +const websocketEndpointMiddleware = (config, options) => (next) => (args) => { + const { request } = args; + if (HttpRequest.isInstance(request) && + config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) { + request.protocol = "wss:"; + request.method = "GET"; + request.path = `${request.path}-websocket`; + const { headers } = request; + delete headers["content-type"]; + delete headers["x-amz-content-sha256"]; + for (const name of Object.keys(headers)) { + if (name.indexOf(options.headerPrefix) === 0) { + const chunkedName = name.replace(options.headerPrefix, ""); + request.query[chunkedName] = headers[name]; + } + } + if (headers["x-amz-user-agent"]) { + request.query["user-agent"] = headers["x-amz-user-agent"]; + } + request.headers = { host: headers.host ?? request.hostname }; + } + return next(args); +}; +const websocketEndpointMiddlewareOptions = { + name: "websocketEndpointMiddleware", + tags: ["WEBSOCKET", "EVENT_STREAM"], + relation: "after", + toMiddleware: "eventStreamHeaderMiddleware", + override: true, +}; + +const injectSessionIdMiddleware = () => (next) => async (args) => { + const requestParams = { + ...args.input, + }; + const response = await next(args); + const output = response.output; + if (requestParams.SessionId && output.SessionId == null) { + output.SessionId = requestParams.SessionId; + } + return response; +}; +const injectSessionIdMiddlewareOptions = { + step: "initialize", + name: "injectSessionIdMiddleware", + tags: ["WEBSOCKET", "EVENT_STREAM"], + override: true, +}; + +const getWebSocketPlugin = (config, options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions); + clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions); + }, +}); + +class WebsocketSignatureV4 { + signer; + constructor(options) { + this.signer = options.signer; + } + presign(originalRequest, options = {}) { + return this.signer.presign(originalRequest, options); + } + async sign(toSign, options) { + if (HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) { + const signedRequest = await this.signer.presign({ ...toSign, body: "" }, { + ...options, + expiresIn: 60, + unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host")), + }); + return { + ...signedRequest, + body: toSign.body, + }; + } + else { + return this.signer.sign(toSign, options); + } + } + signMessage(message, args) { + return this.signer.signMessage(message, args); + } +} + +const resolveWebSocketConfig = (input) => { + const { signer } = input; + return Object.assign(input, { + signer: async (authScheme) => { + const signerObj = await signer(authScheme); + if (validateSigner(signerObj)) { + return new WebsocketSignatureV4({ signer: signerObj }); + } + throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor."); + }, + }); +}; +const validateSigner = (signer) => !!signer; + +class EventSigningTransformStream extends TransformStream { + constructor(initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider, credentials) { + let priorSignature = initialSignature; + const staticCredentials = credentials?.(); + super({ + start() { }, + async transform(chunk, controller) { + try { + const now = new Date(Date.now() + (await systemClockOffsetProvider())); + const dateHeader = { + ":date": { type: "timestamp", value: now }, + }; + const signedMessage = await messageSigner.sign({ + message: { + body: chunk, + headers: dateHeader, + }, + priorSignature: priorSignature, + }, { + signingDate: now, + eventStreamCredentials: await staticCredentials, + }); + priorSignature = signedMessage.signature; + const serializedSigned = eventStreamCodec.encode({ + headers: { + ...dateHeader, + ":chunk-signature": { + type: "binary", + value: fromHex(signedMessage.signature), + }, + }, + body: chunk, + }); + controller.enqueue(serializedSigned); + } + catch (error) { + controller.error(error); + } + }, + }); + } +} + +class EventStreamPayloadHandler { + messageSigner; + eventStreamCodec; + systemClockOffsetProvider; + credentials; + constructor(options) { + this.messageSigner = options.messageSigner; + this.eventStreamCodec = new EventStreamCodec(options.utf8Encoder, options.utf8Decoder); + this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; + this.credentials = options.credentials; + } + async handle(next, args, context = {}) { + const request = args.request; + const { body: payload, headers, query } = request; + if (!(payload instanceof ReadableStream)) { + throw new Error("Eventstream payload must be a ReadableStream."); + } + const placeHolderStream = new TransformStream(); + request.body = placeHolderStream.readable; + const match = (headers?.authorization ?? "").match(/Signature=(\w+)$/); + let priorSignature = (match ?? [])[1] ?? (query && query["X-Amz-Signature"]) ?? ""; + if (context.__staticSignature) { + priorSignature = ""; + } + const signingStream = new EventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider, this.credentials); + payload.pipeThrough(signingStream).pipeThrough(placeHolderStream); + let result; + try { + result = await next(args); + } + catch (e) { + const p = payload.cancel?.(); + if (p instanceof Promise) { + p.catch(() => { }); + } + throw e; + } + return result; + } +} + +const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); + +exports.WebSocketFetchHandler = WebSocketFetchHandler; +exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; +exports.getWebSocketPlugin = getWebSocketPlugin; +exports.resolveWebSocketConfig = resolveWebSocketConfig; + + +/***/ }), + +/***/ 22571: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = __webpack_require__(82172); +const { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = __webpack_require__(89273); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(40417); +const { Command: $Command } = __webpack_require__(40417); +exports.$Command = $Command; +exports.__Client = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(48132); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(19564); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(37015); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(89368); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(31829); +const { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(17727); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(26591); +const { streamCollector, NodeHttpHandler } = __webpack_require__(60517); +const { AwsRestJsonProtocol } = __webpack_require__(37828); +const { Sha256 } = __webpack_require__(7629); + +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": + { + options.push(createSmithyApiNoAuthHttpAuthOption()); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.997.43"; +var packageInfo = { + version: version}; + +const k = "ref"; +const a = -1, b = true, c = "isSet", d = "PartitionResult", e = "booleanEquals", f = "getAttr", g = { [k]: "Endpoint" }, h = { [k]: d }, i = {}, j = [{ [k]: "Region" }]; +const _data = { + conditions: [ + [c, [g]], + [c, j], + ["aws.partition", j, d], + [e, [{ [k]: "UseFIPS" }, b]], + [e, [{ [k]: "UseDualStack" }, b]], + [e, [{ fn: f, argv: [h, "supportsDualStack"] }, b]], + [e, [{ fn: f, argv: [h, "supportsFIPS"] }, b]], + ["stringEquals", [{ fn: f, argv: [h, "name"] }, "aws-us-gov"]] + ], + results: [ + [a], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [g, i], + ["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://oidc.{Region}.amazonaws.com", i], + ["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "FIPS is enabled but this partition does not support FIPS"], + ["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "DualStack is enabled but this partition does not support DualStack"], + ["https://oidc.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 13, 3, + 1, 4, r + 12, + 2, 5, r + 12, + 3, 8, 6, + 4, 7, r + 11, + 5, r + 9, r + 10, + 4, 11, 9, + 6, 10, r + 8, + 7, r + 6, r + 7, + 5, 12, r + 5, + 6, r + 4, r + 5, + 3, r + 1, 14, + 4, r + 2, r + 3, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +class SSOOIDCServiceException extends ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOOIDCServiceException.prototype); + } +} + +class AccessDeniedException extends SSOOIDCServiceException { + name = "AccessDeniedException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class AuthorizationPendingException extends SSOOIDCServiceException { + name = "AuthorizationPendingException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class ExpiredTokenException extends SSOOIDCServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InternalServerException extends SSOOIDCServiceException { + name = "InternalServerException"; + $fault = "server"; + error; + error_description; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidClientException extends SSOOIDCServiceException { + name = "InvalidClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidGrantException extends SSOOIDCServiceException { + name = "InvalidGrantException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidRequestException extends SSOOIDCServiceException { + name = "InvalidRequestException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class InvalidScopeException extends SSOOIDCServiceException { + name = "InvalidScopeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class SlowDownException extends SSOOIDCServiceException { + name = "SlowDownException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnauthorizedClientException extends SSOOIDCServiceException { + name = "UnauthorizedClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnsupportedGrantTypeException extends SSOOIDCServiceException { + name = "UnsupportedGrantTypeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} + +const _ADE = "AccessDeniedException"; +const _APE = "AuthorizationPendingException"; +const _AT = "AccessToken"; +const _CS = "ClientSecret"; +const _CT = "CreateToken"; +const _CTR = "CreateTokenRequest"; +const _CTRr = "CreateTokenResponse"; +const _CV = "CodeVerifier"; +const _ETE = "ExpiredTokenException"; +const _ICE = "InvalidClientException"; +const _IGE = "InvalidGrantException"; +const _IRE = "InvalidRequestException"; +const _ISE = "InternalServerException"; +const _ISEn = "InvalidScopeException"; +const _IT = "IdToken"; +const _RT = "RefreshToken"; +const _SDE = "SlowDownException"; +const _UCE = "UnauthorizedClientException"; +const _UGTE = "UnsupportedGrantTypeException"; +const _aT = "accessToken"; +const _c = "client"; +const _cI = "clientId"; +const _cS = "clientSecret"; +const _cV = "codeVerifier"; +const _co = "code"; +const _dC = "deviceCode"; +const _e = "error"; +const _eI = "expiresIn"; +const _ed = "error_description"; +const _gT = "grantType"; +const _h = "http"; +const _hE = "httpError"; +const _iT = "idToken"; +const _r = "reason"; +const _rT = "refreshToken"; +const _rU = "redirectUri"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; +const _sc = "scope"; +const _se = "server"; +const _tT = "tokenType"; +const n0 = "com.amazonaws.ssooidc"; +const _s_registry = TypeRegistry.for(_s); +var SSOOIDCServiceException$ = [-3, _s, "SSOOIDCServiceException", 0, [], []]; +_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException); +const n0_registry = TypeRegistry.for(n0); +var AccessDeniedException$ = [-3, n0, _ADE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] +]; +n0_registry.registerError(AccessDeniedException$, AccessDeniedException); +var AuthorizationPendingException$ = [-3, n0, _APE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException); +var ExpiredTokenException$ = [-3, n0, _ETE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(ExpiredTokenException$, ExpiredTokenException); +var InternalServerException$ = [-3, n0, _ISE, + { [_e]: _se, [_hE]: 500 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InternalServerException$, InternalServerException); +var InvalidClientException$ = [-3, n0, _ICE, + { [_e]: _c, [_hE]: 401 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidClientException$, InvalidClientException); +var InvalidGrantException$ = [-3, n0, _IGE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidGrantException$, InvalidGrantException); +var InvalidRequestException$ = [-3, n0, _IRE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] +]; +n0_registry.registerError(InvalidRequestException$, InvalidRequestException); +var InvalidScopeException$ = [-3, n0, _ISEn, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidScopeException$, InvalidScopeException); +var SlowDownException$ = [-3, n0, _SDE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(SlowDownException$, SlowDownException); +var UnauthorizedClientException$ = [-3, n0, _UCE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException); +var UnsupportedGrantTypeException$ = [-3, n0, _UGTE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var AccessToken = [0, n0, _AT, 8, 0]; +var ClientSecret = [0, n0, _CS, 8, 0]; +var CodeVerifier = [0, n0, _CV, 8, 0]; +var IdToken = [0, n0, _IT, 8, 0]; +var RefreshToken = [0, n0, _RT, 8, 0]; +var CreateTokenRequest$ = [3, n0, _CTR, + 0, + [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV], + [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3 +]; +var CreateTokenResponse$ = [3, n0, _CTRr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] +]; +var CreateToken$ = [9, n0, _CT, + { [_h]: ["POST", "/token", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.ssooidc", + errorTypeRegistries, + version: "2019-06-10", + serviceTarget: "AWSSSOOIDCService", + }, + serviceId: config?.serviceId ?? "SSO OIDC", + sha256: config?.sha256 ?? Sha256, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOOIDCClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "AWSSSOOIDCService", "SSOOIDCClient", getEndpointPlugin); +const _ep0 = {}; +const _mw0 = (Command, cs, config, o) => []; + +class CreateTokenCommand extends command(_ep0, _mw0, "CreateToken", CreateToken$) { +} + +const commands = { + CreateTokenCommand, +}; +class SSOOIDC extends SSOOIDCClient { +} +createAggregatedClient(commands, SSOOIDC); + +const AccessDeniedExceptionReason = { + KMS_ACCESS_DENIED: "KMS_AccessDeniedException", +}; +const InvalidRequestExceptionReason = { + KMS_DISABLED_KEY: "KMS_DisabledException", + KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", + KMS_INVALID_STATE: "KMS_InvalidStateException", + KMS_KEY_NOT_FOUND: "KMS_NotFoundException", +}; + +exports.AccessDeniedException = AccessDeniedException; +exports.AccessDeniedException$ = AccessDeniedException$; +exports.AccessDeniedExceptionReason = AccessDeniedExceptionReason; +exports.AuthorizationPendingException = AuthorizationPendingException; +exports.AuthorizationPendingException$ = AuthorizationPendingException$; +exports.CreateToken$ = CreateToken$; +exports.CreateTokenCommand = CreateTokenCommand; +exports.CreateTokenRequest$ = CreateTokenRequest$; +exports.CreateTokenResponse$ = CreateTokenResponse$; +exports.ExpiredTokenException = ExpiredTokenException; +exports.ExpiredTokenException$ = ExpiredTokenException$; +exports.InternalServerException = InternalServerException; +exports.InternalServerException$ = InternalServerException$; +exports.InvalidClientException = InvalidClientException; +exports.InvalidClientException$ = InvalidClientException$; +exports.InvalidGrantException = InvalidGrantException; +exports.InvalidGrantException$ = InvalidGrantException$; +exports.InvalidRequestException = InvalidRequestException; +exports.InvalidRequestException$ = InvalidRequestException$; +exports.InvalidRequestExceptionReason = InvalidRequestExceptionReason; +exports.InvalidScopeException = InvalidScopeException; +exports.InvalidScopeException$ = InvalidScopeException$; +exports.SSOOIDC = SSOOIDC; +exports.SSOOIDCClient = SSOOIDCClient; +exports.SSOOIDCServiceException = SSOOIDCServiceException; +exports.SSOOIDCServiceException$ = SSOOIDCServiceException$; +exports.SlowDownException = SlowDownException; +exports.SlowDownException$ = SlowDownException$; +exports.UnauthorizedClientException = UnauthorizedClientException; +exports.UnauthorizedClientException$ = UnauthorizedClientException$; +exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException; +exports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$; +exports.errorTypeRegistries = errorTypeRegistries; + + +/***/ }), + +/***/ 32342: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = __webpack_require__(24491); +const { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = __webpack_require__(57255); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(20895); +const { Command: $Command } = __webpack_require__(20895); +exports.$Command = $Command; +exports.__Client = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(68702); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(93846); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(62049); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(26266); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(39875); +const { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(15302); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(34129); +const { streamCollector, NodeHttpHandler } = __webpack_require__(60517); +const { AwsRestJsonProtocol } = __webpack_require__(54765); +const { Sha256 } = __webpack_require__(95899); + +const defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "signin", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSigninHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateOAuth2Token": + { + options.push(createSmithyApiNoAuthHttpAuthOption()); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "signin", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.997.47"; +var packageInfo = { + version: version}; + +const s = "ref"; +const a = -1, b = false, c = true, d = "isSet", e = "booleanEquals", f = "coalesce", g = "PartitionResult", h = "stringEquals", i = "getAttr", j = "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}", k = { [s]: "Endpoint" }, l = { "fn": i, "argv": [{ [s]: g }, "name"] }, m = { [s]: "Region" }, n = { [s]: g }, o = { "authSchemes": [{ "name": "sigv4", "signingName": "signin", "signingRegion": "{Region}" }] }, p = {}, q = [m]; +const _data = { + conditions: [ + [d, q], + [e, [{ fn: f, argv: [{ [s]: "IsControlPlane" }, b] }, c]], + [d, [k]], + ["aws.partition", q, g], + [e, [{ [s]: "UseFIPS" }, c]], + [h, [l, "aws"]], + [e, [{ fn: f, argv: [{ [s]: "IsOAuthEndpoint" }, b] }, c]], + [e, [{ [s]: "UseDualStack" }, c]], + [h, [l, "aws-cn"]], + [h, [m, "us-gov-west-1"]], + [h, [l, "aws-us-gov"]], + [e, [{ fn: i, argv: [n, "supportsFIPS"] }, c]], + [h, [l, "aws-iso"]], + [h, [l, "aws-iso-b"]], + [h, [l, "aws-iso-f"]], + [h, [l, "aws-iso-e"]], + [h, [l, "aws-eusc"]], + [e, [{ fn: i, argv: [n, "supportsDualStack"] }, c]] + ], + results: [ + [a], + ["https://signin.{Region}.api.aws", o], + ["https://signin.{Region}.api.amazonwebservices.com.cn", o], + [j, o], + [a, "FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation."], + ["https://{Region}.oauth.signin.aws", o], + ["https://{Region}.signin.aws.amazon.com", p], + ["https://{Region}.signin.amazonaws.cn", p], + ["https://{Region}.signin.amazonaws-us-gov.com", p], + ["https://{Region}.signin.c2shome.ic.gov", p], + ["https://{Region}.signin.sc2shome.sgov.gov", p], + ["https://{Region}.signin.csphome.hci.ic.gov", p], + ["https://{Region}.signin.csphome.adc-e.uk", p], + ["https://{Region}.signin.amazonaws-eusc.eu", p], + ["https://signin-fips.amazonaws-us-gov.com", p], + ["https://{Region}.signin-fips.amazonaws-us-gov.com", p], + ["https://{Region}.signin.{PartitionResult#dnsSuffix}", p], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [k, p], + ["https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", p], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://signin-fips.{Region}.{PartitionResult#dnsSuffix}", p], + [a, "FIPS is enabled but this partition does not support FIPS"], + [j, p], + [a, "DualStack is enabled but this partition does not support DualStack"], + ["https://signin.{Region}.{PartitionResult#dnsSuffix}", p], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 6, 3, + 2, 36, 4, + 4, 5, r + 27, + 6, r + 4, r + 27, + 1, 29, 7, + 2, 36, 8, + 3, 9, 31, + 4, 22, 10, + 5, 19, 11, + 7, 21, 12, + 8, r + 7, 13, + 10, r + 8, 14, + 12, r + 9, 15, + 13, r + 10, 16, + 14, r + 11, 17, + 15, r + 12, 18, + 16, r + 13, r + 16, + 6, r + 5, 20, + 7, 21, r + 6, + 17, r + 24, r + 25, + 6, r + 4, 23, + 7, 27, 24, + 9, r + 14, 25, + 10, r + 15, 26, + 11, r + 22, r + 23, + 11, 28, r + 21, + 17, r + 20, r + 21, + 2, 35, 30, + 3, 39, 31, + 4, 32, r + 27, + 6, r + 4, 33, + 7, r + 27, 34, + 9, r + 14, r + 27, + 3, 39, 36, + 4, 38, 37, + 7, r + 18, r + 19, + 6, r + 4, r + 17, + 5, r + 1, 40, + 8, r + 2, r + 3, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "IsControlPlane", "IsOAuthEndpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +class SigninServiceException extends ServiceException { + static shapeId = "smithy.ts.sdk.synthetic.com.amazonaws.signin#SigninServiceException"; + constructor(options) { + super(options); + Object.setPrototypeOf(this, SigninServiceException.prototype); + } +} + +class AccessDeniedException extends SigninServiceException { + static shapeId = "com.amazonaws.signin#AccessDeniedException"; + name = "AccessDeniedException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + } +} +class InternalServerException extends SigninServiceException { + static shapeId = "com.amazonaws.signin#InternalServerException"; + name = "InternalServerException"; + $fault = "server"; + error; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + } +} +class TooManyRequestsError extends SigninServiceException { + static shapeId = "com.amazonaws.signin#TooManyRequestsError"; + name = "TooManyRequestsError"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "TooManyRequestsError", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsError.prototype); + this.error = opts.error; + } +} +class ValidationException extends SigninServiceException { + static shapeId = "com.amazonaws.signin#ValidationException"; + name = "ValidationException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + this.error = opts.error; + } +} + +const _ADE = "AccessDeniedException"; +const _AT = "AccessToken"; +const _COAT = "CreateOAuth2Token"; +const _COATR = "CreateOAuth2TokenRequest"; +const _COATRB = "CreateOAuth2TokenRequestBody"; +const _COATRBr = "CreateOAuth2TokenResponseBody"; +const _COATRr = "CreateOAuth2TokenResponse"; +const _COATWIAM = "CreateOAuth2TokenWithIAM"; +const _COATWIAMR = "CreateOAuth2TokenWithIAMRequest"; +const _COATWIAMRr = "CreateOAuth2TokenWithIAMResponse"; +const _ISE = "InternalServerException"; +const _OAAT = "OAuthAccessToken"; +const _RT = "RefreshToken"; +const _TMRE = "TooManyRequestsError"; +const _VE = "ValidationException"; +const _aKI = "accessKeyId"; +const _aT = "accessToken"; +const _at = "access_token"; +const _c = "client"; +const _cI = "clientId"; +const _cV = "codeVerifier"; +const _co = "code"; +const _e = "error"; +const _eI = "expiresIn"; +const _ei = "expires_in"; +const _gT = "grantType"; +const _gt = "grant_type"; +const _h = "http"; +const _hE = "httpError"; +const _iT = "idToken"; +const _jN = "jsonName"; +const _m = "message"; +const _r = "resource"; +const _rT = "refreshToken"; +const _rU = "redirectUri"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; +const _sAK = "secretAccessKey"; +const _sT = "sessionToken"; +const _se = "server"; +const _tI = "tokenInput"; +const _tO = "tokenOutput"; +const _tT = "tokenType"; +const _tt = "token_type"; +const n0 = "com.amazonaws.signin"; +const _s_registry = new TypeRegistry(_s); +var SigninServiceException$ = [-3, _s, "SigninServiceException", 0, [], []]; +_s_registry.registerError(SigninServiceException$, SigninServiceException); +const n0_registry = new TypeRegistry(n0); +var AccessDeniedException$ = [-3, n0, _ADE, + { [_e]: _c }, + [_e, _m], + [0, 0], 2 +]; +n0_registry.registerError(AccessDeniedException$, AccessDeniedException); +var InternalServerException$ = [-3, n0, _ISE, + { [_e]: _se, [_hE]: 500 }, + [_e, _m], + [0, 0], 2 +]; +n0_registry.registerError(InternalServerException$, InternalServerException); +var TooManyRequestsError$ = [-3, n0, _TMRE, + { [_e]: _c, [_hE]: 429 }, + [_e, _m], + [0, 0], 2 +]; +n0_registry.registerError(TooManyRequestsError$, TooManyRequestsError); +var ValidationException$ = [-3, n0, _VE, + { [_e]: _c, [_hE]: 400 }, + [_e, _m], + [0, 0], 2 +]; +n0_registry.registerError(ValidationException$, ValidationException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var OAuthAccessToken = [0, n0, _OAAT, 8, 0]; +var RefreshToken = [0, n0, _RT, 8, 0]; +var AccessToken$ = [3, n0, _AT, + 8, + [_aKI, _sAK, _sT], + [[0, { [_jN]: _aKI }], [0, { [_jN]: _sAK }], [0, { [_jN]: _sT }]], 3 +]; +var CreateOAuth2TokenRequest$ = [3, n0, _COATR, + 0, + [_tI], + [[() => CreateOAuth2TokenRequestBody$, 16]], 1 +]; +var CreateOAuth2TokenRequestBody$ = [3, n0, _COATRB, + 0, + [_cI, _gT, _co, _rU, _cV, _rT], + [[0, { [_jN]: _cI }], [0, { [_jN]: _gT }], 0, [0, { [_jN]: _rU }], [0, { [_jN]: _cV }], [() => RefreshToken, { [_jN]: _rT }]], 2 +]; +var CreateOAuth2TokenResponse$ = [3, n0, _COATRr, + 0, + [_tO], + [[() => CreateOAuth2TokenResponseBody$, 16]], 1 +]; +var CreateOAuth2TokenResponseBody$ = [3, n0, _COATRBr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [[() => AccessToken$, { [_jN]: _aT }], [0, { [_jN]: _tT }], [1, { [_jN]: _eI }], [() => RefreshToken, { [_jN]: _rT }], [0, { [_jN]: _iT }]], 4 +]; +var CreateOAuth2TokenWithIAMRequest$ = [3, n0, _COATWIAMR, + 0, + [_gT, _r], + [[0, { [_jN]: _gt }], 0], 2 +]; +var CreateOAuth2TokenWithIAMResponse$ = [3, n0, _COATWIAMRr, + 0, + [_aT, _tT, _eI], + [[() => OAuthAccessToken, { [_jN]: _at }], [0, { [_jN]: _tt }], [1, { [_jN]: _ei }]], 3 +]; +var CreateOAuth2Token$ = [9, n0, _COAT, + { [_h]: ["POST", "/v1/token", 200] }, () => CreateOAuth2TokenRequest$, () => CreateOAuth2TokenResponse$ +]; +var CreateOAuth2TokenWithIAM$ = [9, n0, _COATWIAM, + { [_h]: ["POST", "/v1/token?x-amz-client-auth-method=iam", 200] }, () => CreateOAuth2TokenWithIAMRequest$, () => CreateOAuth2TokenWithIAMResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2023-01-01", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.signin", + errorTypeRegistries, + version: "2023-01-01", + serviceTarget: "Signin", + }, + serviceId: config?.serviceId ?? "Signin", + sha256: config?.sha256 ?? Sha256, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SigninClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "Signin", "SigninClient", getEndpointPlugin); +const _ep0 = { + IsControlPlane: { type: "staticContextParams", value: false }, +}; +const _ep1 = { + IsOAuthEndpoint: { type: "staticContextParams", value: true }, +}; +const _mw0 = (Command, cs, config, o) => []; + +class CreateOAuth2TokenCommand extends command(_ep0, _mw0, "CreateOAuth2Token", CreateOAuth2Token$) { +} + +class CreateOAuth2TokenWithIAMCommand extends command(_ep1, _mw0, "CreateOAuth2TokenWithIAM", CreateOAuth2TokenWithIAM$) { +} + +const commands = { + CreateOAuth2TokenCommand, + CreateOAuth2TokenWithIAMCommand, +}; +class Signin extends SigninClient { +} +createAggregatedClient(commands, Signin); + +const OAuth2ErrorCode = { + AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED", + CONFLICT: "CONFLICT", + INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS", + INVALID_REQUEST: "INVALID_REQUEST", + RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND", + SERVER_ERROR: "server_error", + SERVICE_QUOTA_EXCEEDED: "SERVICE_QUOTA_EXCEEDED", + TOKEN_EXPIRED: "TOKEN_EXPIRED", + USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED", +}; + +exports.AccessDeniedException = AccessDeniedException; +exports.AccessDeniedException$ = AccessDeniedException$; +exports.AccessToken$ = AccessToken$; +exports.CreateOAuth2Token$ = CreateOAuth2Token$; +exports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand; +exports.CreateOAuth2TokenRequest$ = CreateOAuth2TokenRequest$; +exports.CreateOAuth2TokenRequestBody$ = CreateOAuth2TokenRequestBody$; +exports.CreateOAuth2TokenResponse$ = CreateOAuth2TokenResponse$; +exports.CreateOAuth2TokenResponseBody$ = CreateOAuth2TokenResponseBody$; +exports.CreateOAuth2TokenWithIAM$ = CreateOAuth2TokenWithIAM$; +exports.CreateOAuth2TokenWithIAMCommand = CreateOAuth2TokenWithIAMCommand; +exports.CreateOAuth2TokenWithIAMRequest$ = CreateOAuth2TokenWithIAMRequest$; +exports.CreateOAuth2TokenWithIAMResponse$ = CreateOAuth2TokenWithIAMResponse$; +exports.InternalServerException = InternalServerException; +exports.InternalServerException$ = InternalServerException$; +exports.OAuth2ErrorCode = OAuth2ErrorCode; +exports.Signin = Signin; +exports.SigninClient = SigninClient; +exports.SigninServiceException = SigninServiceException; +exports.SigninServiceException$ = SigninServiceException$; +exports.TooManyRequestsError = TooManyRequestsError; +exports.TooManyRequestsError$ = TooManyRequestsError$; +exports.ValidationException = ValidationException; +exports.ValidationException$ = ValidationException$; +exports.errorTypeRegistries = errorTypeRegistries; + + +/***/ }), + +/***/ 84623: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = __webpack_require__(24491); +const { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = __webpack_require__(57255); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(20895); +const { Command: $Command } = __webpack_require__(20895); +exports.$Command = $Command; +exports.__Client = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(68702); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(93846); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(62049); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(26266); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(39875); +const { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(15302); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(34129); +const { streamCollector, NodeHttpHandler } = __webpack_require__(60517); +const { AwsRestJsonProtocol } = __webpack_require__(54765); +const { Sha256 } = __webpack_require__(95899); + +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": + { + options.push(createSmithyApiNoAuthHttpAuthOption()); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.997.47"; +var packageInfo = { + version: version}; + +const k = "ref"; +const a = -1, b = true, c = "isSet", d = "PartitionResult", e = "booleanEquals", f = "getAttr", g = { [k]: "Endpoint" }, h = { [k]: d }, i = {}, j = [{ [k]: "Region" }]; +const _data = { + conditions: [ + [c, [g]], + [c, j], + ["aws.partition", j, d], + [e, [{ [k]: "UseFIPS" }, b]], + [e, [{ [k]: "UseDualStack" }, b]], + [e, [{ fn: f, argv: [h, "supportsDualStack"] }, b]], + [e, [{ fn: f, argv: [h, "supportsFIPS"] }, b]], + ["stringEquals", [{ fn: f, argv: [h, "name"] }, "aws-us-gov"]] + ], + results: [ + [a], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [g, i], + ["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://oidc.{Region}.amazonaws.com", i], + ["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "FIPS is enabled but this partition does not support FIPS"], + ["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "DualStack is enabled but this partition does not support DualStack"], + ["https://oidc.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 13, 3, + 1, 4, r + 12, + 2, 5, r + 12, + 3, 8, 6, + 4, 7, r + 11, + 5, r + 9, r + 10, + 4, 11, 9, + 6, 10, r + 8, + 7, r + 6, r + 7, + 5, 12, r + 5, + 6, r + 4, r + 5, + 3, r + 1, 14, + 4, r + 2, r + 3, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +class SSOOIDCServiceException extends ServiceException { + static shapeId = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc#SSOOIDCServiceException"; + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOOIDCServiceException.prototype); + } +} + +class AccessDeniedException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#AccessDeniedException"; + name = "AccessDeniedException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class AuthorizationPendingException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#AuthorizationPendingException"; + name = "AuthorizationPendingException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class ExpiredTokenException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#ExpiredTokenException"; + name = "ExpiredTokenException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InternalServerException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#InternalServerException"; + name = "InternalServerException"; + $fault = "server"; + error; + error_description; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidClientException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#InvalidClientException"; + name = "InvalidClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidGrantException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#InvalidGrantException"; + name = "InvalidGrantException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class InvalidRequestException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#InvalidRequestException"; + name = "InvalidRequestException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } +} +class InvalidScopeException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#InvalidScopeException"; + name = "InvalidScopeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class SlowDownException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#SlowDownException"; + name = "SlowDownException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnauthorizedClientException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#UnauthorizedClientException"; + name = "UnauthorizedClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} +class UnsupportedGrantTypeException extends SSOOIDCServiceException { + static shapeId = "com.amazonaws.ssooidc#UnsupportedGrantTypeException"; + name = "UnsupportedGrantTypeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +} + +const _ADE = "AccessDeniedException"; +const _APE = "AuthorizationPendingException"; +const _AT = "AccessToken"; +const _CS = "ClientSecret"; +const _CT = "CreateToken"; +const _CTR = "CreateTokenRequest"; +const _CTRr = "CreateTokenResponse"; +const _CV = "CodeVerifier"; +const _ETE = "ExpiredTokenException"; +const _ICE = "InvalidClientException"; +const _IGE = "InvalidGrantException"; +const _IRE = "InvalidRequestException"; +const _ISE = "InternalServerException"; +const _ISEn = "InvalidScopeException"; +const _IT = "IdToken"; +const _RT = "RefreshToken"; +const _SDE = "SlowDownException"; +const _UCE = "UnauthorizedClientException"; +const _UGTE = "UnsupportedGrantTypeException"; +const _aT = "accessToken"; +const _c = "client"; +const _cI = "clientId"; +const _cS = "clientSecret"; +const _cV = "codeVerifier"; +const _co = "code"; +const _dC = "deviceCode"; +const _e = "error"; +const _eI = "expiresIn"; +const _ed = "error_description"; +const _gT = "grantType"; +const _h = "http"; +const _hE = "httpError"; +const _iT = "idToken"; +const _r = "reason"; +const _rT = "refreshToken"; +const _rU = "redirectUri"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; +const _sc = "scope"; +const _se = "server"; +const _tT = "tokenType"; +const n0 = "com.amazonaws.ssooidc"; +const _s_registry = new TypeRegistry(_s); +var SSOOIDCServiceException$ = [-3, _s, "SSOOIDCServiceException", 0, [], []]; +_s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException); +const n0_registry = new TypeRegistry(n0); +var AccessDeniedException$ = [-3, n0, _ADE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] +]; +n0_registry.registerError(AccessDeniedException$, AccessDeniedException); +var AuthorizationPendingException$ = [-3, n0, _APE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException); +var ExpiredTokenException$ = [-3, n0, _ETE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(ExpiredTokenException$, ExpiredTokenException); +var InternalServerException$ = [-3, n0, _ISE, + { [_e]: _se, [_hE]: 500 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InternalServerException$, InternalServerException); +var InvalidClientException$ = [-3, n0, _ICE, + { [_e]: _c, [_hE]: 401 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidClientException$, InvalidClientException); +var InvalidGrantException$ = [-3, n0, _IGE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidGrantException$, InvalidGrantException); +var InvalidRequestException$ = [-3, n0, _IRE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] +]; +n0_registry.registerError(InvalidRequestException$, InvalidRequestException); +var InvalidScopeException$ = [-3, n0, _ISEn, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(InvalidScopeException$, InvalidScopeException); +var SlowDownException$ = [-3, n0, _SDE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(SlowDownException$, SlowDownException); +var UnauthorizedClientException$ = [-3, n0, _UCE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException); +var UnsupportedGrantTypeException$ = [-3, n0, _UGTE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] +]; +n0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var AccessToken = [0, n0, _AT, 8, 0]; +var ClientSecret = [0, n0, _CS, 8, 0]; +var CodeVerifier = [0, n0, _CV, 8, 0]; +var IdToken = [0, n0, _IT, 8, 0]; +var RefreshToken = [0, n0, _RT, 8, 0]; +var CreateTokenRequest$ = [3, n0, _CTR, + 0, + [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV], + [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], 3 +]; +var CreateTokenResponse$ = [3, n0, _CTRr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] +]; +var CreateToken$ = [9, n0, _CT, + { [_h]: ["POST", "/token", 200] }, () => CreateTokenRequest$, () => CreateTokenResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.ssooidc", + errorTypeRegistries, + version: "2019-06-10", + serviceTarget: "AWSSSOOIDCService", + }, + serviceId: config?.serviceId ?? "SSO OIDC", + sha256: config?.sha256 ?? Sha256, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOOIDCClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "AWSSSOOIDCService", "SSOOIDCClient", getEndpointPlugin); +const _ep0 = {}; +const _mw0 = (Command, cs, config, o) => []; + +class CreateTokenCommand extends command(_ep0, _mw0, "CreateToken", CreateToken$) { +} + +const commands = { + CreateTokenCommand, +}; +class SSOOIDC extends SSOOIDCClient { +} +createAggregatedClient(commands, SSOOIDC); + +const AccessDeniedExceptionReason = { + KMS_ACCESS_DENIED: "KMS_AccessDeniedException", +}; +const InvalidRequestExceptionReason = { + KMS_DISABLED_KEY: "KMS_DisabledException", + KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", + KMS_INVALID_STATE: "KMS_InvalidStateException", + KMS_KEY_NOT_FOUND: "KMS_NotFoundException", +}; + +exports.AccessDeniedException = AccessDeniedException; +exports.AccessDeniedException$ = AccessDeniedException$; +exports.AccessDeniedExceptionReason = AccessDeniedExceptionReason; +exports.AuthorizationPendingException = AuthorizationPendingException; +exports.AuthorizationPendingException$ = AuthorizationPendingException$; +exports.CreateToken$ = CreateToken$; +exports.CreateTokenCommand = CreateTokenCommand; +exports.CreateTokenRequest$ = CreateTokenRequest$; +exports.CreateTokenResponse$ = CreateTokenResponse$; +exports.ExpiredTokenException = ExpiredTokenException; +exports.ExpiredTokenException$ = ExpiredTokenException$; +exports.InternalServerException = InternalServerException; +exports.InternalServerException$ = InternalServerException$; +exports.InvalidClientException = InvalidClientException; +exports.InvalidClientException$ = InvalidClientException$; +exports.InvalidGrantException = InvalidGrantException; +exports.InvalidGrantException$ = InvalidGrantException$; +exports.InvalidRequestException = InvalidRequestException; +exports.InvalidRequestException$ = InvalidRequestException$; +exports.InvalidRequestExceptionReason = InvalidRequestExceptionReason; +exports.InvalidScopeException = InvalidScopeException; +exports.InvalidScopeException$ = InvalidScopeException$; +exports.SSOOIDC = SSOOIDC; +exports.SSOOIDCClient = SSOOIDCClient; +exports.SSOOIDCServiceException = SSOOIDCServiceException; +exports.SSOOIDCServiceException$ = SSOOIDCServiceException$; +exports.SlowDownException = SlowDownException; +exports.SlowDownException$ = SlowDownException$; +exports.UnauthorizedClientException = UnauthorizedClientException; +exports.UnauthorizedClientException$ = UnauthorizedClientException$; +exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException; +exports.UnsupportedGrantTypeException$ = UnsupportedGrantTypeException$; +exports.errorTypeRegistries = errorTypeRegistries; + + +/***/ }), + +/***/ 22207: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin } = __webpack_require__(24491); +const { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = __webpack_require__(57255); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(20895); +const { Command: $Command } = __webpack_require__(20895); +exports.$Command = $Command; +exports.__Client = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(68702); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(93846); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(62049); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(26266); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(39875); +const { resolveAwsSdkSigV4Config, AwsSdkSigV4Signer, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(15302); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(34129); +const { streamCollector, NodeHttpHandler } = __webpack_require__(60517); +const { AwsRestJsonProtocol } = __webpack_require__(54765); +const { Sha256 } = __webpack_require__(95899); + +const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": + { + options.push(createSmithyApiNoAuthHttpAuthOption()); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal", + }); +}; +const commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.997.47"; +var packageInfo = { + version: version}; + +const k = "ref"; +const a = -1, b = true, c = "isSet", d = "PartitionResult", e = "booleanEquals", f = "getAttr", g = { [k]: "Endpoint" }, h = { [k]: d }, i = {}, j = [{ [k]: "Region" }]; +const _data = { + conditions: [ + [c, [g]], + [c, j], + ["aws.partition", j, d], + [e, [{ [k]: "UseFIPS" }, b]], + [e, [{ [k]: "UseDualStack" }, b]], + [e, [{ fn: f, argv: [h, "supportsDualStack"] }, b]], + [e, [{ fn: f, argv: [h, "supportsFIPS"] }, b]], + ["stringEquals", [{ fn: f, argv: [h, "name"] }, "aws-us-gov"]] + ], + results: [ + [a], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [g, i], + ["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://portal.sso.{Region}.amazonaws.com", i], + ["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "FIPS is enabled but this partition does not support FIPS"], + ["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", i], + [a, "DualStack is enabled but this partition does not support DualStack"], + ["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", i], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 13, 3, + 1, 4, r + 12, + 2, 5, r + 12, + 3, 8, 6, + 4, 7, r + 11, + 5, r + 9, r + 10, + 4, 11, 9, + 6, 10, r + 8, + 7, r + 6, r + 7, + 5, 12, r + 5, + 6, r + 4, r + 5, + 3, r + 1, 14, + 4, r + 2, r + 3, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +class SSOServiceException extends ServiceException { + static shapeId = "smithy.ts.sdk.synthetic.com.amazonaws.sso#SSOServiceException"; + constructor(options) { + super(options); + Object.setPrototypeOf(this, SSOServiceException.prototype); + } +} + +class InvalidRequestException extends SSOServiceException { + static shapeId = "com.amazonaws.sso#InvalidRequestException"; + name = "InvalidRequestException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidRequestException.prototype); + } +} +class ResourceNotFoundException extends SSOServiceException { + static shapeId = "com.amazonaws.sso#ResourceNotFoundException"; + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +} +class TooManyRequestsException extends SSOServiceException { + static shapeId = "com.amazonaws.sso#TooManyRequestsException"; + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, TooManyRequestsException.prototype); + } +} +class UnauthorizedException extends SSOServiceException { + static shapeId = "com.amazonaws.sso#UnauthorizedException"; + name = "UnauthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, UnauthorizedException.prototype); + } +} + +const _ATT = "AccessTokenType"; +const _GRC = "GetRoleCredentials"; +const _GRCR = "GetRoleCredentialsRequest"; +const _GRCRe = "GetRoleCredentialsResponse"; +const _IRE = "InvalidRequestException"; +const _RC = "RoleCredentials"; +const _RNFE = "ResourceNotFoundException"; +const _SAKT = "SecretAccessKeyType"; +const _STT = "SessionTokenType"; +const _TMRE = "TooManyRequestsException"; +const _UE = "UnauthorizedException"; +const _aI = "accountId"; +const _aKI = "accessKeyId"; +const _aT = "accessToken"; +const _ai = "account_id"; +const _c = "client"; +const _e = "error"; +const _ex = "expiration"; +const _h = "http"; +const _hE = "httpError"; +const _hH = "httpHeader"; +const _hQ = "httpQuery"; +const _m = "message"; +const _rC = "roleCredentials"; +const _rN = "roleName"; +const _rn = "role_name"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sso"; +const _sAK = "secretAccessKey"; +const _sT = "sessionToken"; +const _xasbt = "x-amz-sso_bearer_token"; +const n0 = "com.amazonaws.sso"; +const _s_registry = new TypeRegistry(_s); +var SSOServiceException$ = [-3, _s, "SSOServiceException", 0, [], []]; +_s_registry.registerError(SSOServiceException$, SSOServiceException); +const n0_registry = new TypeRegistry(n0); +var InvalidRequestException$ = [-3, n0, _IRE, + { [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(InvalidRequestException$, InvalidRequestException); +var ResourceNotFoundException$ = [-3, n0, _RNFE, + { [_e]: _c, [_hE]: 404 }, + [_m], + [0] +]; +n0_registry.registerError(ResourceNotFoundException$, ResourceNotFoundException); +var TooManyRequestsException$ = [-3, n0, _TMRE, + { [_e]: _c, [_hE]: 429 }, + [_m], + [0] +]; +n0_registry.registerError(TooManyRequestsException$, TooManyRequestsException); +var UnauthorizedException$ = [-3, n0, _UE, + { [_e]: _c, [_hE]: 401 }, + [_m], + [0] +]; +n0_registry.registerError(UnauthorizedException$, UnauthorizedException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var AccessTokenType = [0, n0, _ATT, 8, 0]; +var SecretAccessKeyType = [0, n0, _SAKT, 8, 0]; +var SessionTokenType = [0, n0, _STT, 8, 0]; +var GetRoleCredentialsRequest$ = [3, n0, _GRCR, + 0, + [_rN, _aI, _aT], + [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3 +]; +var GetRoleCredentialsResponse$ = [3, n0, _GRCRe, + 0, + [_rC], + [[() => RoleCredentials$, 0]] +]; +var RoleCredentials$ = [3, n0, _RC, + 0, + [_aKI, _sAK, _sT, _ex], + [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1] +]; +var GetRoleCredentials$ = [9, n0, _GRC, + { [_h]: ["GET", "/federation/credentials", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.sso", + errorTypeRegistries, + version: "2019-06-10", + serviceTarget: "SWBPortalService", + }, + serviceId: config?.serviceId ?? "SSO", + sha256: config?.sha256 ?? Sha256, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class SSOClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "SWBPortalService", "SSOClient", getEndpointPlugin); +const _ep0 = {}; +const _mw0 = (Command, cs, config, o) => []; + +class GetRoleCredentialsCommand extends command(_ep0, _mw0, "GetRoleCredentials", GetRoleCredentials$) { +} + +const commands = { + GetRoleCredentialsCommand, +}; +class SSO extends SSOClient { +} +createAggregatedClient(commands, SSO); + +exports.GetRoleCredentials$ = GetRoleCredentials$; +exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; +exports.GetRoleCredentialsRequest$ = GetRoleCredentialsRequest$; +exports.GetRoleCredentialsResponse$ = GetRoleCredentialsResponse$; +exports.InvalidRequestException = InvalidRequestException; +exports.InvalidRequestException$ = InvalidRequestException$; +exports.ResourceNotFoundException = ResourceNotFoundException; +exports.ResourceNotFoundException$ = ResourceNotFoundException$; +exports.RoleCredentials$ = RoleCredentials$; +exports.SSO = SSO; +exports.SSOClient = SSOClient; +exports.SSOServiceException = SSOServiceException; +exports.SSOServiceException$ = SSOServiceException$; +exports.TooManyRequestsException = TooManyRequestsException; +exports.TooManyRequestsException$ = TooManyRequestsException$; +exports.UnauthorizedException = UnauthorizedException; +exports.UnauthorizedException$ = UnauthorizedException$; +exports.errorTypeRegistries = errorTypeRegistries; + + +/***/ }), + +/***/ 18988: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { awsEndpointFunctions, emitWarningIfUnsupportedVersion: emitWarningIfUnsupportedVersion$1, createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS, getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, resolveUserAgentConfig, resolveHostHeaderConfig, getUserAgentPlugin, getHostHeaderPlugin, getLoggerPlugin, getRecursionDetectionPlugin, setCredentialFeature, stsRegionDefaultResolver } = __webpack_require__(24491); +const { NoAuthSigner, getHttpAuthSchemeEndpointRuleSetPlugin, DefaultIdentityProviderConfig, getHttpSigningPlugin } = __webpack_require__(57255); +const { normalizeProvider, getSmithyContext, ServiceException, NoOpLogger, emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode, getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig, Client, makeBuilder, createAggregatedClient } = __webpack_require__(20895); +const { Command: $Command } = __webpack_require__(20895); +exports.$Command = $Command; +exports.__Client = Client; +const { resolveDefaultsModeConfig, loadConfig, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, resolveRegionConfig } = __webpack_require__(68702); +const { BinaryDecisionDiagram, EndpointCache, decideEndpoint, customEndpointFunctions, resolveParams, resolveEndpointConfig, getEndpointPlugin } = __webpack_require__(93846); +const { parseUrl, getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig, getContentLengthPlugin } = __webpack_require__(62049); +const { DEFAULT_RETRY_MODE, NODE_RETRY_MODE_CONFIG_OPTIONS, NODE_MAX_ATTEMPT_CONFIG_OPTIONS, resolveRetryConfig, getRetryPlugin } = __webpack_require__(26266); +const { TypeRegistry, getSchemaSerdePlugin } = __webpack_require__(39875); +const { resolveAwsSdkSigV4Config, resolveAwsSdkSigV4AConfig, AwsSdkSigV4Signer, AwsSdkSigV4ASigner, NODE_SIGV4A_CONFIG_OPTIONS, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } = __webpack_require__(15302); +const { SignatureV4MultiRegion } = __webpack_require__(92062); +const { toUtf8, fromUtf8, toBase64, fromBase64, calculateBodyLength } = __webpack_require__(34129); +const { streamCollector, NodeHttpHandler } = __webpack_require__(60517); +const { AwsQueryProtocol } = __webpack_require__(54765); +const { Sha256 } = __webpack_require__(95899); + +const q = "ref"; +const a = -1, b = true, c = "isSet", d = "PartitionResult", e = "booleanEquals", f = "stringEquals", g = "getAttr", h = "us-east-1", i = "sigv4", j = "sts", k = "https://sts.{Region}.{PartitionResult#dnsSuffix}", l = { [q]: "Endpoint" }, m = { [q]: "Region" }, n = { [q]: d }, o = {}, p = [m]; +const _data = { + conditions: [ + [c, [l]], + [c, p], + ["aws.partition", p, d], + [e, [{ [q]: "UseFIPS" }, b]], + [e, [{ [q]: "UseDualStack" }, b]], + [f, [m, "aws-global"]], + [e, [{ [q]: "UseGlobalEndpoint" }, b]], + [f, [m, "eu-central-1"]], + [e, [{ fn: g, argv: [n, "supportsDualStack"] }, b]], + [e, [{ fn: g, argv: [n, "supportsFIPS"] }, b]], + [f, [m, "ap-south-1"]], + [f, [m, "eu-north-1"]], + [f, [m, "eu-west-1"]], + [f, [m, "eu-west-2"]], + [f, [m, "eu-west-3"]], + [f, [m, "sa-east-1"]], + [f, [m, h]], + [f, [m, "us-east-2"]], + [f, [m, "us-west-2"]], + [f, [m, "us-west-1"]], + [f, [m, "ca-central-1"]], + [f, [m, "ap-southeast-1"]], + [f, [m, "ap-northeast-1"]], + [f, [m, "ap-southeast-2"]], + [f, [{ fn: g, argv: [n, "name"] }, "aws-us-gov"]] + ], + results: [ + [a], + ["https://sts.amazonaws.com", { authSchemes: [{ name: i, signingName: j, signingRegion: h }] }], + [k, { authSchemes: [{ name: i, signingName: j, signingRegion: "{Region}" }] }], + [a, "Invalid Configuration: FIPS and custom endpoint are not supported"], + [a, "Invalid Configuration: Dualstack and custom endpoint are not supported"], + [l, o], + ["https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", o], + [a, "FIPS and DualStack are enabled, but this partition does not support one or both"], + ["https://sts.{Region}.amazonaws.com", o], + ["https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", o], + [a, "FIPS is enabled but this partition does not support FIPS"], + ["https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", o], + [a, "DualStack is enabled but this partition does not support DualStack"], + [k, o], + [a, "Invalid Configuration: Missing Region"] + ] +}; +const root = 2; +const r = 100_000_000; +const nodes = new Int32Array([ + -1, 1, -1, + 0, 30, 3, + 1, 4, r + 14, + 2, 5, r + 14, + 3, 25, 6, + 4, 24, 7, + 5, r + 1, 8, + 6, 9, r + 13, + 7, r + 1, 10, + 10, r + 1, 11, + 11, r + 1, 12, + 12, r + 1, 13, + 13, r + 1, 14, + 14, r + 1, 15, + 15, r + 1, 16, + 16, r + 1, 17, + 17, r + 1, 18, + 18, r + 1, 19, + 19, r + 1, 20, + 20, r + 1, 21, + 21, r + 1, 22, + 22, r + 1, 23, + 23, r + 1, r + 2, + 8, r + 11, r + 12, + 4, 28, 26, + 9, 27, r + 10, + 24, r + 8, r + 9, + 8, 29, r + 7, + 9, r + 6, r + 7, + 3, r + 3, 31, + 4, r + 4, r + 5, +]); +const bdd = BinaryDecisionDiagram.from(nodes, root, _data.conditions, _data.results); + +const cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => decideEndpoint(bdd, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +customEndpointFunctions.aws = awsEndpointFunctions; + +const createEndpointRuleSetHttpAuthSchemeParametersProvider = (defaultHttpAuthSchemeParametersProvider) => async (config, context, input) => { + if (!input) { + throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`"); + } + const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config, context, input); + const instructionsFn = getSmithyContext(context)?.commandInstance?.constructor + ?.getEndpointParameterInstructions; + if (!instructionsFn) { + throw new Error(`getEndpointParameterInstructions() is not defined on '${context.commandName}'`); + } + const endpointParameters = await resolveParams(input, { getEndpointParameterInstructions: instructionsFn }, config); + return Object.assign(defaultParameters, endpointParameters); +}; +const _defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +const defaultSTSHttpAuthSchemeParametersProvider = createEndpointRuleSetHttpAuthSchemeParametersProvider(_defaultSTSHttpAuthSchemeParametersProvider); +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createAwsAuthSigv4aHttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4a", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const createEndpointRuleSetHttpAuthSchemeProvider = (defaultEndpointResolver, defaultHttpAuthSchemeResolver, createHttpAuthOptionFunctions) => { + const endpointRuleSetHttpAuthSchemeProvider = (authParameters) => { + const endpoint = defaultEndpointResolver(authParameters); + const authSchemes = endpoint.properties?.authSchemes; + if (!authSchemes) { + return defaultHttpAuthSchemeResolver(authParameters); + } + const options = []; + for (const scheme of authSchemes) { + const { name: resolvedName, properties = {}, ...rest } = scheme; + const name = resolvedName.toLowerCase(); + if (resolvedName !== name) { + console.warn(`HttpAuthScheme has been normalized with lowercasing: '${resolvedName}' to '${name}'`); + } + let schemeId; + if (name === "sigv4a") { + schemeId = "aws.auth#sigv4a"; + const sigv4Present = authSchemes.find((s) => { + const name = s.name.toLowerCase(); + return name !== "sigv4a" && name.startsWith("sigv4"); + }); + if (SignatureV4MultiRegion.sigv4aDependency() === "none" && sigv4Present) { + continue; + } + } + else if (name.startsWith("sigv4")) { + schemeId = "aws.auth#sigv4"; + } + else { + throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${name}'`); + } + const createOption = createHttpAuthOptionFunctions[schemeId]; + if (!createOption) { + throw new Error(`Could not find HttpAuthOption create function for '${schemeId}'`); + } + const option = createOption(authParameters); + option.schemeId = schemeId; + option.signingProperties = { ...(option.signingProperties || {}), ...rest, ...properties }; + options.push(option); + } + return options; + }; + return endpointRuleSetHttpAuthSchemeProvider; +}; +const _defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption()); + options.push(createAwsAuthSigv4aHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + options.push(createAwsAuthSigv4aHttpAuthOption(authParameters)); + } + } + return options; +}; +const defaultSTSHttpAuthSchemeProvider = createEndpointRuleSetHttpAuthSchemeProvider(defaultEndpointResolver, _defaultSTSHttpAuthSchemeProvider, { + "aws.auth#sigv4": createAwsAuthSigv4HttpAuthOption, + "aws.auth#sigv4a": createAwsAuthSigv4aHttpAuthOption, + "smithy.api#noAuth": createSmithyApiNoAuthHttpAuthOption, +}); +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + const config_1 = resolveAwsSdkSigV4AConfig(config_0); + return Object.assign(config_1, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []), + }); +}; + +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +const commonParams = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, +}; + +var version = "3.997.47"; +var packageInfo = { + version: version}; + +class STSServiceException extends ServiceException { + static shapeId = "smithy.ts.sdk.synthetic.com.amazonaws.sts#STSServiceException"; + constructor(options) { + super(options); + Object.setPrototypeOf(this, STSServiceException.prototype); + } +} + +class ExpiredTokenException extends STSServiceException { + static shapeId = "com.amazonaws.sts#ExpiredTokenException"; + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ExpiredTokenException.prototype); + } +} +class MalformedPolicyDocumentException extends STSServiceException { + static shapeId = "com.amazonaws.sts#MalformedPolicyDocumentException"; + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); + } +} +class PackedPolicyTooLargeException extends STSServiceException { + static shapeId = "com.amazonaws.sts#PackedPolicyTooLargeException"; + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); + } +} +class RegionDisabledException extends STSServiceException { + static shapeId = "com.amazonaws.sts#RegionDisabledException"; + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, RegionDisabledException.prototype); + } +} +class IDPRejectedClaimException extends STSServiceException { + static shapeId = "com.amazonaws.sts#IDPRejectedClaimException"; + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); + } +} +class InvalidIdentityTokenException extends STSServiceException { + static shapeId = "com.amazonaws.sts#InvalidIdentityTokenException"; + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); + } +} +class IDPCommunicationErrorException extends STSServiceException { + static shapeId = "com.amazonaws.sts#IDPCommunicationErrorException"; + name = "IDPCommunicationErrorException"; + $fault = "client"; + $retryable = {}; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); + } +} + +const _A = "Arn"; +const _AKI = "AccessKeyId"; +const _AR = "AssumeRole"; +const _ARI = "AssumedRoleId"; +const _ARR = "AssumeRoleRequest"; +const _ARRs = "AssumeRoleResponse"; +const _ARU = "AssumedRoleUser"; +const _ARWWI = "AssumeRoleWithWebIdentity"; +const _ARWWIR = "AssumeRoleWithWebIdentityRequest"; +const _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; +const _Au = "Audience"; +const _C = "Credentials"; +const _CA = "ContextAssertion"; +const _DS = "DurationSeconds"; +const _E = "Expiration"; +const _EI = "ExternalId"; +const _ETE = "ExpiredTokenException"; +const _IDPCEE = "IDPCommunicationErrorException"; +const _IDPRCE = "IDPRejectedClaimException"; +const _IITE = "InvalidIdentityTokenException"; +const _K = "Key"; +const _MPDE = "MalformedPolicyDocumentException"; +const _MSTS = "MinimumSessionTokenSize"; +const _P = "Policy"; +const _PA = "PolicyArns"; +const _PAr = "ProviderArn"; +const _PC = "ProvidedContexts"; +const _PCLT = "ProvidedContextsListType"; +const _PCr = "ProvidedContext"; +const _PDT = "PolicyDescriptorType"; +const _PI = "ProviderId"; +const _PPS = "PackedPolicySize"; +const _PPTLE = "PackedPolicyTooLargeException"; +const _Pr = "Provider"; +const _RA = "RoleArn"; +const _RDE = "RegionDisabledException"; +const _RSN = "RoleSessionName"; +const _SAK = "SecretAccessKey"; +const _SFWIT = "SubjectFromWebIdentityToken"; +const _SI = "SourceIdentity"; +const _SN = "SerialNumber"; +const _ST = "SessionToken"; +const _STS = "SessionTokenSize"; +const _STU = "SessionTokenUtilization"; +const _T = "Tags"; +const _TC = "TokenCode"; +const _TTK = "TransitiveTagKeys"; +const _Ta = "Tag"; +const _V = "Value"; +const _WIT = "WebIdentityToken"; +const _a = "arn"; +const _aKST = "accessKeySecretType"; +const _aQE = "awsQueryError"; +const _c = "client"; +const _cTT = "clientTokenType"; +const _e = "error"; +const _hE = "httpError"; +const _m = "message"; +const _pDLT = "policyDescriptorListType"; +const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; +const _tLT = "tagListType"; +const n0 = "com.amazonaws.sts"; +const _s_registry = new TypeRegistry(_s); +var STSServiceException$ = [-3, _s, "STSServiceException", 0, [], []]; +_s_registry.registerError(STSServiceException$, STSServiceException); +const n0_registry = new TypeRegistry(n0); +var ExpiredTokenException$ = [-3, n0, _ETE, + { [_aQE]: [`ExpiredTokenException`, 400], [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(ExpiredTokenException$, ExpiredTokenException); +var IDPCommunicationErrorException$ = [-3, n0, _IDPCEE, + { [_aQE]: [`IDPCommunicationError`, 400], [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException); +var IDPRejectedClaimException$ = [-3, n0, _IDPRCE, + { [_aQE]: [`IDPRejectedClaim`, 403], [_e]: _c, [_hE]: 403 }, + [_m], + [0] +]; +n0_registry.registerError(IDPRejectedClaimException$, IDPRejectedClaimException); +var InvalidIdentityTokenException$ = [-3, n0, _IITE, + { [_aQE]: [`InvalidIdentityToken`, 400], [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException); +var MalformedPolicyDocumentException$ = [-3, n0, _MPDE, + { [_aQE]: [`MalformedPolicyDocument`, 400], [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException); +var PackedPolicyTooLargeException$ = [-3, n0, _PPTLE, + { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e]: _c, [_hE]: 400 }, + [_m], + [0] +]; +n0_registry.registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException); +var RegionDisabledException$ = [-3, n0, _RDE, + { [_aQE]: [`RegionDisabledException`, 403], [_e]: _c, [_hE]: 403 }, + [_m], + [0] +]; +n0_registry.registerError(RegionDisabledException$, RegionDisabledException); +const errorTypeRegistries = [ + _s_registry, + n0_registry, +]; +var accessKeySecretType = [0, n0, _aKST, 8, 0]; +var clientTokenType = [0, n0, _cTT, 8, 0]; +var AssumedRoleUser$ = [3, n0, _ARU, + 0, + [_ARI, _A], + [0, 0], 2 +]; +var AssumeRoleRequest$ = [3, n0, _ARR, + 0, + [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC, _MSTS], + [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType, 1], 2 +]; +var AssumeRoleResponse$ = [3, n0, _ARRs, + 0, + [_C, _ARU, _PPS, _SI, _STU, _STS], + [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0, 1, 1] +]; +var AssumeRoleWithWebIdentityRequest$ = [3, n0, _ARWWIR, + 0, + [_RA, _RSN, _WIT, _PI, _PA, _P, _DS, _MSTS], + [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1, 1], 3 +]; +var AssumeRoleWithWebIdentityResponse$ = [3, n0, _ARWWIRs, + 0, + [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI, _STU, _STS], + [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0, 1, 1] +]; +var Credentials$ = [3, n0, _C, + 0, + [_AKI, _SAK, _ST, _E], + [0, [() => accessKeySecretType, 0], 0, 4], 4 +]; +var PolicyDescriptorType$ = [3, n0, _PDT, + 0, + [_a], + [0] +]; +var ProvidedContext$ = [3, n0, _PCr, + 0, + [_PAr, _CA], + [0, 0] +]; +var Tag$ = [3, n0, _Ta, + 0, + [_K, _V], + [0, 0], 2 +]; +var policyDescriptorListType = [1, n0, _pDLT, + 0, () => PolicyDescriptorType$ +]; +var ProvidedContextsListType = [1, n0, _PCLT, + 0, () => ProvidedContext$ +]; +var tagListType = [1, n0, _tLT, + 0, () => Tag$ +]; +var AssumeRole$ = [9, n0, _AR, + 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$ +]; +var AssumeRoleWithWebIdentity$ = [9, n0, _ARWWI, + 0, () => AssumeRoleWithWebIdentityRequest$, () => AssumeRoleWithWebIdentityResponse$ +]; + +const getRuntimeConfig$1 = (config) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "aws.auth#sigv4a", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), + signer: new AwsSdkSigV4ASigner(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsQueryProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.sts", + errorTypeRegistries, + xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", + version: "2011-06-15", + serviceTarget: "AWSSecurityTokenServiceV20110615", + }, + serviceId: config?.serviceId ?? "STS", + sha256: config?.sha256 ?? Sha256, + signerConstructor: config?.signerConstructor ?? SignatureV4MultiRegion, + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, + }; +}; + +const getRuntimeConfig = (config) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig$1(config); + emitWarningIfUnsupportedVersion$1(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new AwsSdkSigV4Signer(), + }, + { + schemeId: "aws.auth#sigv4a", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), + signer: new AwsSdkSigV4ASigner(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? + loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }, config), + sigv4aSigningRegionSet: config?.sigv4aSigningRegionSet ?? loadConfig(NODE_SIGV4A_CONFIG_OPTIONS, loaderConfig), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; + +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; + +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +class STSClient extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + "aws.auth#sigv4a": config.credentials, + }), + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +const command = makeBuilder(commonParams, "AWSSecurityTokenServiceV20110615", "STSClient", getEndpointPlugin); +const _ep0 = {}; +const _mw0 = (Command, cs, config, o) => []; + +class AssumeRoleCommand extends command(_ep0, _mw0, "AssumeRole", AssumeRole$) { +} + +class AssumeRoleWithWebIdentityCommand extends command(_ep0, _mw0, "AssumeRoleWithWebIdentity", AssumeRoleWithWebIdentity$) { +} + +const commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand, +}; +class STS extends STSClient { +} +createAggregatedClient(commands, STS); + +const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } + } + return undefined; +}; +const resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + let stsDefaultRegion = ""; + const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await stsRegionDefaultResolver(loaderConfig)()); + credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); + return resolvedRegion; +}; +const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + credentialDefaultProvider: () => async () => closureSourceCreds, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}; +const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger, + profile, + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient({ + ...stsOptions, + userAgentAppId, + profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, + logger: logger, + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), + ...(accountId && { accountId }), + }; + if (accountId) { + setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}; +const isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}; + +const getCustomizableStsClientCtor = (baseCtor, customizations) => { + if (!customizations) + return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}; +const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); +const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); +const decorateDefaultCredentialProvider = (provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), + ...input, +}); + +exports.AssumeRole$ = AssumeRole$; +exports.AssumeRoleCommand = AssumeRoleCommand; +exports.AssumeRoleRequest$ = AssumeRoleRequest$; +exports.AssumeRoleResponse$ = AssumeRoleResponse$; +exports.AssumeRoleWithWebIdentity$ = AssumeRoleWithWebIdentity$; +exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; +exports.AssumeRoleWithWebIdentityRequest$ = AssumeRoleWithWebIdentityRequest$; +exports.AssumeRoleWithWebIdentityResponse$ = AssumeRoleWithWebIdentityResponse$; +exports.AssumedRoleUser$ = AssumedRoleUser$; +exports.Credentials$ = Credentials$; +exports.ExpiredTokenException = ExpiredTokenException; +exports.ExpiredTokenException$ = ExpiredTokenException$; +exports.IDPCommunicationErrorException = IDPCommunicationErrorException; +exports.IDPCommunicationErrorException$ = IDPCommunicationErrorException$; +exports.IDPRejectedClaimException = IDPRejectedClaimException; +exports.IDPRejectedClaimException$ = IDPRejectedClaimException$; +exports.InvalidIdentityTokenException = InvalidIdentityTokenException; +exports.InvalidIdentityTokenException$ = InvalidIdentityTokenException$; +exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException; +exports.MalformedPolicyDocumentException$ = MalformedPolicyDocumentException$; +exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException; +exports.PackedPolicyTooLargeException$ = PackedPolicyTooLargeException$; +exports.PolicyDescriptorType$ = PolicyDescriptorType$; +exports.ProvidedContext$ = ProvidedContext$; +exports.RegionDisabledException = RegionDisabledException; +exports.RegionDisabledException$ = RegionDisabledException$; +exports.STS = STS; +exports.STSClient = STSClient; +exports.STSServiceException = STSServiceException; +exports.STSServiceException$ = STSServiceException$; +exports.Tag$ = Tag$; +exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; +exports.errorTypeRegistries = errorTypeRegistries; +exports.getDefaultRoleAssumer = getDefaultRoleAssumer; +exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; + + +/***/ }), + +/***/ 92062: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { SignatureV4, signatureV4aContainer } = __webpack_require__(82961); + +const signatureV4CrtContainer = { + CrtSignerV4: null, +}; + +const SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token"; +const SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(); +class SignatureV4SignWithCredentials extends SignatureV4 { + async signWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return privateAccess.signRequest(requestToSign, options ?? {}); + } + async presignWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + delete requestToSign.headers[SESSION_TOKEN_HEADER]; + requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + requestToSign.query = requestToSign.query ?? {}; + requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return this.presign(requestToSign, options); + } +} +function getCredentialsWithoutSessionToken(credentials) { + return { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + expiration: credentials.expiration, + }; +} +function setSingleOverride(privateAccess, credentialsWithoutSessionToken) { + const currentCredentialProvider = privateAccess.credentialProvider; + privateAccess.credentialProvider = () => { + privateAccess.credentialProvider = currentCredentialProvider; + return Promise.resolve(credentialsWithoutSessionToken); + }; +} + +class SignatureV4MultiRegion { + sigv4aSigner; + sigv4Signer; + signerOptions; + static sigv4aDependency() { + if (typeof signatureV4CrtContainer.CrtSignerV4 === "function") { + return "crt"; + } + else if (typeof signatureV4aContainer.SignatureV4a === "function") { + return "js"; + } + return "none"; + } + constructor(options) { + this.sigv4Signer = new SignatureV4SignWithCredentials(options); + this.signerOptions = options; + } + async sign(requestToSign, options = {}) { + if (options.signingRegion === "*") { + return this.getSigv4aSigner().sign(requestToSign, options); + } + return this.sigv4Signer.sign(requestToSign, options); + } + async signWithCredentials(requestToSign, credentials, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.signWithCredentials(requestToSign, credentials, options); + } + else { + throw new Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. ` + + `Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. ` + + `You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] ` + + `or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. ` + + `For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); + } + } + return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options); + } + async presign(originalRequest, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.presign(originalRequest, options); + } + else { + throw new Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. ` + + `Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. ` + + `You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] ` + + `or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. ` + + `For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); + } + } + return this.sigv4Signer.presign(originalRequest, options); + } + async presignWithCredentials(originalRequest, credentials, options = {}) { + if (options.signingRegion === "*") { + throw new Error("Method presignWithCredentials is not supported for [signingRegion=*]."); + } + return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options); + } + getSigv4aSigner() { + if (!this.sigv4aSigner) { + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + const JsSigV4aSigner = signatureV4aContainer.SignatureV4a; + if (this.signerOptions.runtime === "node") { + if (!CrtSignerV4 && !JsSigV4aSigner) { + throw new Error("Neither CRT nor JS SigV4a implementation is available. " + + "Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. " + + "For more information please go to " + + "https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); + } + if (CrtSignerV4 && typeof CrtSignerV4 === "function") { + this.sigv4aSigner = new CrtSignerV4({ + ...this.signerOptions, + signingAlgorithm: 1, + }); + } + else if (JsSigV4aSigner && typeof JsSigV4aSigner === "function") { + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions, + }); + } + else { + throw new Error("Available SigV4a implementation is not a valid constructor. " + + "Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a." + + "For more information please go to " + + "https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); + } + } + else { + if (!JsSigV4aSigner || typeof JsSigV4aSigner !== "function") { + throw new Error("JS SigV4a implementation is not available or not a valid constructor. " + + "Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. " + + "You must also register the package by calling [require('@aws-sdk/signature-v4a');] " + + "or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. " + + "For more information please go to " + + "https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a"); + } + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions, + }); + } + } + return this.sigv4aSigner; + } +} + +exports.SignatureV4MultiRegion = SignatureV4MultiRegion; +exports.SignatureV4SignWithCredentials = SignatureV4SignWithCredentials; +exports.signatureV4CrtContainer = signatureV4CrtContainer; + + +/***/ }), + +/***/ 84341: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setTokenFeature } = __webpack_require__(82172); +const { getBearerTokenEnvKey } = __webpack_require__(17727); +const { TokenProviderError, getSSOTokenFilepath, parseKnownFiles, getProfileName, loadSsoSessionData, getSSOTokenFromFile, memoize, chain } = __webpack_require__(48132); +const { promises } = __webpack_require__(73024); + +const fromEnvSigningName = ({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); + } + const bearerTokenKey = getBearerTokenEnvKey(signingName); + if (!(bearerTokenKey in process.env)) { + throw new TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); + } + const token = { token: process.env[bearerTokenKey] }; + setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}; + +const EXPIRE_WINDOW_MS = 5 * 60 * 1000; +const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => { + const { SSOOIDCClient } = __webpack_require__(22571); + const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop]; + const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: coalesce("logger"), + userAgentAppId: coalesce("userAgentAppId"), + })); + return ssoOidcClient; +}; + +const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => { + const { CreateTokenCommand } = __webpack_require__(22571); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig); + return ssoOidcClient.send(new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token", + })); +}; + +const validateTokenExpiry = (token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); + } +}; + +const validateTokenKey = (key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); + } +}; + +const { writeFile } = promises; +const writeSSOTokenToFile = (id, ssoToken) => { + const tokenFilepath = getSSOTokenFilepath(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}; + +const lastRefreshAttemptTimes = new Map(); +const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await parseKnownFiles(init); + const profileName = getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile) { + throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } + else if (!profile["sso_session"]) { + throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await loadSsoSessionData(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); + } + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); + } + } + ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await getSSOTokenFromFile(ssoSessionName); + } + catch (e) { + throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { + token: accessToken, + expiration: new Date(expiresAt), + }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + const lastRefreshAttemptTime = lastRefreshAttemptTimes.get(ssoSessionName) ?? 0; + if (Date.now() - lastRefreshAttemptTime < 30 * 1000) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTimes.set(ssoSessionName, Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken, + }); + } + catch (error) { + } + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration, + }; + } + catch (error) { + validateTokenExpiry(existingToken); + return existingToken; + } +}; + +const fromStatic = ({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}; + +const nodeProvider = (init = {}) => memoize(chain(fromSso(init), async () => { + throw new TokenProviderError("Could not load token from any providers", false); +}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); + +exports.fromEnvSigningName = fromEnvSigningName; +exports.fromSso = fromSso; +exports.fromStatic = fromStatic; +exports.nodeProvider = nodeProvider; + + +/***/ }), + +/***/ 14119: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { setTokenFeature } = __webpack_require__(24491); +const { getBearerTokenEnvKey } = __webpack_require__(15302); +const { TokenProviderError, getSSOTokenFilepath, parseKnownFiles, getProfileName, loadSsoSessionData, getSSOTokenFromFile, memoize, chain } = __webpack_require__(68702); +const { promises } = __webpack_require__(73024); + +const fromEnvSigningName = ({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); + } + const bearerTokenKey = getBearerTokenEnvKey(signingName); + if (!(bearerTokenKey in process.env)) { + throw new TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); + } + const token = { token: process.env[bearerTokenKey] }; + setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}; + +const EXPIRE_WINDOW_MS = 5 * 60 * 1000; +const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => { + const { SSOOIDCClient } = __webpack_require__(84623); + const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop]; + const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: coalesce("logger"), + userAgentAppId: coalesce("userAgentAppId"), + })); + return ssoOidcClient; +}; + +const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => { + const { CreateTokenCommand } = __webpack_require__(84623); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig); + return ssoOidcClient.send(new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token", + })); +}; + +const validateTokenExpiry = (token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); + } +}; + +const validateTokenKey = (key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); + } +}; + +const { writeFile } = promises; +const writeSSOTokenToFile = (id, ssoToken) => { + const tokenFilepath = getSSOTokenFilepath(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}; + +const lastRefreshAttemptTimes = new Map(); +const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await parseKnownFiles(init); + const profileName = getProfileName({ + profile: init.profile ?? callerClientConfig?.profile, + }); + const profile = profiles[profileName]; + if (!profile) { + throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } + else if (!profile["sso_session"]) { + throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await loadSsoSessionData(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); + } + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); + } + } + ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await getSSOTokenFromFile(ssoSessionName); + } + catch (e) { + throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { + token: accessToken, + expiration: new Date(expiresAt), + }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + const lastRefreshAttemptTime = lastRefreshAttemptTimes.get(ssoSessionName) ?? 0; + if (Date.now() - lastRefreshAttemptTime < 30 * 1000) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTimes.set(ssoSessionName, Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken, + }); + } + catch (error) { + } + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration, + }; + } + catch (error) { + validateTokenExpiry(existingToken); + return existingToken; + } +}; + +const fromStatic = ({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}; + +const nodeProvider = (init = {}) => memoize(chain(fromSso(init), async () => { + throw new TokenProviderError("Could not load token from any providers", false); +}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); + +exports.fromEnvSigningName = fromEnvSigningName; +exports.fromSso = fromSso; +exports.fromStatic = fromStatic; +exports.nodeProvider = nodeProvider; + + +/***/ }), + +/***/ 46158: +/***/ ((__unused_webpack_module, exports) => { + +const ATTR_ESCAPE_RE = /[&<>"]/g; +const ATTR_ESCAPE_MAP = { + "&": "&", + "<": "<", + ">": ">", + '"': """, +}; +function escapeAttribute(value) { + return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]); +} + +const ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g; +const ELEMENT_ESCAPE_MAP = { + "&": "&", + '"': """, + "'": "'", + "<": "<", + ">": ">", + "\r": " ", + "\n": " ", + "\u0085": "…", + "\u2028": "
", +}; +function escapeElement(value) { + return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]); +} + +class XmlText { + value; + constructor(value) { + this.value = value; + } + toString() { + return escapeElement("" + this.value); + } +} + +class XmlNode { + name; + children; + attributes = {}; + static of(name, childText, withName) { + const node = new XmlNode(name); + if (childText !== undefined) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== undefined) { + node.withName(withName); + } + return node; + } + constructor(name, children = []) { + this.name = name; + this.children = children; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + n(name) { + this.name = name; + return this; + } + c(child) { + this.children.push(child); + return this; + } + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + cc(input, field, withName = field) { + if (input[field] != null) { + const node = XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return (xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`); + } +} + +function writeKey(obj) { + Object.defineProperty(obj, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true }); +} +function parseXML(xml) { + const state = new AwsXmlParser(xml); + return state.parse(); +} +class AwsXmlParser { + x; + i = 0; + z; + constructor(x) { + this.x = x; + this.x = x.replace(/\r\n?/g, "\n"); + this.z = this.x.length; + } + parse() { + const p = this; + const { z } = p; + while (p.i < z) { + p.trim(); + if (p.i >= z) { + break; + } + if (p.isNext(""); + p.trim(); + } + else if (p.isNext(""); + p.trim(); + } + else if (p.isNext("/".includes(p.x[p.i])) { + tag += p.x[p.i++]; + } + let hasAttrs = false; + const attrs = {}; + while (p.i < p.z) { + p.trim(); + if (">/".includes(p.x[p.i])) { + break; + } + let name = ""; + while (p.i < p.z && !"= \t\r\n>/?".includes(p.x[p.i])) { + name += p.x[p.i++]; + } + p.trim(); + if (p.x[p.i] !== "=") { + break; + } + ++p.i; + p.trim(); + if (name === "__proto__") { + writeKey(attrs); + } + attrs[name] = p.readAttrValue(); + hasAttrs = true; + } + if (p.i >= p.z) { + throw new Error("@aws-sdk XML parse error: unexpected end of input."); + } + if (p.x[p.i] === "/") { + ++p.i; + if (p.i >= p.z || p.x[p.i] !== ">") { + throw new Error("@aws-sdk XML parse error: expected > at the end of self-closing tag."); + } + ++p.i; + return { tag, value: hasAttrs ? attrs : "" }; + } + if (p.x[p.i] !== ">") { + throw new Error("@aws-sdk XML parse error: expected > at the end of opening tag."); + } + ++p.i; + const textParts = []; + const childTags = []; + let hasElementChild = false; + while (p.i < p.z) { + if (p.isNext(""); + } + else if (p.isNext("")); + } + else if (p.isNext(""); + } + else { + hasElementChild = true; + childTags.push(p.parseTag()); + } + } + else { + let text = ""; + while (p.i < p.z && p.x[p.i] !== "<") { + text += p.x[p.i++]; + } + textParts.push(p.decodeEntities(text)); + } + } + if (!p.isNext(".`); + } + p.i += 2; + const closeTag = p.readTo(">").trim(); + if (closeTag !== tag) { + throw new Error(`@aws-sdk XML parse error: mismatched tags <${tag}> and .`); + } + if (!hasAttrs && textParts.length === 0 && !hasElementChild) { + return { tag, value: "" }; + } + if (!hasAttrs && !hasElementChild) { + const text = textParts.length === 1 ? textParts[0] : textParts.join(""); + if (text.trim() === "" && text.includes("\n")) { + return { tag, value: "" }; + } + return { tag, value: text }; + } + const obj = {}; + for (const text of textParts) { + if (text.trim() === "" && text.includes("\n")) { + continue; + } + obj["#text"] = "#text" in obj ? obj["#text"] + text : text; + } + for (const child of childTags) { + if (child.tag === "__proto__") { + writeKey(obj); + } + if (child.tag in obj) { + if (Array.isArray(obj[child.tag])) { + obj[child.tag].push(child.value); + } + else { + obj[child.tag] = [obj[child.tag], child.value]; + } + } + else { + obj[child.tag] = child.value; + } + } + for (const [k, v] of Object.entries(attrs)) { + if (k === "__proto__") { + writeKey(obj); + } + obj[k] = v; + } + return { tag, value: obj }; + } + static ENTITIES = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + }; + skipDoctype() { + const p = this; + p.i += 9; + let depth = 0; + while (p.i < p.z) { + const c = p.x[p.i]; + if (c === "[") { + ++depth; + } + else if (c === "]") { + --depth; + } + else if (c === ">" && depth === 0) { + ++p.i; + return; + } + ++p.i; + } + throw new Error("@aws-sdk XML parse error: unclosed DOCTYPE."); + } + decodeEntities(s) { + return s.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g, (_, hex, dec, named) => { + if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + if (dec) { + return String.fromCharCode(parseInt(dec, 10)); + } + return AwsXmlParser.ENTITIES[named] ?? ""; + }); + } +} + +exports.XmlNode = XmlNode; +exports.XmlText = XmlText; +exports.parseXML = parseXML; + + +/***/ }), + +/***/ 80007: +/***/ ((__unused_webpack_module, exports) => { + +const ATTR_ESCAPE_RE = /[&<>"]/g; +const ATTR_ESCAPE_MAP = { + "&": "&", + "<": "<", + ">": ">", + '"': """, +}; +function escapeAttribute(value) { + return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]); +} + +const ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g; +const ELEMENT_ESCAPE_MAP = { + "&": "&", + '"': """, + "'": "'", + "<": "<", + ">": ">", + "\r": " ", + "\n": " ", + "\u0085": "…", + "\u2028": "
", +}; +function escapeElement(value) { + return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]); +} + +class XmlText { + value; + constructor(value) { + this.value = value; + } + toString() { + return escapeElement("" + this.value); + } +} + +class XmlNode { + name; + children; + attributes = {}; + static of(name, childText, withName) { + const node = new XmlNode(name); + if (childText !== undefined) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== undefined) { + node.withName(withName); + } + return node; + } + constructor(name, children = []) { + this.name = name; + this.children = children; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + n(name) { + this.name = name; + return this; + } + c(child) { + this.children.push(child); + return this; + } + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + cc(input, field, withName = field) { + if (input[field] != null) { + const node = XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return (xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`); + } +} + +function writeKey(obj) { + Object.defineProperty(obj, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true }); +} +function parseXML(xml) { + const state = new AwsXmlParser(xml); + return state.parse(); +} +class AwsXmlParser { + x; + i = 0; + z; + constructor(x) { + this.x = x; + this.x = x.replace(/\r\n?/g, "\n"); + this.z = this.x.length; + } + parse() { + const p = this; + const { z } = p; + while (p.i < z) { + p.trim(); + if (p.i >= z) { + break; + } + if (p.isNext(""); + p.trim(); + } + else if (p.isNext(""); + p.trim(); + } + else if (p.isNext("/".includes(p.x[p.i])) { + tag += p.x[p.i++]; + } + let hasAttrs = false; + const attrs = {}; + while (p.i < p.z) { + p.trim(); + if (">/".includes(p.x[p.i])) { + break; + } + let name = ""; + while (p.i < p.z && !"= \t\r\n>/?".includes(p.x[p.i])) { + name += p.x[p.i++]; + } + p.trim(); + if (p.x[p.i] !== "=") { + break; + } + ++p.i; + p.trim(); + if (name === "__proto__") { + writeKey(attrs); + } + attrs[name] = p.readAttrValue(); + hasAttrs = true; + } + if (p.i >= p.z) { + throw new Error("@aws-sdk XML parse error: unexpected end of input."); + } + if (p.x[p.i] === "/") { + ++p.i; + if (p.i >= p.z || p.x[p.i] !== ">") { + throw new Error("@aws-sdk XML parse error: expected > at the end of self-closing tag."); + } + ++p.i; + return { tag, value: hasAttrs ? attrs : "" }; + } + if (p.x[p.i] !== ">") { + throw new Error("@aws-sdk XML parse error: expected > at the end of opening tag."); + } + ++p.i; + const textParts = []; + const childTags = []; + let hasElementChild = false; + while (p.i < p.z) { + if (p.isNext(""); + } + else if (p.isNext("")); + } + else if (p.isNext(""); + } + else { + hasElementChild = true; + childTags.push(p.parseTag()); + } + } + else { + let text = ""; + while (p.i < p.z && p.x[p.i] !== "<") { + text += p.x[p.i++]; + } + textParts.push(p.decodeEntities(text)); + } + } + if (!p.isNext(".`); + } + p.i += 2; + const closeTag = p.readTo(">").trim(); + if (closeTag !== tag) { + throw new Error(`@aws-sdk XML parse error: mismatched tags <${tag}> and .`); + } + if (!hasAttrs && textParts.length === 0 && !hasElementChild) { + return { tag, value: "" }; + } + if (!hasAttrs && !hasElementChild) { + const text = textParts.length === 1 ? textParts[0] : textParts.join(""); + if (text.trim() === "" && text.includes("\n")) { + return { tag, value: "" }; + } + return { tag, value: text }; + } + const obj = {}; + for (const text of textParts) { + if (text.trim() === "" && text.includes("\n")) { + continue; + } + obj["#text"] = "#text" in obj ? obj["#text"] + text : text; + } + for (const child of childTags) { + if (child.tag === "__proto__") { + writeKey(obj); + } + if (child.tag in obj) { + if (Array.isArray(obj[child.tag])) { + obj[child.tag].push(child.value); + } + else { + obj[child.tag] = [obj[child.tag], child.value]; + } + } + else { + obj[child.tag] = child.value; + } + } + for (const [k, v] of Object.entries(attrs)) { + if (k === "__proto__") { + writeKey(obj); + } + obj[k] = v; + } + return { tag, value: obj }; + } + static ENTITIES = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + }; + skipDoctype() { + const p = this; + p.i += 9; + let depth = 0; + while (p.i < p.z) { + const c = p.x[p.i]; + if (c === "[") { + ++depth; + } + else if (c === "]") { + --depth; + } + else if (c === ">" && depth === 0) { + ++p.i; + return; + } + ++p.i; + } + throw new Error("@aws-sdk XML parse error: unclosed DOCTYPE."); + } + decodeEntities(s) { + return s.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g, (_, hex, dec, named) => { + if (hex) { + return String.fromCharCode(parseInt(hex, 16)); + } + if (dec) { + return String.fromCharCode(parseInt(dec, 10)); + } + return AwsXmlParser.ENTITIES[named] ?? ""; + }); + } +} + +exports.XmlNode = XmlNode; +exports.XmlText = XmlText; +exports.parseXML = parseXML; + + +/***/ }), + +/***/ 89273: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { getSmithyContext, hasOwn } = __webpack_require__(74875); +exports.getSmithyContext = getSmithyContext; +const { HttpRequest } = __webpack_require__(37015); +const { requestBuilder } = __webpack_require__(37015); +exports.requestBuilder = requestBuilder; +const { HttpApiKeyAuthLocation } = __webpack_require__(88867); + +const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; +}; + +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; +} +const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = getSmithyContext(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}; + +const httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware", +}; +const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + }, +}); + +const httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "serializerMiddleware", +}; +const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeMiddlewareOptions); + }, +}); + +const defaultErrorHandler = (signingProperties) => (error) => { + throw error; +}; +const defaultSuccessHandler = (httpResponse, signingProperties) => { }; +const httpSigningMiddleware = (config) => (next, context) => async (args) => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties), + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}; + +const httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware", +}; +const getHttpSigningPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions); + }, +}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}; +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); + } + else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return undefined; + }; +} +const get = (fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return undefined; + } + cursor = cursor[step]; + } + return cursor; +}; + +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {}, + }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} + +class DefaultIdentityProviderConfig { + authSchemes = new Map(); + constructor(config) { + for (const key in config) { + if (!hasOwn(config, key)) + continue; + const value = config[key]; + if (value !== undefined) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +} + +class HttpApiKeyAuthSigner { + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = HttpRequest.clone(httpRequest); + if (signingProperties.in === HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } + else if (signingProperties.in === HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme + ? `${signingProperties.scheme} ${identity.apiKey}` + : identity.apiKey; + } + else { + throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + + "but found: `" + + signingProperties.in + + "`"); + } + return clonedRequest; + } +} + +class HttpBearerAuthSigner { + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } +} + +class NoAuthSigner { + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +} + +const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; +}; +const EXPIRATION_MS = 300_000; +const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined; +const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === undefined) { + return undefined; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}; + +exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig; +exports.EXPIRATION_MS = EXPIRATION_MS; +exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner; +exports.HttpBearerAuthSigner = HttpBearerAuthSigner; +exports.NoAuthSigner = NoAuthSigner; +exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction; +exports.createPaginator = createPaginator; +exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh; +exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin; +exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin; +exports.getHttpSigningPlugin = getHttpSigningPlugin; +exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions; +exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware; +exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions; +exports.httpSigningMiddleware = httpSigningMiddleware; +exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions; +exports.isIdentityExpired = isIdentityExpired; +exports.memoizeIdentityProvider = memoizeIdentityProvider; +exports.normalizeProvider = normalizeProvider; +exports.setFeature = setFeature; + + +/***/ }), + +/***/ 76798: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { nv, NumericValue, calculateBodyLength, generateIdempotencyToken, fromBase64, _parseEpochTimestamp } = __webpack_require__(26591); +const { hasOwn, getSmithyContext } = __webpack_require__(74875); +const { HttpRequest, collectBody, SerdeContext, RpcProtocol } = __webpack_require__(37015); +const { NormalizedSchema, deref, TypeRegistry } = __webpack_require__(31829); + +const majorUint64 = 0; +const majorNegativeInt64 = 1; +const majorUnstructuredByteString = 2; +const majorUtf8String = 3; +const majorList = 4; +const majorMap = 5; +const majorTag = 6; +const majorSpecial = 7; +const specialFalse = 20; +const specialTrue = 21; +const specialNull = 22; +const specialUndefined = 23; +const extendedOneByte = 24; +const extendedFloat16 = 25; +const extendedFloat32 = 26; +const extendedFloat64 = 27; +const minorIndefinite = 31; +function alloc(size) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); +} +const tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); +function tag(data) { + data[tagSymbol] = true; + return data; +} + +const USE_BUFFER$3 = typeof Buffer !== "undefined"; +const textDecoder$1 = new TextDecoder(); +let payload$1 = alloc(0); +let isBuffer$1 = false; +let dataView$2 = new DataView(payload$1.buffer, payload$1.byteOffset, payload$1.byteLength); +let _offset = 0; +function setPayload(bytes) { + payload$1 = bytes; + isBuffer$1 = USE_BUFFER$3 && payload$1 instanceof Buffer; + dataView$2 = new DataView(payload$1.buffer, payload$1.byteOffset, payload$1.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (minor === minorIndefinite && 2 <= major && major <= 5) { + return decodeIndefinite(at, to); + } + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: { + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } + else { + switch (minor) { + case extendedOneByte: + if (to - at < 2) { + overflow$1(1); + } + unsignedInt = payload$1[at + 1]; + offset = 2; + break; + case extendedFloat16: + if (to - at < 3) { + overflow$1(2); + } + unsignedInt = dataView$2.getUint16(at + 1); + offset = 3; + break; + case extendedFloat32: + if (to - at < 5) { + overflow$1(4); + } + unsignedInt = dataView$2.getUint32(at + 1); + offset = 5; + break; + case extendedFloat64: + if (to - at < 9) { + overflow$1(8); + } + { + const hi = dataView$2.getUint32(at + 1); + if (hi < 0x00200000) { + unsignedInt = hi * 4294967296 + dataView$2.getUint32(at + 5); + } + else { + unsignedInt = dataView$2.getBigUint64(at + 1); + } + } + offset = 9; + break; + default: + unexpectedMinor(minor); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt$1(unsignedInt); + } + else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } + else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt$1(negativeInt); + } + else { + return decodeTagValue(at, to, minor, unsignedInt, offset); + } + } + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + default: + return decodeSpecial(at, to); + } +} +function decodeIndefinite(at, to) { + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } +} +function bytesToFloat16$1(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + if (exponent === 0b00000) { + if (fraction === 0) { + return 0; + } + return scalar * (Math.pow(2, 1 - 15) * (fraction / 1024)); + } + else if (exponent === 0b11111) { + if (fraction === 0) { + return scalar * Infinity; + } + return NaN; + } + return scalar * (Math.pow(2, exponent - 15) * (1 + fraction / 1024)); +} +function decodeMap(at, to) { + const mapDataLength = decodeCount$1(at, to); + if (mapDataLength < 25) { + return decodeMapSmall(at, to, mapDataLength); + } + return decodeMapLarge(at, to, mapDataLength); +} +function decodeMapLarge(at, to, mapDataLength) { + const offset = _offset; + at += offset; + const base = at; + const map = Object.create(null); + for (let i = 0; i < mapDataLength; ++i) { + const key = decodeUtf8String(at, to); + at += _offset; + const valMajor = (payload$1[at] & 0b1110_0000) >> 5; + if (valMajor === majorUtf8String) { + map[key] = decodeUtf8String(at, to); + } + else { + map[key] = decode(at, to); + } + at += _offset; + } + _offset = offset + (at - base); + Object.setPrototypeOf(map, Object.prototype); + return map; +} +function decodeMapSmall(at, to, mapDataLength) { + const offset = _offset; + at += offset; + const base = at; + const map = {}; + for (let i = 0; i < mapDataLength; ++i) { + const key = decodeUtf8String(at, to); + at += _offset; + map[key] = decode(at, to); + at += _offset; + } + _offset = offset + (at - base); + return map; +} +function decodeList(at, to) { + const listDataLength = decodeCount$1(at, to); + const offset = _offset; + at += offset; + const base = at; + const list = Array(listDataLength); + for (let i = 0; i < listDataLength; ++i) { + list[i] = decode(at, to); + at += _offset; + } + _offset = offset + (at - base); + return list; +} +function decodeUtf8String(at, to) { + const length = decodeCount$1(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + overflow$1(length); + } + _offset = offset + length; + if (length < 24) { + return decodeUtf8StringCached(at, length); + } + if (isBuffer$1) { + return payload$1.toString("utf-8", at, at + length); + } + return textDecoder$1.decode(payload$1.subarray(at, at + length)); +} +const stringCache$1 = new Array(2048); +const stringCacheEpochs$1 = new Uint16Array(2048); +let cacheEpoch$1 = 0; +function advanceDecodingEpoch() { + cacheEpoch$1 = (cacheEpoch$1 + 1) & 0b1111_1111_1111_1111; +} +function decodeUtf8StringCached(at, length) { + let h = length; + for (let i = 0; i < length; ++i) { + h = (h * 31 + payload$1[at + i]) | 0; + } + const slot = (h >>> 0) & 2047; + const cached = stringCache$1[slot]; + if (cached !== undefined) { + if (cached.length === length) { + let match = true; + for (let i = 0; i < length; ++i) { + if (cached.charCodeAt(i) !== payload$1[at + i]) { + match = false; + break; + } + } + if (match) { + stringCacheEpochs$1[slot] = cacheEpoch$1; + return cached; + } + } + } + const result = isBuffer$1 + ? payload$1.toString("utf-8", at, at + length) + : textDecoder$1.decode(payload$1.subarray(at, at + length)); + if (stringCacheEpochs$1[slot] !== cacheEpoch$1) { + stringCache$1[slot] = result; + stringCacheEpochs$1[slot] = cacheEpoch$1; + } + return result; +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount$1(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + overflow$1(length); + } + const value = payload$1.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeTagValue(at, to, minor, unsignedInt, offset) { + if (minor === 2 || minor === 3) { + const length = decodeCount$1(at + offset, to); + let b = BigInt(0); + const start = at + offset + _offset; + for (let i = start; i < start + length; ++i) { + b = (b << BigInt(8)) | BigInt(payload$1[i]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b - BigInt(1) : b; + } + else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [rawExponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const absMantissa = BigInt(normalizer) * BigInt(mantissa); + const mantissaDigits = String(absMantissa); + const sign = mantissa < 0 ? "-" : ""; + let numericString; + const isSmallExponent = typeof rawExponent === "number" && Math.abs(rawExponent) <= 2 ** 28; + if (isSmallExponent) { + const exponent = rawExponent; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + mantissaDigits; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + } + else { + const bigExponent = BigInt(rawExponent); + if (mantissaDigits.length === 1) { + numericString = sign + mantissaDigits + "e" + String(bigExponent); + } + else { + const adjustedExp = bigExponent + BigInt(mantissaDigits.length - 1); + numericString = sign + mantissaDigits[0] + "." + mantissaDigits.slice(1) + "e" + String(adjustedExp); + } + } + _offset = offset + _offset; + return nv(numericString); + } + else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt$1(unsignedInt), value }); + } +} +function decodeSpecial(at, to) { + const minor = payload$1[at] & 0b0001_1111; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16$1(payload$1[at + 1], payload$1[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView$2.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView$2.getFloat64(at + 1); + default: + unexpectedMinor(minor); + } +} +function decodeCount$1(at, to) { + const minor = payload$1[at] & 0b0001_1111; + if (minor < 24) { + _offset = 1; + return minor; + } + switch (minor) { + case extendedOneByte: + if (to - at < 2) { + overflow$1(1); + } + _offset = 2; + return payload$1[at + 1]; + case extendedFloat16: + if (to - at < 3) { + overflow$1(2); + } + _offset = 3; + return dataView$2.getUint16(at + 1); + case extendedFloat32: + if (to - at < 5) { + overflow$1(4); + } + _offset = 5; + return dataView$2.getUint32(at + 1); + case extendedFloat64: + if (to - at < 9) { + overflow$1(8); + } + _offset = 9; + return demote(dataView$2.getBigUint64(at + 1)); + default: + unexpectedMinor(minor); + } +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map = {}; + for (; at < to;) { + if (payload$1[at] === 0b1111_1111) { + _offset = at - base + 2; + return map; + } + const key = decodeUtf8String(at, to); + at += _offset; + map[key] = decode(at, to); + at += _offset; + } + throw new Error("expected break marker."); +} +function decodeListIndefinite(at, to) { + at += 1; + const list = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + _offset = at - base + 2; + return list; + } + list.push(decode(at, to)); + at += _offset; + } + throw new Error("expected break marker."); +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + if (USE_BUFFER$3) { + return data.toString("utf-8", 0, data.length); + } + return textDecoder$1.decode(data); + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (major !== majorUtf8String) { + unexpectedMajorInIndefiniteString(major); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return data; + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (major !== majorUnstructuredByteString) { + unexpectedMajorInIndefiniteString(major); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function castBigInt$1(bigInt) { + if (typeof bigInt === "number") { + return bigInt; + } + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); + } + return num; +} +function overflow$1(n) { + throw new Error(`length ${n} greater than remaining buf len.`); +} +function unexpectedMinor(minor) { + throw new Error(`unexpected minor value ${minor}.`); +} +function unexpectedMajorInIndefiniteString(major) { + throw new Error(`unexpected major type ${major} in indefinite string.`); +} + +const USE_BUFFER$2 = typeof Buffer !== "undefined"; +const encodeStringCache = new Map(); +let encodeCacheEpoch$1 = 0; +let encodeCacheSaturated$1 = false; +const initialSize = 2048; +let data = alloc(initialSize); +let dataView$1 = new DataView(data.buffer, data.byteOffset, data.byteLength); +let cursor$1 = 0; +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + if (typeof input === "string") { + const len = input.length; + if (USE_BUFFER$2) { + ensureSpace(len * 3 + 9); + if (len > 23) { + encodeHeader$1(majorUtf8String, Buffer.byteLength(input)); + cursor$1 += data.write(input, cursor$1); + } + else { + encodeStringCached(input); + } + } + else { + const maxBytes = len * 3; + ensureSpace(maxBytes + 9); + const headerPos = cursor$1; + const result = new TextEncoder().encodeInto(input, data.subarray(cursor$1 + 9)); + const byteLen = result.written; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else if (byteLen < 65536) { + headerSize = 3; + } + else if (byteLen < 4294967296) { + headerSize = 5; + } + else { + headerSize = 9; + } + if (headerSize < 9) { + data.copyWithin(headerPos + headerSize, headerPos + 9, headerPos + 9 + byteLen); + } + cursor$1 = headerPos; + encodeInteger(majorUtf8String, byteLen); + cursor$1 += byteLen; + } + continue; + } + if (data.byteLength - cursor$1 < 9) { + ensureSpace(64); + } + if (typeof input === "number") { + if (Number.isInteger(input) && input >= -9007199254740992 && input <= 0x1fffffffffffff) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + data[cursor$1++] = value >> 8; + data[cursor$1++] = value & 0xff; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + dataView$1.setUint32(cursor$1, hi); + dataView$1.setUint32(cursor$1 + 4, lo); + cursor$1 += 8; + } + continue; + } + data[cursor$1++] = (majorSpecial << 5) | extendedFloat64; + dataView$1.setFloat64(cursor$1, input); + cursor$1 += 8; + continue; + } + else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + if (value < BigInt("18446744073709551616")) { + const n = Number(value); + if (n < 4294967296) { + encodeInteger(major, n); + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + dataView$1.setBigUint64(cursor$1, value); + cursor$1 += 8; + } + } + else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b = value; + let i = 0; + while (bigIntBytes.byteLength - ++i >= 0) { + bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2 + 16); + data[cursor$1++] = nonNegative ? 0b110_00010 : 0b110_00011; + encodeHeader$1(majorUnstructuredByteString, bigIntBytes.byteLength); + data.set(bigIntBytes, cursor$1); + cursor$1 += bigIntBytes.byteLength; + } + continue; + } + else if (input === null) { + data[cursor$1++] = (majorSpecial << 5) | specialNull; + continue; + } + else if (typeof input === "boolean") { + data[cursor$1++] = (majorSpecial << 5) | (input ? specialTrue : specialFalse); + continue; + } + else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } + else if (Array.isArray(input)) { + encodeInteger(majorList, input.length); + ensureSpace(input.length * 9 + 64); + for (let i = input.length - 1; i >= 0; --i) { + encodeStack.push(input[i]); + } + continue; + } + else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2 + 9); + encodeInteger(majorUnstructuredByteString, input.length); + data.set(input, cursor$1); + cursor$1 += input.byteLength; + continue; + } + else if (typeof input === "object") { + if (input instanceof NumericValue) { + let str = input.string; + let expOffset = BigInt(0); + const eIndex = str.search(/[eE]/); + if (eIndex !== -1) { + expOffset = BigInt(str.slice(eIndex + 1)); + str = str.slice(0, eIndex); + } + const decimalIndex = str.indexOf("."); + const fractionDigits = decimalIndex === -1 ? 0 : str.length - decimalIndex - 1; + const exponent = expOffset - BigInt(fractionDigits); + const mantissa = BigInt(str.replace(".", "")); + data[cursor$1++] = 0b110_00100; + encodeInteger(majorList, 2); + encodeStack.push(mantissa); + encodeStack.push(exponent >= -0x20000000000000n && exponent <= 0x1fffffffffffffn ? Number(exponent) : exponent); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader$1(majorTag, input.tag); + continue; + } + else { + throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); + } + } + const keys = Object.keys(input); + const len = keys.length; + encodeInteger(majorMap, len); + for (let i = len - 1; i >= 0; --i) { + encodeStack.push(input[keys[i]]); + encodeStack.push(keys[i]); + } + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); + } +} +function advanceEncodingEpoch() { + encodeCacheEpoch$1 = (encodeCacheEpoch$1 + 1) & 0b1111_1111_1111_1111; + encodeCacheSaturated$1 = false; +} +function toUint8Array() { + const out = alloc(cursor$1); + out.set(data.subarray(0, cursor$1), 0); + cursor$1 = 0; + return out; +} +function resize(size) { + const old = data; + data = alloc(size); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } + else { + data.set(old, 0); + } + } + dataView$1 = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeStringCached(input) { + const cached = encodeStringCache.get(input); + if (cached !== undefined) { + data.set(cached.bytes, cursor$1); + cursor$1 += cached.bytes.length; + cached.epoch = encodeCacheEpoch$1; + return; + } + const start = cursor$1; + const byteLen = Buffer.byteLength(input); + encodeInteger(majorUtf8String, byteLen); + cursor$1 += data.write(input, cursor$1); + const bytes = Uint8Array.prototype.slice.call(data, start, cursor$1); + if (encodeStringCache.size >= 2048) { + if (encodeCacheSaturated$1) { + return; + } + let evicted = 0; + for (const [key, entry] of encodeStringCache) { + if (evicted >= 1024) { + break; + } + if (entry.epoch !== encodeCacheEpoch$1) { + encodeStringCache.delete(key); + evicted++; + } + } + if (evicted === 0) { + encodeCacheSaturated$1 = true; + return; + } + } + if (encodeStringCache.size < 2048) { + encodeStringCache.set(input, { epoch: encodeCacheEpoch$1, bytes }); + } +} +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor$1; + if (remaining < bytes) { + if (cursor$1 < 16_000_000) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } + else { + resize(data.byteLength + bytes + 16_000_000); + } + } +} +function encodeHeader$1(major, value) { + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + dataView$1.setUint16(cursor$1, value); + cursor$1 += 2; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + dataView$1.setBigUint64(cursor$1, typeof value === "bigint" ? value : BigInt(value)); + cursor$1 += 8; + } +} +function encodeInteger(major, value) { + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + data[cursor$1++] = value >> 8; + data[cursor$1++] = value & 0xff; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + dataView$1.setUint32(cursor$1, hi); + dataView$1.setUint32(cursor$1 + 4, lo); + cursor$1 += 8; + } +} + +const cbor = { + deserialize(payload) { + advanceDecodingEpoch(); + setPayload(payload); + return decode(0, payload.length); + }, + serialize(input) { + advanceEncodingEpoch(); + try { + encode(input); + return toUint8Array(); + } + catch (e) { + toUint8Array(); + throw e; + } + }, + resizeEncodingBuffer(size) { + resize(size); + }, +}; + +const parseCborBody = (streamBody, context) => { + return collectBody(streamBody, context).then(async (bytes) => { + if (bytes.length) { + try { + return cbor.deserialize(bytes); + } + catch (e) { + Object.defineProperty(e, "$responseBodyText", { + value: context.utf8Encoder(bytes), + }); + throw e; + } + } + return {}; + }); +}; +const dateToTag = (date) => { + return tag({ + tag: 1, + value: date.getTime() / 1000, + }); +}; +const parseCborErrorBody = async (errorBody, context) => { + const value = await parseCborBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadSmithyRpcV2CborErrorCode = (output, data) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } + let codeKey; + for (const key in data) { + if (!hasOwn(data, key)) + continue; + if (key.toLowerCase() === "code") { + codeKey = key; + break; + } + } + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } +}; +const checkCborResponse = (response) => { + if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { + throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); + } +}; +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const endpoint = await context.endpoint(); + const { hostname, protocol = "https", port, path: basePath } = endpoint; + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers: { + ...headers, + }, + }; + if (resolvedHostname !== undefined) { + contents.hostname = resolvedHostname; + } + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + contents.headers[name] = endpoint.headers[name]; + } + } + if (body !== undefined) { + contents.body = body; + try { + contents.headers["content-length"] = String(calculateBodyLength(body)); + } + catch (ignored) { } + } + return new HttpRequest(contents); +}; + +class CborShapeSerializer2 extends SerdeContext { + write(schema, value) { + cursor = 0; + const ns = NormalizedSchema.of(schema); + writeValue(ns, value, undefined, this.serdeContext); + } + flush() { + const result = buf.subarray(0, cursor); + cursor = 0; + buf = allocUnsafe(INITIAL_BUFFER_SIZE); + view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + return result; + } +} +const CBOR_STRUCT_CACHE = Symbol.for("@smithy/cbor-struct-cache"); +function loadCborStructIterator(ns) { + const schema = ns.getSchema(); + const existing = schema[CBOR_STRUCT_CACHE]; + if (existing) { + return existing; + } + const memberNames = []; + const memberSchemas = []; + for (const [name, memberSchema] of ns.structIterator()) { + memberNames.push(name); + memberSchemas.push(memberSchema); + } + const encodedKeys = new Array(memberNames.length); + for (let i = 0; i < memberNames.length; ++i) { + encodedKeys[i] = encodeCborStringKey(memberNames[i]); + } + const cache = { memberNames, memberSchemas, encodedKeys }; + schema[CBOR_STRUCT_CACHE] = cache; + return cache; +} +function encodeCborStringKey(s) { + let utf8Bytes; + if (USE_BUFFER$1) { + utf8Bytes = Buffer.from(s, "utf-8"); + } + else { + utf8Bytes = new TextEncoder().encode(s); + } + const byteLen = utf8Bytes.length; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else { + headerSize = 3; + } + const result = new Uint8Array(headerSize + byteLen); + if (headerSize === 1) { + result[0] = (majorUtf8String << 5) | byteLen; + } + else if (headerSize === 2) { + result[0] = (majorUtf8String << 5) | 24; + result[1] = byteLen; + } + else { + result[0] = (majorUtf8String << 5) | extendedFloat16; + result[1] = byteLen >> 8; + result[2] = byteLen & 0xff; + } + result.set(utf8Bytes, headerSize); + return result; +} +const USE_BUFFER$1 = typeof Buffer !== "undefined"; +const textEncoder = new TextEncoder(); +const INITIAL_BUFFER_SIZE = 2048; +let buf = USE_BUFFER$1 ? Buffer.allocUnsafe(INITIAL_BUFFER_SIZE) : new Uint8Array(INITIAL_BUFFER_SIZE); +let view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); +let cursor = 0; +const STRING_CACHE_MAX = 2048; +const stringEncodeCache = new Map(); +let encodeCacheEpoch = 0; +let encodeCacheSaturated = false; +function allocUnsafe(size) { + return USE_BUFFER$1 ? Buffer.allocUnsafe(size) : new Uint8Array(size); +} +function writeValue(ns, value, container, serdeContext) { + if (value == null) { + if (value === undefined && ns.isIdempotencyToken()) { + writeString(generateIdempotencyToken()); + return; + } + ensure(1); + buf[cursor++] = (majorSpecial << 5) | specialNull; + return; + } + if (ns.isUnitSchema()) { + ensure(1); + encodeHeader(majorMap, 0); + return; + } + const isObject = typeof value === "object"; + if (isObject) { + if (ns.isBlobSchema()) { + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + } + if (ns.isTimestampSchema()) { + if (value instanceof Date) { + writeTimestamp(value); + return; + } + } + if (ns.isStructSchema()) { + writeStruct(ns, value, serdeContext); + return; + } + if (Array.isArray(value) && (ns.isListSchema() || ns.isDocumentSchema())) { + writeList(ns, value, ns.isDocumentSchema(), serdeContext); + return; + } + if (ns.isMapSchema()) { + writeMap(ns, value, false, serdeContext); + return; + } + if (value instanceof Date) { + writeTimestamp(value); + return; + } + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + if (value instanceof NumericValue) { + writeNumericValue(value); + return; + } + if (value[tagSymbol]) { + const tagged = value; + writeTag(tagged.tag, tagged.value); + return; + } + if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + writeList(ns, value, true, serdeContext); + } + else { + writeMap(ns, value, true, serdeContext); + } + return; + } + if (ns.isBigDecimalSchema()) { + writeUntypedValue(value); + return; + } + writeMap(ns, value, true, serdeContext); + return; + } + if (typeof value === "string") { + if (ns.isBlobSchema()) { + const bytes = (serdeContext?.base64Decoder ?? fromBase64)(value); + writeBytes(bytes); + return; + } + writeString(value); + return; + } + if (typeof value === "number") { + ensure(9); + if (Number.isInteger(value) && value >= -9007199254740992 && value <= 0x1fffffffffffff) { + writeInteger(value); + } + else { + writeFloat64(value); + } + return; + } + if (typeof value === "boolean") { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | (value ? specialTrue : specialFalse); + return; + } + if (typeof value === "bigint") { + writeBigInt(value); + return; + } + writeString(String(value)); +} +function writeStruct(ns, value, serdeContext) { + if (ns.isUnionSchema()) { + let wrote = false; + for (const [memberName, memberSchema] of ns.structIterator()) { + const item = value[memberName]; + if (item != null) { + ensure(9); + encodeHeader(majorMap, 1); + writeString(memberName); + writeValue(memberSchema, item, ns, serdeContext); + wrote = true; + break; + } + } + if (!wrote) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + ensure(9); + encodeHeader(majorMap, 1); + writeString($unknown[0]); + writeUntypedValue($unknown[1]); + } + else { + ensure(9); + encodeHeader(majorMap, 0); + } + } + return; + } + const cache = loadCborStructIterator(ns); + const { memberNames, memberSchemas, encodedKeys } = cache; + const z = memberNames.length; + let headerSize; + if (z < 24) { + headerSize = 1; + } + else if (z < 256) { + headerSize = 2; + } + else { + headerSize = 3; + } + ensure(headerSize); + const headerPos = cursor; + cursor += headerSize; + let count = 0; + for (let i = 0; i < z; ++i) { + const item = value[memberNames[i]]; + if (item == null && !memberSchemas[i].isIdempotencyToken()) { + continue; + } + const key = encodedKeys[i]; + ensure(key.length); + buf.set(key, cursor); + cursor += key.length; + writeValue(memberSchemas[i], item, ns, serdeContext); + ++count; + } + if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!memberNames.includes(k)) { + writeString(k); + writeUntypedValue(value[k]); + ++count; + } + } + } + if (headerSize === 1) { + buf[headerPos] = (majorMap << 5) | count; + } + else if (headerSize === 2) { + buf[headerPos] = (majorMap << 5) | 24; + buf[headerPos + 1] = count; + } + else { + buf[headerPos] = (majorMap << 5) | extendedFloat16; + buf[headerPos + 1] = count >> 8; + buf[headerPos + 2] = count & 0xff; + } +} +function writeList(ns, value, isDocument, serdeContext) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (isDocument || sparse) { + const items = []; + for (let i = 0; i < value.length; ++i) { + const item = value[i]; + if (isDocument) { + if (item !== undefined) { + items.push(item); + } + } + else { + if (item != null || sparse) { + items.push(item); + } + } + } + ensure(9); + encodeHeader(majorList, items.length); + for (let i = 0; i < items.length; ++i) { + writeValue(valueSchema, items[i], undefined, serdeContext); + } + } + else { + let count = 0; + for (let i = 0; i < value.length; ++i) { + if (value[i] != null) { + ++count; + } + } + ensure(9); + encodeHeader(majorList, count); + for (let i = 0; i < value.length; ++i) { + if (value[i] != null) { + writeValue(valueSchema, value[i], undefined, serdeContext); + } + } + } +} +function writeMap(ns, value, isDocument, serdeContext) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + const keys = []; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + const v = value[k]; + if (isDocument ? v !== undefined : v != null || sparse) { + keys.push(k); + } + } + ensure(9); + encodeHeader(majorMap, keys.length); + for (let i = 0; i < keys.length; ++i) { + const k = keys[i]; + writeString(k); + writeValue(valueSchema, value[k], undefined, serdeContext); + } +} +function writeUntypedValue(value) { + if (value == null) { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | specialNull; + return; + } + if (typeof value === "string") { + writeString(value); + return; + } + if (typeof value === "number") { + ensure(9); + if (Number.isInteger(value) && value >= -9007199254740992 && value <= 0x1fffffffffffff) { + writeInteger(value); + } + else { + writeFloat64(value); + } + return; + } + if (typeof value === "boolean") { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | (value ? specialTrue : specialFalse); + return; + } + if (typeof value === "bigint") { + writeBigInt(value); + return; + } + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + if (value instanceof Date) { + writeTimestamp(value); + return; + } + if (value instanceof NumericValue) { + writeNumericValue(value); + return; + } + if (value[tagSymbol]) { + const tagged = value; + writeTag(tagged.tag, tagged.value); + return; + } + if (Array.isArray(value)) { + ensure(9); + encodeHeader(majorList, value.length); + for (let i = 0; i < value.length; ++i) { + writeUntypedValue(value[i]); + } + return; + } + if (typeof value === "object") { + const keys = Object.keys(value); + ensure(9); + encodeHeader(majorMap, keys.length); + for (let i = 0; i < keys.length; ++i) { + writeString(keys[i]); + writeUntypedValue(value[keys[i]]); + } + return; + } + writeString(String(value)); +} +function ensure(n) { + if (cursor + n > buf.length) { + let newSize = buf.length * 2; + while (newSize < cursor + n) { + newSize *= 2; + } + const next = allocUnsafe(newSize); + next.set(buf.subarray(0, cursor)); + buf = next; + view = new DataView(next.buffer, next.byteOffset, next.byteLength); + } +} +function encodeHeader(major, value) { + if (value < 24) { + buf[cursor++] = (major << 5) | value; + } + else if (value < 256) { + buf[cursor++] = (major << 5) | 24; + buf[cursor++] = value; + } + else if (value < 65536) { + buf[cursor++] = (major << 5) | extendedFloat16; + buf[cursor++] = value >> 8; + buf[cursor++] = value & 0xff; + } + else if (value < 4294967296) { + buf[cursor++] = (major << 5) | extendedFloat32; + view.setUint32(cursor, value); + cursor += 4; + } + else { + buf[cursor++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + view.setUint32(cursor, hi); + view.setUint32(cursor + 4, lo); + cursor += 8; + } +} +function encodeBigHeader(major, value) { + const n = Number(value); + if (n < 4294967296) { + encodeHeader(major, n); + return; + } + buf[cursor++] = (major << 5) | extendedFloat64; + view.setBigUint64(cursor, value); + cursor += 8; +} +function writeString(s) { + const len = s.length; + if (len <= 23) { + const cached = stringEncodeCache.get(s); + if (cached) { + ensure(cached.bytes.length); + buf.set(cached.bytes, cursor); + cursor += cached.bytes.length; + cached.epoch = encodeCacheEpoch; + return; + } + const start = cursor; + writeStringUncached(s, len); + const end = cursor; + const bytes = Uint8Array.prototype.slice.call(buf, start, end); + if (stringEncodeCache.size >= STRING_CACHE_MAX) { + if (encodeCacheSaturated) { + return; + } + let evicted = 0; + for (const [key, entry] of stringEncodeCache) { + if (evicted >= 1024) { + break; + } + if (entry.epoch !== encodeCacheEpoch) { + stringEncodeCache.delete(key); + ++evicted; + } + } + if (evicted === 0) { + encodeCacheSaturated = true; + return; + } + } + if (stringEncodeCache.size < STRING_CACHE_MAX) { + stringEncodeCache.set(s, { epoch: encodeCacheEpoch, bytes }); + } + return; + } + writeStringUncached(s, len); +} +function writeStringUncached(s, len) { + if (USE_BUFFER$1) { + const maxBytes = len * 3; + ensure(maxBytes + 9); + const byteLen = Buffer.byteLength(s); + encodeHeader(majorUtf8String, byteLen); + cursor += buf.write(s, cursor); + } + else { + const maxBytes = len * 3; + ensure(maxBytes + 9); + const headerPos = cursor; + const result = textEncoder.encodeInto(s, buf.subarray(headerPos + 9)); + const byteLen = result.written; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else if (byteLen < 65536) { + headerSize = 3; + } + else if (byteLen < 4294967296) { + headerSize = 5; + } + else { + headerSize = 9; + } + if (headerSize < 9) { + buf.copyWithin(headerPos + headerSize, headerPos + 9, headerPos + 9 + byteLen); + } + cursor = headerPos; + encodeHeader(majorUtf8String, byteLen); + cursor += byteLen; + } +} +function writeFloat64(value) { + ensure(9); + buf[cursor++] = (majorSpecial << 5) | extendedFloat64; + view.setFloat64(cursor, value); + cursor += 8; +} +function writeInteger(value) { + ensure(9); + const nonNegative = value >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const abs = nonNegative ? value : -value - 1; + encodeHeader(major, abs); +} +function writeBigInt(value) { + const nonNegative = value >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const abs = nonNegative ? value : -value - BigInt(1); + if (abs < BigInt("18446744073709551616")) { + ensure(9); + encodeBigHeader(major, abs); + } + else { + const binaryStr = abs.toString(2); + const byteLen = Math.ceil(binaryStr.length / 8); + const bigIntBytes = new Uint8Array(byteLen); + let b = abs; + for (let i = byteLen - 1; i >= 0; --i) { + bigIntBytes[i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensure(byteLen + 16); + buf[cursor++] = nonNegative ? 0b110_00010 : 0b110_00011; + encodeHeader(majorUnstructuredByteString, byteLen); + buf.set(bigIntBytes, cursor); + cursor += byteLen; + } +} +function writeBytes(data) { + ensure(data.length + 9); + encodeHeader(majorUnstructuredByteString, data.length); + buf.set(data, cursor); + cursor += data.length; +} +function writeTag(tagValue, innerValue) { + ensure(9); + if (typeof tagValue === "bigint") { + encodeBigHeader(majorTag, tagValue); + } + else { + encodeHeader(majorTag, tagValue); + } + writeUntypedValue(innerValue); +} +function writeNumericValue(nv) { + let str = nv.string; + let expOffset = BigInt(0); + const eIndex = str.search(/[eE]/); + if (eIndex !== -1) { + expOffset = BigInt(str.slice(eIndex + 1)); + str = str.slice(0, eIndex); + } + const decimalIndex = str.indexOf("."); + const fractionDigits = decimalIndex === -1 ? 0 : str.length - decimalIndex - 1; + const exponent = expOffset - BigInt(fractionDigits); + const mantissa = BigInt(str.replace(".", "")); + ensure(9); + buf[cursor++] = 0b110_00100; + encodeHeader(majorList, 2); + ensure(9); + if (exponent >= -0x20000000000000n && exponent <= 0x1fffffffffffffn) { + writeInteger(Number(exponent)); + } + else { + writeBigInt(exponent); + } + writeBigInt(mantissa); +} +function writeTimestamp(date) { + ensure(18); + encodeHeader(majorTag, 1); + const epochSecs = date.getTime() / 1000; + if (Number.isInteger(epochSecs)) { + writeInteger(epochSecs); + } + else { + writeFloat64(epochSecs); + } +} + +class CborShapeDeserializer2 extends SerdeContext { + read(schema, bytes) { + payload = bytes; + isBuffer = USE_BUFFER && bytes instanceof Buffer; + dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + pos = 0; + end = bytes.length; + cacheEpoch = (cacheEpoch + 1) & 0xffff; + return readValue(NormalizedSchema.of(schema)); + } + readValue(_schema, value) { + return transformObject(NormalizedSchema.of(_schema), value); + } +} +const USE_BUFFER = typeof Buffer !== "undefined"; +const textDecoder = new TextDecoder(); +let payload = new Uint8Array(0); +let isBuffer = false; +let dataView = new DataView(new ArrayBuffer(0)); +let pos = 0; +let end = 0; +const STRING_CACHE_SIZE = 2048; +const stringCache = new Array(STRING_CACHE_SIZE); +const stringCacheEpochs = new Uint16Array(STRING_CACHE_SIZE); +let cacheEpoch = 0; +function readValue(ns) { + if (pos >= end) { + throw new Error("unexpected end of CBOR payload."); + } + const major = (payload[pos] & 0b1110_0000) >> 5; + const minor = payload[pos] & 0b0001_1111; + if (minor === minorIndefinite && major >= 2 && major <= 5) { + return readIndefinite(ns, major); + } + switch (major) { + case majorUint64: + return readUnsignedInt(); + case majorNegativeInt64: + return readNegativeInt(); + case majorUnstructuredByteString: + return readByteString(); + case majorUtf8String: + return readUtf8String(); + case majorList: + return readList(ns); + case majorMap: + return readMap(ns); + case majorTag: + return readTag(); + case majorSpecial: + return readSpecial(); + default: + throw new Error(`unexpected CBOR major type ${major}.`); + } +} +function readList(ns) { + const count = decodeCount(); + const memberSchema = ns.isListSchema() ? ns.getValueSchema() : ns; + const list = Array(count); + for (let i = 0; i < count; ++i) { + list[i] = readValue(memberSchema); + } + return list; +} +function readMap(ns) { + const count = decodeCount(); + if (ns.isStructSchema()) { + const startPos = pos; + return readStruct(ns, count, startPos); + } + const valueSchema = ns.isMapSchema() ? ns.getValueSchema() : ns; + const map = {}; + for (let i = 0; i < count; ++i) { + const key = readUtf8String(); + map[key] = readValue(valueSchema); + } + return map; +} +function readStruct(ns, count, startPos) { + const isUnion = ns.isUnionSchema(); + const cache = loadCborStructIterator(ns); + const { memberSchemas, encodedKeys, memberNames } = cache; + const z = encodedKeys.length; + const result = {}; + let unknownKey; + let unknownValue; + let unknownCount = 0; + let hasType = false; + let hint = 0; + for (let i = 0; i < count; ++i) { + const matchIdx = matchStructKey(encodedKeys, z, hint); + if (matchIdx >= 0) { + hint = matchIdx + 1; + if (hint >= z) { + hint = 0; + } + const val = readValue(memberSchemas[matchIdx]); + if (val != null) { + result[memberNames[matchIdx]] = val; + } + } + else { + const key = readUtf8String(); + const val = readValue(NormalizedSchema.of(15)); + if (key === "__type" && typeof val === "string") { + hasType = true; + } + else { + unknownKey = key; + unknownValue = val; + ++unknownCount; + } + } + } + if (isUnion) { + let resultEmpty = true; + for (const _ in result) { + if (!hasOwn(result, _)) + continue; + resultEmpty = false; + break; + } + if (resultEmpty && unknownCount === 1) { + result.$unknown = [unknownKey, unknownValue]; + } + } + else if (hasType) { + pos = startPos; + const docSchema = NormalizedSchema.of(15); + for (let i = 0; i < count; ++i) { + const key = readUtf8String(); + const val = readValue(docSchema); + if (!(key in result)) { + result[key] = val; + } + } + } + return result; +} +function readTag(ns) { + const tagNum = decodeArgument(); + const tagNumber = typeof tagNum === "bigint" ? Number(tagNum) : tagNum; + if (tagNumber === 1) { + const docSchema = NormalizedSchema.of(15); + const epochValue = readValue(docSchema); + return _parseEpochTimestamp(epochValue); + } + if (tagNumber === 2 || tagNumber === 3) { + const byteStr = readByteString(); + let b = BigInt(0); + for (let i = 0; i < byteStr.length; ++i) { + b = (b << BigInt(8)) | BigInt(byteStr[i]); + } + return tagNumber === 3 ? -b - BigInt(1) : b; + } + if (tagNumber === 4) { + const docSchema = NormalizedSchema.of(15); + const pair = readValue(docSchema); + const [rawExponent, mantissa] = pair; + const normalizer = mantissa < 0 ? -1 : 1; + const absMantissa = BigInt(normalizer) * BigInt(mantissa); + const mantissaDigits = String(absMantissa); + const sign = mantissa < 0 ? "-" : ""; + let numericString; + const isSmallExponent = typeof rawExponent === "number" && Math.abs(rawExponent) <= 2 ** 28; + if (isSmallExponent) { + const exponent = rawExponent; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + mantissaDigits; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + } + else { + const bigExponent = BigInt(rawExponent); + if (mantissaDigits.length === 1) { + numericString = sign + mantissaDigits + "e" + String(bigExponent); + } + else { + const adjustedExp = bigExponent + BigInt(mantissaDigits.length - 1); + numericString = sign + mantissaDigits[0] + "." + mantissaDigits.slice(1) + "e" + String(adjustedExp); + } + } + return nv(numericString); + } + const docSchema = NormalizedSchema.of(15); + const innerValue = readValue(docSchema); + return { tag: castBigInt(tagNum), value: innerValue }; +} +function readIndefinite(ns, major) { + switch (major) { + case majorUtf8String: + return readUtf8StringIndefinite(); + case majorUnstructuredByteString: + return readByteStringIndefinite(); + case majorList: + return readListIndefinite(ns); + case majorMap: + return readMapIndefinite(ns); + default: + throw new Error(`unexpected indefinite length for major ${major}.`); + } +} +function readUtf8StringIndefinite() { + pos += 1; + const chunks = []; + let totalLen = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + const combined = new Uint8Array(totalLen); + let offset = 0; + for (let i = 0; i < chunks.length; ++i) { + combined.set(chunks[i], offset); + offset += chunks[i].length; + } + if (USE_BUFFER) { + return Buffer.from(combined.buffer, combined.byteOffset, combined.byteLength).toString("utf-8"); + } + return textDecoder.decode(combined); + } + const bytes = readByteString(); + chunks.push(bytes); + totalLen += bytes.length; + } + throw new Error("expected break marker."); +} +function readByteStringIndefinite() { + pos += 1; + const chunks = []; + let totalLen = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + const combined = new Uint8Array(totalLen); + let offset = 0; + for (let i = 0; i < chunks.length; ++i) { + combined.set(chunks[i], offset); + offset += chunks[i].length; + } + return combined; + } + const bytes = readByteString(); + chunks.push(bytes); + totalLen += bytes.length; + } + throw new Error("expected break marker."); +} +function readListIndefinite(ns) { + pos += 1; + const memberSchema = ns.isListSchema() ? ns.getValueSchema() : ns; + const list = []; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + return list; + } + list.push(readValue(memberSchema)); + } + throw new Error("expected break marker."); +} +function readMapIndefinite(ns) { + pos += 1; + if (ns.isStructSchema()) { + const cache = loadCborStructIterator(ns); + const { memberSchemas, encodedKeys, memberNames } = cache; + const z = encodedKeys.length; + const isUnion = ns.isUnionSchema(); + const result = {}; + let unknownKey; + let unknownValue; + let unknownCount = 0; + let hint = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + if (isUnion) { + let resultEmpty = true; + for (const _ in result) { + if (!hasOwn(result, _)) + continue; + resultEmpty = false; + break; + } + if (resultEmpty && unknownCount === 1) { + result.$unknown = [unknownKey, unknownValue]; + } + } + return result; + } + const matchIdx = matchStructKey(encodedKeys, z, hint); + if (matchIdx >= 0) { + hint = matchIdx + 1; + if (hint >= z) { + hint = 0; + } + const val = readValue(memberSchemas[matchIdx]); + if (val != null) { + result[memberNames[matchIdx]] = val; + } + } + else { + const key = readUtf8String(); + const val = readValue(NormalizedSchema.of(15)); + if (key !== "__type") { + unknownKey = key; + unknownValue = val; + ++unknownCount; + } + } + } + throw new Error("expected break marker."); + } + const valueSchema = ns.isMapSchema() ? ns.getValueSchema() : ns; + const map = {}; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + return map; + } + const key = readUtf8String(); + map[key] = readValue(valueSchema); + } + throw new Error("expected break marker."); +} +function matchStructKey(encodedKeys, z, hint) { + const hintKey = encodedKeys[hint]; + if (pos + hintKey.length <= end && bytesMatch(pos, hintKey)) { + pos += hintKey.length; + return hint; + } + for (let i = 0; i < z; ++i) { + if (i === hint) { + continue; + } + const ek = encodedKeys[i]; + if (pos + ek.length <= end && bytesMatch(pos, ek)) { + pos += ek.length; + return i; + } + } + return -1; +} +function bytesMatch(at, expected) { + const len = expected.length; + if (payload[at] !== expected[0]) { + return false; + } + for (let i = 1; i < len; ++i) { + if (payload[at + i] !== expected[i]) { + return false; + } + } + return true; +} +function decodeArgument() { + const minor = payload[pos] & 0b0001_1111; + if (minor < 24) { + pos += 1; + return minor; + } + switch (minor) { + case extendedOneByte: + if (end - pos < 2) { + overflow(1); + } + pos += 2; + return payload[pos - 1]; + case extendedFloat16: + if (end - pos < 3) { + overflow(2); + } + pos += 3; + return dataView.getUint16(pos - 2); + case extendedFloat32: + if (end - pos < 5) { + overflow(4); + } + pos += 5; + return dataView.getUint32(pos - 4); + case extendedFloat64: { + if (end - pos < 9) { + overflow(8); + } + pos += 9; + const hi = dataView.getUint32(pos - 8); + if (hi < 0x00200000) { + return hi * 4294967296 + dataView.getUint32(pos - 4); + } + return dataView.getBigUint64(pos - 8); + } + default: + throw new Error(`unexpected minor value ${minor}.`); + } +} +function decodeCount() { + const val = decodeArgument(); + return typeof val === "bigint" ? Number(val) : val; +} +function readUnsignedInt() { + const val = decodeArgument(); + return castBigInt(val); +} +function readNegativeInt() { + const val = decodeArgument(); + if (typeof val === "bigint") { + return BigInt(-1) - val; + } + return -1 - val; +} +function readByteString() { + const length = decodeCount(); + if (end - pos < length) { + overflow(length); + } + const start = pos; + pos += length; + return payload.subarray(start, start + length); +} +function readUtf8String() { + const length = decodeCount(); + if (end - pos < length) { + overflow(length); + } + const start = pos; + pos += length; + if (length < 24) { + return decodeUtf8Cached(start, length); + } + if (isBuffer) { + return payload.toString("utf-8", start, start + length); + } + return textDecoder.decode(payload.subarray(start, start + length)); +} +function decodeUtf8Cached(at, length) { + let h = length; + for (let i = 0; i < length; ++i) { + h = (h * 31 + payload[at + i]) | 0; + } + const slot = (h >>> 0) & (STRING_CACHE_SIZE - 1); + const cached = stringCache[slot]; + if (cached !== undefined && cached.length === length) { + let match = true; + for (let i = 0; i < length; ++i) { + if (cached.charCodeAt(i) !== payload[at + i]) { + match = false; + break; + } + } + if (match) { + stringCacheEpochs[slot] = cacheEpoch; + return cached; + } + } + const result = isBuffer + ? payload.toString("utf-8", at, at + length) + : textDecoder.decode(payload.subarray(at, at + length)); + if (stringCacheEpochs[slot] !== cacheEpoch) { + stringCache[slot] = result; + stringCacheEpochs[slot] = cacheEpoch; + } + return result; +} +function readSpecial() { + const p = pos; + const minor = payload[p] & 0b0001_1111; + switch (minor) { + case specialTrue: + pos = p + 1; + return true; + case specialFalse: + pos = p + 1; + return false; + case specialNull: + pos = p + 1; + return null; + case specialUndefined: + pos = p + 1; + return null; + case extendedFloat16: { + if (end - p < 3) { + overflow(2); + } + pos = p + 3; + return bytesToFloat16(payload[p + 1], payload[p + 2]); + } + case extendedFloat32: { + if (end - p < 5) { + overflow(4); + } + pos = p + 5; + return dataView.getFloat32(p + 1); + } + case extendedFloat64: { + if (end - p < 9) { + overflow(8); + } + pos = p + 9; + return dataView.getFloat64(p + 1); + } + default: + throw new Error(`unexpected minor value ${minor} for major 7.`); + } +} +function bytesToFloat16(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + if (exponent === 0b00000) { + if (fraction === 0) { + return 0; + } + return scalar * (Math.pow(2, 1 - 15) * (fraction / 1024)); + } + else if (exponent === 0b11111) { + if (fraction === 0) { + return scalar * Infinity; + } + return NaN; + } + return scalar * (Math.pow(2, exponent - 15) * (1 + fraction / 1024)); +} +function castBigInt(value) { + if (typeof value === "number") { + return value; + } + const num = Number(value); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return value; +} +function overflow(n) { + throw new Error(`CBOR: length ${n} greater than remaining buffer length.`); +} +function transformObject(ns, value) { + if (ns.isTimestampSchema()) { + if (typeof value === "number") { + return _parseEpochTimestamp(value); + } + if (typeof value === "object" && value !== null) { + if (value.tag === 1 && "value" in value) { + return _parseEpochTimestamp(value.value); + } + } + } + if (ns.isBlobSchema()) { + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + if (typeof value !== "object" || value === null) { + return value; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (value instanceof NumericValue) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const memberSchema = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(transformObject(memberSchema, item)); + } + return out; + } + const newObject = {}; + if (ns.isMapSchema()) { + const targetSchema = ns.getValueSchema(); + for (const key in value) { + if (!hasOwn(value, key)) + continue; + newObject[key] = transformObject(targetSchema, value[key]); + } + } + else if (ns.isStructSchema()) { + const isUnion = ns.isUnionSchema(); + let keys; + if (isUnion) { + keys = new Set(); + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (k !== "__type") { + keys.add(k); + } + } + } + for (const [key, memberSchema] of ns.structIterator()) { + if (isUnion) { + keys.delete(key); + } + if (value[key] != null) { + newObject[key] = transformObject(memberSchema, value[key]); + } + } + if (isUnion && keys?.size === 1) { + let newObjectEmpty = true; + for (const _ in newObject) { + if (!hasOwn(newObject, _)) + continue; + newObjectEmpty = false; + break; + } + if (newObjectEmpty) { + const k = keys.values().next().value; + newObject.$unknown = [k, value[k]]; + } + } + else if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!(k in newObject)) { + newObject[k] = value[k]; + } + } + } + } + return newObject; +} + +class CborCodec extends SerdeContext { + createSerializer() { + const serializer = new CborShapeSerializer2(); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new CborShapeDeserializer2(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class SmithyRpcV2CborProtocol extends RpcProtocol { + codec = new CborCodec(); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace, errorTypeRegistries, }) { + super({ defaultNamespace, errorTypeRegistries }); + } + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType(), + }); + if (deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } + else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + if (request.body instanceof Uint8Array) { + request.headers["content-length"] = String(request.body.byteLength); + } + } + const { service, operation } = getSmithyContext(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } + else { + request.path += path; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode <= 500 ? "client" : "server", + }; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const registry = this.compositeErrorRegistry; + const nsRegistry = TypeRegistry.for(namespace); + registry.copyFrom(nsRegistry); + let errorSchema; + try { + errorSchema = registry.getSchema(errorName); + } + catch (ignored) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const syntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + registry.copyFrom(syntheticRegistry); + const baseExceptionSchema = registry.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = registry.getErrorCtor(baseExceptionSchema); + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = registry.getErrorCtor(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor({}); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/cbor"; + } +} + +class CborShapeSerializer extends SerdeContext { + value; + write(schema, value) { + this.value = this.serialize(schema, value); + } + serialize(schema, source) { + const ns = NormalizedSchema.of(schema); + if (source == null) { + if (ns.isIdempotencyToken()) { + return generateIdempotencyToken(); + } + return source; + } + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? fromBase64)(source); + } + return source; + } + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date((Number(source) / 1000) | 0)); + } + return dateToTag(source); + } + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i++] = value; + } + } + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key in sourceObject) { + if (!hasOwn(sourceObject, key)) + continue; + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + const isUnion = ns.isUnionSchema(); + if (isUnion && Array.isArray(sourceObject.$unknown)) { + const [k, v] = sourceObject.$unknown; + newObject[k] = v; + } + else if (typeof sourceObject.__type === "string") { + for (const k in sourceObject) { + if (!hasOwn(sourceObject, k)) + continue; + if (!(k in newObject)) { + newObject[k] = this.serialize(15, sourceObject[k]); + } + } + } + } + else if (ns.isDocumentSchema()) { + if (Array.isArray(sourceObject)) { + const newArray = []; + let i = 0; + for (const item of sourceObject) { + newArray[i++] = this.serialize(ns.getValueSchema(), item); + } + return newArray; + } + for (const key in sourceObject) { + if (!hasOwn(sourceObject, key)) + continue; + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + } + } + else if (ns.isBigDecimalSchema()) { + return sourceObject; + } + return newObject; + } + return source; + } + flush() { + const buffer = cbor.serialize(this.value); + this.value = undefined; + return buffer; + } +} + +class CborShapeDeserializer extends SerdeContext { + read(schema, bytes) { + const data = cbor.deserialize(bytes); + return this.readValue(schema, data); + } + readValue(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isTimestampSchema()) { + if (typeof value === "number") { + return _parseEpochTimestamp(value); + } + if (typeof value === "object") { + if (value.tag === 1 && "value" in value) { + return _parseEpochTimestamp(value.value); + } + } + } + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + else if (typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + newArray.push(itemValue); + } + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const targetSchema = ns.getValueSchema(); + for (const key in value) { + if (!hasOwn(value, key)) + continue; + const itemValue = this.readValue(targetSchema, value[key]); + newObject[key] = itemValue; + } + } + else if (ns.isStructSchema()) { + const isUnion = ns.isUnionSchema(); + let keys; + if (isUnion) { + keys = new Set(); + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (k !== "__type") { + keys.add(k); + } + } + } + for (const [key, memberSchema] of ns.structIterator()) { + if (isUnion) { + keys.delete(key); + } + if (value[key] != null) { + newObject[key] = this.readValue(memberSchema, value[key]); + } + } + if (isUnion && keys?.size === 1) { + let newObjectEmpty = true; + for (const _ in newObject) { + if (!hasOwn(newObject, _)) + continue; + newObjectEmpty = false; + break; + } + if (newObjectEmpty) { + const k = keys.values().next().value; + newObject.$unknown = [k, value[k]]; + } + } + else if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!(k in newObject)) { + newObject[k] = value[k]; + } + } + } + } + else if (value instanceof NumericValue) { + return value; + } + return newObject; + } + else { + return value; + } + } +} + +exports.CborCodec = CborCodec; +exports.CborShapeDeserializer = CborShapeDeserializer; +exports.CborShapeDeserializer2 = CborShapeDeserializer2; +exports.CborShapeSerializer = CborShapeSerializer; +exports.CborShapeSerializer2 = CborShapeSerializer2; +exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol; +exports.buildHttpRpcRequest = buildHttpRpcRequest; +exports.cbor = cbor; +exports.checkCborResponse = checkCborResponse; +exports.dateToTag = dateToTag; +exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; +exports.parseCborBody = parseCborBody; +exports.parseCborErrorBody = parseCborErrorBody; +exports.tag = tag; +exports.tagSymbol = tagSymbol; + + +/***/ }), + +/***/ 7629: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { createReadStream } = __webpack_require__(73024); +const { Writable } = __webpack_require__(57075); +const { toUint8Array, concatBytes } = __webpack_require__(26591); +const { createHash, createHmac } = __webpack_require__(77598); +const zlib = __webpack_require__(38522); + +async function blobReader(blob, onChunk, chunkSize = 1024 * 1024) { + const size = blob.size; + let totalBytesRead = 0; + while (totalBytesRead < size) { + const slice = blob.slice(totalBytesRead, Math.min(size, totalBytesRead + chunkSize)); + onChunk(new Uint8Array(await slice.arrayBuffer())); + totalBytesRead += slice.size; + } +} + +const blobHasher = async function blobHasher(hashCtor, blob) { + const hash = new hashCtor(); + await blobReader(blob, (chunk) => { + hash.update(chunk); + }); + return hash.digest(); +}; + +class HashCalculator extends Writable { + hash; + constructor(hash, options) { + super(options); + this.hash = hash; + } + _write(chunk, encoding, callback) { + try { + this.hash.update(toUint8Array(chunk)); + } + catch (err) { + return callback(err); + } + callback(); + } +} + +const fileStreamHasher = (hashCtor, fileStream) => new Promise((resolve, reject) => { + if (!isReadStream(fileStream)) { + reject(new Error("Unable to calculate hash for non-file streams.")); + return; + } + const fileStreamTee = createReadStream(fileStream.path, { + start: fileStream.start, + end: fileStream.end, + }); + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + fileStreamTee.pipe(hashCalculator); + fileStreamTee.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", function () { + hash.digest().then(resolve).catch(reject); + }); +}); +const isReadStream = (stream) => typeof stream.path === "string"; + +const readableStreamHasher = (hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); + } + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + readableStream.pipe(hashCalculator); + return new Promise((resolve, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash.digest().then(resolve).catch(reject); + }); + }); +}; + +class Md5Js { + digestLength = 16; + state = Uint32Array.from(INIT$1); + writeBuffer = new DataView(new ArrayBuffer(64)); + bufferLength = 0; + bytesHashed = 0; + update(sourceData) { + const data = toUint8Array(sourceData); + let pos = 0; + let len = data.byteLength; + this.bytesHashed += len; + while (len > 0) { + this.writeBuffer.setUint8(this.bufferLength++, data[pos++]); + --len; + if (this.bufferLength === 64) { + compress(this.state, this.writeBuffer); + this.bufferLength = 0; + } + } + } + async digest() { + const state = Uint32Array.from(this.state); + const buf = new DataView(this.writeBuffer.buffer.slice(0)); + let bufLen = this.bufferLength; + const bits = this.bytesHashed * 8; + buf.setUint8(bufLen++, 0x80); + if (this.bufferLength % 64 >= 56) { + for (let i = bufLen; i < 64; ++i) { + buf.setUint8(i, 0); + } + compress(state, buf); + bufLen = 0; + } + for (let i = bufLen; i < 56; ++i) { + buf.setUint8(i, 0); + } + buf.setUint32(56, bits >>> 0, true); + buf.setUint32(60, Math.floor(bits / 2 ** 32), true); + compress(state, buf); + const out = new Uint8Array(16); + const view = new DataView(out.buffer); + for (let i = 0; i < 4; ++i) { + view.setUint32(i * 4, state[i], true); + } + return out; + } + reset() { + this.state.set(INIT$1); + this.writeBuffer = new DataView(new ArrayBuffer(64)); + this.bufferLength = 0; + this.bytesHashed = 0; + } +} +const INIT$1 = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; +const M = 0xffffffff; +const S = Uint8Array.of(7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21); +const T = Array.from({ length: 64 }, (_, i) => (Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0); +function compress(state, block) { + let a = state[0], b = state[1], c = state[2], d = state[3]; + for (let i = 0; i < 64; ++i) { + let f, g; + if (i < 16) { + f = (b & c) | (~b & d); + g = i; + } + else if (i < 32) { + f = (d & b) | (c & ~d); + g = (5 * i + 1) % 16; + } + else if (i < 48) { + f = b ^ c ^ d; + g = (3 * i + 5) % 16; + } + else { + f = c ^ (b | ~d); + g = (7 * i) % 16; + } + const x = block.getUint32(g * 4, true); + const tmp = d; + d = c; + c = b; + const s = S[(i >> 4) * 4 + (i & 3)]; + const sum = (((a + f) & M) + ((x + T[i]) & M)) & M; + b = (b + (((sum << s) | (sum >>> (32 - s))) >>> 0)) & M; + a = tmp; + } + state[0] = (state[0] + a) & M; + state[1] = (state[1] + b) & M; + state[2] = (state[2] + c) & M; + state[3] = (state[3] + d) & M; +} + +const hasNativeCrypto$1 = (() => { + try { + createHash("md5"); + return true; + } + catch { + return false; + } +})(); +const Md5Node = hasNativeCrypto$1 ? buildNativeClass$2() : Md5Js; +function buildNativeClass$2() { + return class Md5Node { + digestLength = 16; + hash = createHash("md5"); + update(data) { + this.hash.update(toUint8Array(data)); + } + async digest() { + const buf = this.hash.copy().digest(); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + reset() { + this.hash = createHash("md5"); + } + }; +} + +const CRC32_TABLE = new Uint32Array(256); +for (let i = 0; i < 256; ++i) { + let c = i; + for (let j = 0; j < 8; ++j) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + CRC32_TABLE[i] = c >>> 0; +} +const ONES = 0xffff_ffff; +class Crc32Js { + digestLength = 4; + checksum = ONES; + update(data) { + for (let i = 0; i < data.length; ++i) { + this.checksum = (this.checksum >>> 8) ^ CRC32_TABLE[(this.checksum ^ data[i]) & 0xff]; + } + } + digestSync() { + return (this.checksum ^ ONES) >>> 0; + } + async digest() { + const value = this.digestSync(); + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, value, false); + return out; + } + reset() { + this.checksum = ONES; + } +} + +const zlibCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : undefined; +const Crc32Node = zlibCrc32 ? buildNativeClass$1(zlibCrc32) : Crc32Js; +function buildNativeClass$1(nativeCrc32) { + return class Crc32Node { + digestLength = 4; + value = 0; + update(data) { + this.value = nativeCrc32(data, this.value); + } + digestSync() { + return this.value >>> 0; + } + async digest() { + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, this.digestSync(), false); + return out; + } + reset() { + this.value = 0; + } + }; +} + +const BLOCK = 64; +const DIGEST_LENGTH = 32; +const MAX_HASHABLE_LENGTH = 2 ** 53 - 1; +class Sha256Js { + digestLength = DIGEST_LENGTH; + state = Int32Array.from(INIT); + w; + buffer = new Uint8Array(64); + bufferLength = 0; + bytesHashed = 0; + finished = false; + inner; + outer; + constructor(secret) { + if (secret) { + const key = Sha256Js.normalizeKey(secret); + this.inner = new Sha256Js(); + this.outer = new Sha256Js(); + const { inner, outer } = this; + const pad = new Uint8Array(BLOCK * 2); + for (let i = 0; i < BLOCK; ++i) { + pad[i] = 0x36 ^ key[i]; + pad[i + BLOCK] = 0x5c ^ key[i]; + } + inner.update(pad.subarray(0, BLOCK)); + outer.update(pad.subarray(BLOCK)); + } + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished HMAC."); + } + if (this.inner) { + this.inner.update(data); + return; + } + const chunk = toUint8Array(data); + let position = 0; + let { byteLength } = chunk; + this.bytesHashed += byteLength; + if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) { + throw new Error("Cannot hash more than 2^53 - 1 bits"); + } + while (byteLength > 0) { + this.buffer[this.bufferLength++] = chunk[position++]; + byteLength--; + if (this.bufferLength === BLOCK) { + this.hashBuffer(); + this.bufferLength = 0; + } + } + } + async digest() { + const { inner, outer } = this; + if (inner && outer) { + if (this.finished) { + throw new Error("Attempted to digest an already finished HMAC."); + } + this.finished = true; + const innerDigest = inner.digestSync(); + outer.update(innerDigest); + return outer.digestSync(); + } + return this.digestSync(); + } + reset() { + this.state = Int32Array.from(INIT); + this.buffer = new Uint8Array(64); + this.bufferLength = 0; + this.bytesHashed = 0; + } + digestSync() { + const state = this.state.slice(); + const buffer = this.buffer.slice(); + let bufferLength = this.bufferLength; + const bitsHashed = this.bytesHashed * 8; + const bufferView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + bufferView.setUint8(bufferLength++, 0x80); + if ((bufferLength - 1) % BLOCK >= BLOCK - 8) { + for (let i = bufferLength; i < BLOCK; ++i) { + bufferView.setUint8(i, 0); + } + this.hashBufferWith(state, buffer); + bufferLength = 0; + } + for (let i = bufferLength; i < BLOCK - 8; ++i) { + bufferView.setUint8(i, 0); + } + bufferView.setUint32(BLOCK - 8, Math.floor(bitsHashed / 0x100000000), false); + bufferView.setUint32(BLOCK - 4, bitsHashed, false); + this.hashBufferWith(state, buffer); + const out = new Uint8Array(DIGEST_LENGTH); + for (let i = 0; i < 8; ++i) { + out[i * 4] = (state[i] >>> 24) & 0xff; + out[i * 4 + 1] = (state[i] >>> 16) & 0xff; + out[i * 4 + 2] = (state[i] >>> 8) & 0xff; + out[i * 4 + 3] = (state[i] >>> 0) & 0xff; + } + return out; + } + static normalizeKey(secret) { + const key = toUint8Array(secret); + if (key.byteLength > BLOCK) { + const h = new Sha256Js(); + h.update(key); + const out = h.digestSync(); + const padded = new Uint8Array(BLOCK); + padded.set(out); + return padded; + } + if (key.byteLength < BLOCK) { + const padded = new Uint8Array(BLOCK); + padded.set(key); + return padded; + } + return key; + } + hashBuffer() { + this.hashBufferWith(this.state, this.buffer); + } + hashBufferWith(state, buffer) { + const w = (this.w ??= new Int32Array(64)); + let s0 = state[0], s1 = state[1], s2 = state[2], s3 = state[3], s4 = state[4], s5 = state[5], s6 = state[6], s7 = state[7]; + for (let i = 0; i < BLOCK; ++i) { + if (i < 16) { + w[i] = + ((buffer[i * 4] & 0xff) << 24) | + ((buffer[i * 4 + 1] & 0xff) << 16) | + ((buffer[i * 4 + 2] & 0xff) << 8) | + (buffer[i * 4 + 3] & 0xff); + } + else { + let u = w[i - 2]; + const t1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10); + u = w[i - 15]; + const t2 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3); + w[i] = ((t1 + w[i - 7]) | 0) + ((t2 + w[i - 16]) | 0); + } + const t1 = ((((((s4 >>> 6) | (s4 << 26)) ^ ((s4 >>> 11) | (s4 << 21)) ^ ((s4 >>> 25) | (s4 << 7))) + + ((s4 & s5) ^ (~s4 & s6))) | + 0) + + ((s7 + ((K[i] + w[i]) | 0)) | 0)) | + 0; + const t2 = ((((s0 >>> 2) | (s0 << 30)) ^ ((s0 >>> 13) | (s0 << 19)) ^ ((s0 >>> 22) | (s0 << 10))) + + ((s0 & s1) ^ (s0 & s2) ^ (s1 & s2))) | + 0; + s7 = s6; + s6 = s5; + s5 = s4; + s4 = (s3 + t1) | 0; + s3 = s2; + s2 = s1; + s1 = s0; + s0 = (t1 + t2) | 0; + } + state[0] += s0; + state[1] += s1; + state[2] += s2; + state[3] += s3; + state[4] += s4; + state[5] += s5; + state[6] += s6; + state[7] += s7; + } +} +const INIT = new Int32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]); +const K = new Int32Array([ + 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, +]); + +const hasNativeCrypto = (() => { + try { + createHash("sha256"); + return true; + } + catch { + return false; + } +})(); +const Sha256Node = hasNativeCrypto ? buildNativeClass() : Sha256Js; +function buildNativeClass() { + return class Sha256Node { + digestLength = 32; + secret; + hash; + isHmac; + finished = false; + constructor(secret) { + this.secret = secret; + this.isHmac = !!secret; + this.hash = this.createHash(); + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished hash."); + } + this.hash.update(data); + } + async digest() { + let buf; + if (this.isHmac) { + this.finished = true; + buf = this.hash.digest(); + } + else { + buf = this.hash.copy().digest(); + } + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + reset() { + this.hash = this.createHash(); + this.finished = false; + } + createHash() { + return this.secret ? createHmac("sha256", toBuffer(this.secret)) : createHash("sha256"); + } + }; +} +function toBuffer(data) { + if (typeof data === "string") { + return data; + } + if (ArrayBuffer.isView(data)) { + return Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } + return Buffer.from(data); +} + +const { digest, sign, importKey } = globalThis?.crypto?.subtle ?? {}; +const subtle = typeof digest === "function" && typeof sign === "function" && typeof importKey === "function" + ? globalThis.crypto.subtle + : undefined; +const MAX_PENDING_BYTES = 8 * 1024 * 1024; +class Sha256WebCrypto { + digestLength = 32; + secret; + pending = []; + pendingBytes = 0; + fallback; + finished = false; + constructor(secret) { + if (secret) { + this.secret = toUint8Array(secret); + } + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished HMAC."); + } + if (this.fallback) { + this.fallback.update(data); + return; + } + this.pending.push(data.slice()); + this.pendingBytes += data.byteLength; + if (this.pendingBytes >= MAX_PENDING_BYTES) { + this.switchToFallback(); + } + } + async digest() { + if (this.fallback) { + return this.fallback.digest(); + } + if (this.secret && this.finished) { + throw new Error("Attempted to digest an already finished HMAC."); + } + const data = concatBytes(this.pending); + if (subtle) { + if (this.secret) { + this.finished = true; + const key = await subtle.importKey("raw", this.secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); + const sig = await subtle.sign("HMAC", key, data); + return new Uint8Array(sig); + } + const hash = await subtle.digest("SHA-256", data); + return new Uint8Array(hash); + } + const sha256 = new Sha256Js(this.secret); + sha256.update(data); + return sha256.digest(); + } + reset() { + this.pending = []; + this.pendingBytes = 0; + this.fallback = undefined; + this.finished = false; + } + switchToFallback() { + const sha256Js = new Sha256Js(this.secret); + for (const chunk of this.pending) { + sha256Js.update(chunk); + } + this.fallback = sha256Js; + this.pending = []; + this.pendingBytes = 0; + } +} + +exports.Crc32 = Crc32Node; +exports.Crc32Js = Crc32Js; +exports.Crc32Node = Crc32Node; +exports.Md5 = Md5Node; +exports.Md5Js = Md5Js; +exports.Md5Node = Md5Node; +exports.Sha256 = Sha256Node; +exports.Sha256Js = Sha256Js; +exports.Sha256Node = Sha256Node; +exports.Sha256WebCrypto = Sha256WebCrypto; +exports.blobHasher = blobHasher; +exports.blobReader = blobReader; +exports.fileStreamHasher = fileStreamHasher; +exports.readableStreamHasher = readableStreamHasher; + + +/***/ }), + +/***/ 40417: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { hasOwn } = __webpack_require__(74875); +const { getSmithyContext, normalizeProvider } = __webpack_require__(74875); +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; +const { SMITHY_CONTEXT_KEY, AlgorithmId } = __webpack_require__(88867); +exports.AlgorithmId = AlgorithmId; +const { NormalizedSchema } = __webpack_require__(31829); + +const getAllAliases = (name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; +}; +const getMiddlewareNameWithAliases = (name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}; +const constructStack = () => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = new Set(); + const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] || + priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]); + const removeByName = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const removeByReference = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const cloneTo = (toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }; + const expandRelativeMiddlewareList = (from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }; + const getMiddlewareList = (debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === undefined) { + if (debug) { + return; + } + throw new Error(`${entry.toMiddleware} is not found when adding ` + + `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + + `middleware ${entry.relation} ${entry.toMiddleware}`); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries) + .map(expandRelativeMiddlewareList) + .reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }; + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + + `${toOverride.priority} priority in ${toOverride.step} step cannot ` + + `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + + `${entry.priority} priority in ${entry.step} step.`); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + + `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + + `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + + `"${entry.toMiddleware}" middleware.`); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? + mw.relation + + " " + + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList() + .map((entry) => entry.middleware) + .reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + }, + }; + return stack; +}; +const stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1, +}; +const priorityWeights = { + high: 3, + normal: 2, + low: 1, +}; + +const invalidFunction = (message) => () => { + throw new Error(message); +}; + +const invalidProvider = (message) => () => Promise.reject(message); + +const getCircularReplacer = () => { + const seen = new WeakSet(); + return (key, value) => { + if (typeof value === "object" && value !== null) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }; +}; + +const sleep = (seconds) => { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); +}; + +const waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120, +}; +var WaiterState; +(function (WaiterState) { + WaiterState["ABORTED"] = "ABORTED"; + WaiterState["FAILURE"] = "FAILURE"; + WaiterState["SUCCESS"] = "SUCCESS"; + WaiterState["RETRY"] = "RETRY"; + WaiterState["TIMEOUT"] = "TIMEOUT"; +})(WaiterState || (WaiterState = {})); +const checkExceptions = (result) => { + if (result.state === WaiterState.ABORTED) { + const abortError = new Error(`${JSON.stringify({ + ...result, + reason: "Request was aborted", + }, getCircularReplacer())}`); + abortError.name = "AbortError"; + throw abortError; + } + else if (result.state === WaiterState.TIMEOUT) { + const timeoutError = new Error(`${JSON.stringify({ + ...result, + reason: "Waiter has timed out", + }, getCircularReplacer())}`); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } + else if (result.state !== WaiterState.SUCCESS) { + throw new Error(`${JSON.stringify(result, getCircularReplacer())}`); + } + return result; +}; + +const runPolling = async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const [minDelayMs, maxDelayMs] = [minDelay * 1000, maxDelay * 1000]; + let currentAttempt = 0; + const waitUntil = Date.now() + maxWaitTime * 1000; + const warn403Time = Date.now() + 60_000; + let didWarn403 = false; + while (true) { + if (currentAttempt > 0) { + const delayMs = exponentialBackoffWithJitter(minDelayMs, maxDelayMs, currentAttempt, waitUntil); + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message = "AbortController signal aborted."; + observedResponses[message] |= 0; + observedResponses[message] += 1; + return { state: WaiterState.ABORTED, observedResponses }; + } + if (Date.now() + delayMs > waitUntil) { + return { state: WaiterState.TIMEOUT, observedResponses }; + } + await sleep(delayMs / 1_000); + } + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state !== WaiterState.RETRY) { + return { state, reason, final: reason, observedResponses }; + } + currentAttempt += 1; + if (!didWarn403 && Date.now() >= warn403Time) { + checkWarn403(observedResponses, client); + didWarn403 = true; + } + } +}; +const checkWarn403 = (observedResponses = {}, client) => { + const orderedErrors = Object.keys(observedResponses); + let count403 = 0; + for (const response of orderedErrors) { + const n = observedResponses[response] | 0; + if (response.startsWith("403:")) { + count403 += n; + } + } + const clientLogger = client?.config?.logger; + const warningLogger = typeof clientLogger?.warn === "function" && !clientLogger.constructor?.name?.includes?.("NoOpLogger") + ? clientLogger + : console; + if (count403 >= 3 || orderedErrors[orderedErrors.length - 1]?.startsWith("403:")) { + warningLogger.warn(`@smithy/util-waiter WARN - 403 status code encountered during waiter polling.`); + } +}; +const createMessageFromResponse = (reason) => { + const status = reason?.$response?.statusCode ?? reason?.$metadata?.httpStatusCode; + if (reason?.$responseBodyText) { + return `${status ? status + ": " : ""}Deserialization error for body: ${reason.$responseBodyText}`; + } + if (status) { + if (reason?.$response || reason?.message) { + return `${status ?? "Unknown"}: ${reason?.message}`; + } + return `${status}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason, getCircularReplacer()) ?? "Unknown"); +}; +const exponentialBackoffWithJitter = (minDelayMs, maxDelayMs, attempt, waitUntil) => { + const attemptCountCeiling = Math.log(maxDelayMs / minDelayMs) / Math.log(2) + 1; + if (attempt > attemptCountCeiling) { + return maxDelayMs; + } + const delay = minDelayMs * 2 ** (attempt - 1); + const capped = Math.min(delay, maxDelayMs); + const waitFor = randomInRange(minDelayMs, capped); + if (Date.now() + waitFor > waitUntil) { + const timeRemaining = waitUntil - Date.now(); + return Math.max(0, timeRemaining - 500); + } + return waitFor; +}; +const randomInRange = (min, max) => min + Math.random() * (max - min); + +const validateWaiterOptions = (options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } + else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } + else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } + else if (options.maxWaitTime <= options.minDelay) { + throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } + else if (options.maxDelay < options.minDelay) { + throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } +}; + +const abortTimeout = (abortSignal) => { + let onAbort; + const promise = new Promise((resolve) => { + onAbort = () => resolve({ state: WaiterState.ABORTED }); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + }); + return { + clearListener() { + if (typeof abortSignal.removeEventListener === "function") { + abortSignal.removeEventListener("abort", onAbort); + } + }, + aborted: promise, + }; +}; +const createWaiter = async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options, + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + const finalize = []; + if (options.abortSignal) { + const { aborted, clearListener } = abortTimeout(options.abortSignal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + if (options.abortController?.signal) { + const { aborted, clearListener } = abortTimeout(options.abortController.signal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + return Promise.race(exitConditions).then((result) => { + for (const fn of finalize) { + fn(); + } + return result; + }); +}; + +class Client { + config; + middlewareStack = constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + const { protocol, protocolSettings } = config; + if (protocolSettings) { + if (typeof protocol === "function") { + config.protocol = new protocol(protocolSettings); + } + } + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema, data) { + if (data == null) { + return data; + } + const ns = NormalizedSchema.of(schema); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext, + }, + ...additionalContext, + }; + const { requestHandler } = configuration; + let requestOptions = options ?? {}; + if (smithyContext.eventStream) { + requestOptions = { + isEventStream: true, + ...requestOptions, + }; + } + return stack.resolve((request) => requestHandler.handle(request.request, requestOptions), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client, options) => { + for (const [command, CommandCtor] of Object.entries(commands)) { + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } + const { paginators = {}, waiters = {} } = options ?? {}; + for (const [paginatorName, paginatorFn] of Object.entries(paginators)) { + if (Client.prototype[paginatorName] === void 0) { + Client.prototype[paginatorName] = function (commandInput = {}, paginationConfiguration, ...rest) { + return paginatorFn({ + ...paginationConfiguration, + client: this, + }, commandInput, ...rest); + }; + } + } + for (const [waiterName, waiterFn] of Object.entries(waiters)) { + if (Client.prototype[waiterName] === void 0) { + Client.prototype[waiterName] = async function (commandInput = {}, waiterConfiguration, ...rest) { + let config = waiterConfiguration; + if (typeof waiterConfiguration === "number") { + config = { + maxWaitTime: waiterConfiguration, + }; + } + return waiterFn({ + ...config, + client: this, + }, commandInput, ...rest); + }; + } + } +}; + +class ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const knownAlgorithms = Object.values(AlgorithmId); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in AlgorithmId) { + if (!hasOwn(AlgorithmId, id)) + continue; + const algorithmId = AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) { + checksumAlgorithms.push({ + algorithmId: () => id, + checksumConstructor: () => ChecksumCtor, + }); + } + return { + addChecksumAlgorithm(algo) { + runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {}; + const id = algo.algorithmId(); + const ctor = algo.checksumConstructor(); + if (knownAlgorithms.includes(id)) { + runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor; + } + else { + runtimeConfig.checksumAlgorithms[id] = ctor; + } + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + const id = checksumAlgorithm.algorithmId(); + if (knownAlgorithms.includes(id)) { + runtimeConfig[id] = checksumAlgorithm.checksumConstructor(); + } + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (!hasOwn(obj, key)) + continue; + if (obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key in instructions) { + if (!hasOwn(instructions, key)) + continue; + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + if (!hasOwn(instructions, key)) + continue; + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key in obj) { + if (!hasOwn(obj, key)) + continue; + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +function makeBuilder(common, service, name, ep) { + return function makeCommand(added, plugins, op, $, smithyContext = {}) { + const epMerged = Object.assign({}, common, added); + return Command.classBuilder() + .ep(epMerged) + .m(function (CommandCtor, clientStack, config, options) { + const list = plugins.call(this, CommandCtor, clientStack, config, options); + list.unshift(ep(config, CommandCtor.getEndpointParameterInstructions())); + return list; + }) + .s(service, op, smithyContext) + .n(name, op.charAt(0).toUpperCase() + op.slice(1) + "Command") + .sc($) + .build(); + }; +} + +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports.WaiterState = WaiterState; +exports._json = _json; +exports.checkExceptions = checkExceptions; +exports.constructStack = constructStack; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.createWaiter = createWaiter; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getChecksumConfiguration = getChecksumConfiguration; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getRetryConfiguration = getRetryConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.invalidFunction = invalidFunction; +exports.invalidProvider = invalidProvider; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.makeBuilder = makeBuilder; +exports.map = map; +exports.resolveChecksumRuntimeConfig = resolveChecksumRuntimeConfig; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.resolveRetryRuntimeConfig = resolveRetryRuntimeConfig; +exports.schemaLogFilter = schemaLogFilter; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.waiterServiceDefaults = waiterServiceDefaults; +exports.withBaseException = withBaseException; + + +/***/ }), + +/***/ 48132: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { homedir } = __webpack_require__(48161); +const { sep, join } = __webpack_require__(76760); +const { createHash } = __webpack_require__(77598); +const { readFile: readFile$1 } = __webpack_require__(51455); +const { IniSectionType } = __webpack_require__(88867); +const { normalizeProvider } = __webpack_require__(40417); +const { isValidHostLabel } = __webpack_require__(74875); + +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +} + +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); + } +} + +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); + } +} + +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +const fromValue = (staticValue) => () => Promise.resolve(staticValue); + +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}; + +const booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}; + +const numberSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}; + +var SelectorType; +(function (SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; +})(SelectorType || (SelectorType = {})); + +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = homedir(); + return homeDirCache[homeDirCacheKey]; +}; + +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + +const getSSOTokenFilepath = (id) => { + const hasher = createHash("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return join(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`); +}; + +const tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (tokenIntercept[id]) { + return tokenIntercept[id]; + } + const ssoTokenFilepath = getSSOTokenFilepath(id); + const ssoTokenText = await readFile$1(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; + +const CONFIG_PREFIX_SEPARATOR = "."; + +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; +}, { + ...(data.default && { default: data.default }), +}); + +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || join(getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || join(getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } + } + return map; +}; + +const filePromises = {}; +const fileIntercept = {}; +const readFile = (path, options) => { + if (fileIntercept[path] !== undefined) { + return fileIntercept[path]; + } + if (!filePromises[path] || options?.ignoreCache) { + filePromises[path] = readFile$1(path, "utf8"); + } + return filePromises[path]; +}; + +const swallowError$1 = () => ({}); +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = join(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = join(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + readFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + readFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; +}; + +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => readFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); + +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } + } + } + return merged; +}; + +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; + +const externalDataInterceptor = { + getFileRecord() { + return fileIntercept; + }, + interceptFile(path, contents) { + fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return tokenIntercept; + }, + interceptToken(id, contents) { + tokenIntercept[id] = contents; + }, +}; + +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } + catch (ignored) { + return functionString; + } +} + +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); + } + return config; + } + catch (e) { + throw new CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); + } +}; + +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = getProfileName(init); + const { configFile, credentialsFile } = await loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } + catch (e) { + throw new CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); + } +}; + +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : fromValue(defaultValue); + +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +const DEFAULT_USE_DUALSTACK_ENDPOINT = false; +const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG), + default: false, +}; +const nodeDualstackConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG), + default: undefined, +}; + +const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +const DEFAULT_USE_FIPS_ENDPOINT = false; +const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG), + default: false, +}; +const nodeFipsConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG), + default: undefined, +}; + +const resolveCustomEndpointsConfig = (input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), + }); +}; + +const getEndpointFromRegion = async (input) => { + const { tls = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}; + +const resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint + ? normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) + : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint, + }); +}; + +const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +const AWS_REGION_ENV = "AWS_REGION"; +const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +const IMDS_REGION_PATH = "/latest/meta-data/placement/region"; +const IMDS_TOKEN_PATH = "/latest/api/token"; +const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +const X_AWS_EC2_METADATA_TOKEN_TTL = "x-aws-ec2-metadata-token-ttl-seconds"; + +const TIMEOUT_MS = 1000; +const NEG_CACHE_TTL_MS = 60_000; +let negativeCacheUntil = 0; +const getInstanceMetadataRegion = async () => { + if (process.env[ENV_IMDS_DISABLED]) { + return undefined; + } + if (Date.now() < negativeCacheUntil) { + return undefined; + } + try { + const endpoint = resolveImdsEndpoint(); + const token = (await imdsRequest({ + ...endpoint, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + [X_AWS_EC2_METADATA_TOKEN_TTL]: "21600", + }, + })).toString(); + const region = (await imdsRequest({ + ...endpoint, + path: IMDS_REGION_PATH, + method: "GET", + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token, + }, + })) + .toString() + .trim(); + return region || cacheNegativeAndReturnUndefined(); + } + catch { + return cacheNegativeAndReturnUndefined(); + } +}; +const cacheNegativeAndReturnUndefined = () => { + negativeCacheUntil = Date.now() + NEG_CACHE_TTL_MS; + return undefined; +}; +const resolveImdsEndpoint = () => { + const envEndpoint = process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT; + if (envEndpoint) { + const url = new URL(envEndpoint); + return { + hostname: url.hostname.replace(/^\[(.+)]$/, "$1"), + port: url.port ? Number(url.port) : undefined, + }; + } + if (process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE === "IPv6") { + return { hostname: "fd00:ec2::254" }; + } + return { hostname: "169.254.169.254" }; +}; +const imdsRequest = async (options) => { + const { request } = __webpack_require__(37067); + return new Promise((resolve, reject) => { + const req = request({ + hostname: options.hostname, + port: options.port, + path: options.path, + method: options.method, + headers: options.headers, + timeout: TIMEOUT_MS, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + req.on("error", (err) => { + reject(err); + req.destroy(); + }); + req.on("timeout", () => { + reject(new Error("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || statusCode >= 300) { + reject(Object.assign(new Error("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + return; + } + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + resolve(Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); +}; + +const REGION_ENV_NAME = "AWS_REGION"; +const REGION_INI_NAME = "region"; +const NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: async () => { + const region = await getInstanceMetadataRegion(); + if (region) { + return region; + } + throw new Error("Region is missing"); + }, +}; +const NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials", +}; + +const validRegions = new Set(); +const checkRegion = (region, check = isValidHostLabel) => { + if (!validRegions.has(region) && !check(region)) { + if (region === "*") { + console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); + } + else { + throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); + } + } + else { + validRegions.add(region); + } +}; + +const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); + +const getRealRegion = (region) => isFipsRegion(region) + ? ["fips-aws-global", "aws-fips"].includes(region) + ? "us-east-1" + : region.replace(/fips-(dkr-|prod-)?|-fips/, "") + : region; + +const resolveRegionConfig = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: async () => { + const providedRegion = typeof region === "function" ? await region() : region; + const realRegion = getRealRegion(providedRegion); + checkRegion(realRegion); + return realRegion; + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, + }); +}; + +const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; + +const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname + ? regionHostname + : partitionHostname + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; + +const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; + +const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; + } + else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } + } +}; + +const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : (partitionHash[partition]?.endpoint ?? region); + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === undefined) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + } + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint, + }); + return { + partition, + signingService, + hostname, + ...(signingRegion && { signingRegion }), + ...(regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService, + }), + }; +}; + +const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy", +}; + +const resolveDefaultsModeConfig = ({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case undefined: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); + } +}); +const resolveNodeDefaultsModeAuto = async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } + else { + return "cross-region"; + } + } + return "standard"; +}; +const inferPhysicalRegion = async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + return getInstanceMetadataRegion(); +}; + +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; +exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; +exports.CredentialsProviderError = CredentialsProviderError; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; +exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; +exports.ENV_PROFILE = ENV_PROFILE; +exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; +exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; +exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; +exports.ProviderError = ProviderError; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.SelectorType = SelectorType; +exports.TokenProviderError = TokenProviderError; +exports.booleanSelector = booleanSelector; +exports.chain = chain; +exports.externalDataInterceptor = externalDataInterceptor; +exports.fromStatic = fromStatic; +exports.fromValue = fromValue; +exports.getHomeDir = getHomeDir; +exports.getProfileName = getProfileName; +exports.getRegionInfo = getRegionInfo; +exports.getSSOTokenFilepath = getSSOTokenFilepath; +exports.getSSOTokenFromFile = getSSOTokenFromFile; +exports.loadConfig = loadConfig; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.memoize = memoize; +exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors; +exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors; +exports.numberSelector = numberSelector; +exports.parseKnownFiles = parseKnownFiles; +exports.readFile = readFile; +exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; +exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; +exports.resolveEndpointsConfig = resolveEndpointsConfig; +exports.resolveRegionConfig = resolveRegionConfig; + + +/***/ }), + +/***/ 19564: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { CONFIG_PREFIX_SEPARATOR, booleanSelector, SelectorType, loadConfig } = __webpack_require__(48132); +const { toEndpointV1, getSmithyContext, normalizeProvider, isValidHostLabel, hasOwn } = __webpack_require__(74875); +exports.isValidHostLabel = isValidHostLabel; +exports.middlewareEndpointToEndpointV1 = toEndpointV1; +exports.toEndpointV1 = toEndpointV1; +const { EndpointURLScheme } = __webpack_require__(88867); + +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (profile.services) { + const servicesSectionKey = ["services", profile.services].join(CONFIG_PREFIX_SEPARATOR); + if (!config || !config[servicesSectionKey]) { + throw new Error(`The services section "${profile.services}" specified in the profile is not present in the shared configuration file.`); + } + const servicesSection = config[servicesSectionKey]; + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); + +const ENV_IGNORE_CONFIGURED_ENDPOINT_URLS = "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS"; +const CONFIG_IGNORE_CONFIGURED_ENDPOINT_URLS = "ignore_configured_endpoint_urls"; +const ignoreConfiguredEndpointUrlsConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_IGNORE_CONFIGURED_ENDPOINT_URLS, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_IGNORE_CONFIGURED_ENDPOINT_URLS, SelectorType.CONFIG), + default: false, +}; + +const getEndpointFromConfig = async (serviceId) => { + const ignore = await loadConfig(ignoreConfiguredEndpointUrlsConfigSelectors)(); + if (ignore) { + return undefined; + } + return loadConfig(getEndpointUrlConfig(serviceId ?? ""))(); +}; + +const resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } + else if (!isDnsCompatibleBucketName(bucket) || + (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || + bucket.toLowerCase() !== bucket || + bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}; +const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/; +const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +const DOTS_PATTERN = /\.\./; +const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); +const isArnBucketName = (bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}; + +const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config, isClientContextParam = false) => { + const configProvider = async () => { + let configValue; + if (isClientContextParam) { + const clientContextParams = config.clientContextParams; + const nestedValue = clientContextParams?.[configKey]; + configValue = nestedValue ?? config[configKey] ?? config[canonicalEndpointParamKey]; + } + else { + configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + } + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return undefined; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}; + +function bindGetEndpointFromInstructions(getEndpointFromConfig) { + return async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint && !clientConfig.ignoreConfiguredEndpointUrls) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } + else { + endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + context?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${endpointFromConfig}`); + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + if (clientConfig.isCustomEndpoint && clientConfig.endpoint) { + const customEndpoint = await clientConfig.endpoint(); + if (customEndpoint?.headers) { + endpoint.headers ??= {}; + for (const [name, value] of Object.entries(customEndpoint.headers)) { + endpoint.headers[name] = Array.isArray(value) ? value : [value]; + } + } + } + return endpoint; + }; +} +const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== "builtInParams")(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}; + +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { features: {} }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +function bindEndpointMiddleware(getEndpointFromConfig) { + const getEndpointFromInstructions = bindGetEndpointFromInstructions(getEndpointFromConfig); + return ({ config, instructions, }) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + setFeature(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + }, + }, { ...config }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet, + }, authScheme.properties); + } + } + return next({ + ...args, + }); + }; + }; +} + +const serializerMiddlewareOption = { + name: "serializerMiddleware"}; +const endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: serializerMiddlewareOption.name, +}; +function bindGetEndpointPlugin(getEndpointFromConfig) { + const endpointMiddleware = bindEndpointMiddleware(getEndpointFromConfig); + return (config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config, + instructions, + }), endpointMiddlewareOptions); + }, + }); +} + +function bindResolveEndpointConfig(getEndpointFromConfig) { + return (input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : undefined; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false), + ignoreConfiguredEndpointUrls: !!input.ignoreConfiguredEndpointUrls, + }); + let configuredEndpointPromise = undefined; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; + }; +} + +class BinaryDecisionDiagram { + nodes; + root; + conditions; + results; + constructor(bdd, root, conditions, results) { + this.nodes = bdd; + this.root = root; + this.conditions = conditions; + this.results = results; + } + static from(bdd, root, conditions, results) { + return new BinaryDecisionDiagram(bdd, root, conditions, results); + } +} + +class EndpointCache { + capacity; + data = new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } + } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; + } +} + +class EndpointError extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; + } +} + +const debugId = "endpoints"; + +function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); +} + +const customEndpointFunctions = {}; + +const booleanEquals = (value1, value2) => value1 === value2; + +function coalesce(...args) { + for (const arg of args) { + if (arg != null) { + return arg; + } + } + return undefined; +} + +const getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } + else { + pathList.push(part); + } + } + return pathList; +}; + +const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } + else if (Array.isArray(acc)) { + const i = parseInt(index); + return acc[i < 0 ? acc.length + i : i]; + } + return acc[index]; +}, value); + +const isSet = (value) => value != null; + +function ite(condition, trueValue, falseValue) { + return condition ? trueValue : falseValue; +} + +const not = (value) => !value; + +const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); +const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); + +const DEFAULT_PORTS = { + [EndpointURLScheme.HTTP]: 80, + [EndpointURLScheme.HTTPS]: 443, +}; +const parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname, port, protocol = "", path = "", query = {} } = value; + const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query) + .map(([k, v]) => `${k}=${v}`) + .join("&"); + return url; + } + return new URL(value); + } + catch (ignored) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || + (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp, + }; +}; + +function split(value, delimiter, limit) { + if (limit === 1) { + return [value]; + } + if (value === "") { + return [""]; + } + const parts = value.split(delimiter); + if (limit === 0) { + return parts; + } + return parts.slice(0, limit - 1).concat(parts.slice(1).join(delimiter)); +} + +const stringEquals = (value1, value2) => value1 === value2; + +const substring = (input, start, stop, reverse) => { + if (input == null || start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); +}; + +const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + +const endpointFunctions = { + booleanEquals, + coalesce, + getAttr, + isSet, + isValidHostLabel, + ite, + not, + parseURL, + split, + stringEquals, + substring, + uriEncode, +}; + +const evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const { referenceRecord, endpointParams } = options; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr((referenceRecord[refName] ?? endpointParams[refName]), attrName)); + } + else { + evaluatedTemplateArr.push((referenceRecord[parameterName] ?? endpointParams[parameterName])); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); +}; + +const getReferenceValue = ({ ref }, options) => { + return options.referenceRecord[ref] ?? options.endpointParams[ref]; +}; + +const evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } + else if (obj["fn"]) { + return group$2.callFunction(obj, options); + } + else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}; +const callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = Array(argv.length); + for (let i = 0; i < evaluatedArgs.length; ++i) { + const arg = argv[i]; + if (typeof arg === "boolean" || typeof arg === "number") { + evaluatedArgs[i] = arg; + } + else { + evaluatedArgs[i] = group$2.evaluateExpression(arg, "arg", options); + } + } + const namespaceSeparatorIndex = fn.indexOf("."); + if (namespaceSeparatorIndex !== -1) { + const namespaceFunctions = customEndpointFunctions[fn.slice(0, namespaceSeparatorIndex)]; + const customFunction = namespaceFunctions?.[fn.slice(namespaceSeparatorIndex + 1)]; + if (typeof customFunction === "function") { + return customFunction(...evaluatedArgs); + } + } + const callable = endpointFunctions[fn]; + if (typeof callable === "function") { + return callable(...evaluatedArgs); + } + throw new Error(`function ${fn} not loaded in endpointFunctions.`); +}; +const group$2 = { + evaluateExpression, + callFunction, +}; + +const evaluateCondition = (condition, options) => { + const { assign } = condition; + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(condition, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(condition)} = ${toDebugString(value)}`); + const result = value === "" ? true : !!value; + if (assign != null) { + return { result, toAssign: { name: assign, value } }; + } + return { result }; +}; + +const getEndpointHeaders = (headers, options) => Object.entries(headers ?? {}).reduce((acc, [headerKey, headerVal]) => { + acc[headerKey] = headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }); + return acc; +}, {}); + +const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => { + acc[propertyKey] = group$1.getEndpointProperty(propertyVal, options); + return acc; +}, {}); +const getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return group$1.getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}; +const group$1 = { + getEndpointProperty, + getEndpointProperties, +}; + +const getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } + catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}; + +const RESULT = 100_000_000; +const decideEndpoint = (bdd, options) => { + const { nodes, root, results, conditions } = bdd; + let ref = root; + const referenceRecord = {}; + const closure = { + referenceRecord, + endpointParams: options.endpointParams, + logger: options.logger, + }; + while (ref !== 1 && ref !== -1 && ref < RESULT) { + const node_i = 3 * (Math.abs(ref) - 1); + const [condition_i, highRef, lowRef] = [nodes[node_i], nodes[node_i + 1], nodes[node_i + 2]]; + const [fn, argv, assign] = conditions[condition_i]; + const evaluation = evaluateCondition({ fn, assign, argv }, closure); + if (evaluation.toAssign) { + const { name, value } = evaluation.toAssign; + referenceRecord[name] = value; + } + ref = ref >= 0 === evaluation.result ? highRef : lowRef; + } + if (ref >= RESULT) { + const result = results[ref - RESULT]; + if (result[0] === -1) { + const [, errorExpression] = result; + throw new EndpointError(evaluateExpression(errorExpression, "Error", closure)); + } + const [url, properties, headers] = result; + return { + url: getEndpointUrl(url, closure), + properties: getEndpointProperties(properties, closure), + headers: getEndpointHeaders(headers ?? {}, closure), + }; + } + throw new EndpointError(`No matching endpoint.`); +}; + +const evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + const conditionOptions = { + ...options, + referenceRecord: { ...options.referenceRecord }, + }; + let didAssign = false; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, conditionOptions); + if (!result) { + return { result }; + } + if (toAssign) { + didAssign = true; + conditionsReferenceRecord[toAssign.name] = toAssign.value; + conditionOptions.referenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + if (didAssign) { + return { result: true, referenceRecord: conditionsReferenceRecord }; + } + return { result: true }; +}; + +const evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = referenceRecord + ? { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + } + : options; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + const endpointToReturn = { url: getEndpointUrl(url, endpointRuleOptions) }; + if (headers != null) { + endpointToReturn.headers = getEndpointHeaders(headers, endpointRuleOptions); + } + if (properties != null) { + endpointToReturn.properties = getEndpointProperties(properties, endpointRuleOptions); + } + return endpointToReturn; +}; + +const evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const errorRuleOptions = referenceRecord + ? { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + } + : options; + throw new EndpointError(evaluateExpression(error, "Error", errorRuleOptions)); +}; + +const evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } + else if (rule.type === "tree") { + const endpointOrUndefined = group.evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); +}; +const evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const treeRuleOptions = referenceRecord + ? { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } } + : options; + return group.evaluateRules(rules, treeRuleOptions); +}; +const group = { + evaluateRules, + evaluateTreeRule, +}; + +const resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + for (const paramKey in parameters) { + if (!hasOwn(parameters, paramKey)) + continue; + const parameter = parameters[paramKey]; + const endpointParam = endpointParams[paramKey]; + if (endpointParam == null && parameter.default != null) { + endpointParams[paramKey] = parameter.default; + continue; + } + if (parameter.required && endpointParam == null) { + throw new EndpointError(`Missing required parameter: '${paramKey}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}; + +const resolveEndpointRequiredConfig = (input) => { + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); + }; + } + return input; +}; + +const getEndpointFromInstructions = bindGetEndpointFromInstructions(getEndpointFromConfig); +const resolveEndpointConfig = bindResolveEndpointConfig(getEndpointFromConfig); +const endpointMiddleware = bindEndpointMiddleware(getEndpointFromConfig); +const getEndpointPlugin = bindGetEndpointPlugin(getEndpointFromConfig); + +exports.BinaryDecisionDiagram = BinaryDecisionDiagram; +exports.EndpointCache = EndpointCache; +exports.EndpointError = EndpointError; +exports.customEndpointFunctions = customEndpointFunctions; +exports.decideEndpoint = decideEndpoint; +exports.endpointMiddleware = endpointMiddleware; +exports.endpointMiddlewareOptions = endpointMiddlewareOptions; +exports.getEndpointFromInstructions = getEndpointFromInstructions; +exports.getEndpointPlugin = getEndpointPlugin; +exports.isIpAddress = isIpAddress; +exports.resolveEndpoint = resolveEndpoint; +exports.resolveEndpointConfig = resolveEndpointConfig; +exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; +exports.resolveParams = resolveParams; + + +/***/ }), + +/***/ 49458: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Crc32 } = __webpack_require__(7629); +const { hasOwn } = __webpack_require__(74875); +const { toHex, fromHex, toUtf8, fromUtf8 } = __webpack_require__(26591); +const { Readable } = __webpack_require__(57075); +const { TypeRegistry } = __webpack_require__(31829); + +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +class HeaderMarshaller { + toUtf8; + fromUtf8; + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + format(headers) { + const chunks = []; + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex(header.value.replace(/-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true, + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false, + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++), + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false), + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false), + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)), + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength), + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)), + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()), + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${toHex(uuidBytes.subarray(0, 4))}-${toHex(uuidBytes.subarray(4, 6))}-${toHex(uuidBytes.subarray(6, 8))}-${toHex(uuidBytes.subarray(8, 10))}-${toHex(uuidBytes.subarray(10))}`, + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } +} +var HEADER_VALUE_TYPE; +(function (HEADER_VALUE_TYPE) { + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"] = 3] = "short"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"] = 5] = "long"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"] = 7] = "string"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"] = 9] = "uuid"; +})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); +const BOOLEAN_TAG = "boolean"; +const BYTE_TAG = "byte"; +const SHORT_TAG = "short"; +const INT_TAG = "integer"; +const LONG_TAG = "long"; +const BINARY_TAG = "binary"; +const STRING_TAG = "string"; +const TIMESTAMP_TAG = "timestamp"; +const UUID_TAG = "uuid"; +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +const PRELUDE_MEMBER_LENGTH = 4; +const PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +const CHECKSUM_LENGTH = 4; +const MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new Crc32(); + checksummer.update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digestSync()) { + throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digestSync()})`); + } + checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); + if (expectedMessageChecksum !== checksummer.digestSync()) { + throw new Error(`The message checksum (${checksummer.digestSync()}) did not match the expected value of ${expectedMessageChecksum}`); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)), + }; +} + +class EventStreamCodec { + headerMarshaller; + messageBuffer; + isEndOfStream; + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + checksum.update(out.subarray(0, 8)); + view.setUint32(8, checksum.digestSync(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + checksum.update(out.subarray(8, length - 4)); + view.setUint32(length - 4, checksum.digestSync(), false); + return out; + } + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +} + +class MessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } +} + +class MessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } +} + +class SmithyMessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === undefined) + continue; + yield deserialized; + } + } +} + +class SmithyMessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } +} + +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } + else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } + else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator, + }; +} + +function getUnmarshalledStream(source, options) { + const messageUnmarshaller = getMessageUnmarshaller(options.deserializer, options.toUtf8); + return { + [Symbol.asyncIterator]: async function* () { + for await (const chunk of source) { + const message = options.eventStreamCodec.decode(chunk); + const type = await messageUnmarshaller(message); + if (type === undefined) + continue; + yield type; + } + }, + }; +} +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function (message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } + else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } + else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message, + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } + else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} + +let EventStreamMarshaller$1 = class EventStreamMarshaller { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new SmithyMessageDecoderStream({ + messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder), + }); + } + serialize(inputStream, serializer) { + return new MessageEncoderStream({ + messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true, + }); + } +}; +const eventStreamSerdeProvider$1 = (options) => new EventStreamMarshaller$1(options); + +class EventStreamMarshaller { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new EventStreamMarshaller$1({ + utf8Decoder, + utf8Encoder, + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readableToIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +} +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); +async function* readableToIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } +} + +const readableStreamToIterable = (readableStream) => ({ + [Symbol.asyncIterator]: async function* () { + const reader = readableStream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) + return; + yield value; + } + } + finally { + reader.releaseLock(); + } + }, +}); +const iterableToReadableStream = (asyncIterable) => { + const iterator = asyncIterable[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const { done, value } = await iterator.next(); + if (done) { + return controller.close(); + } + controller.enqueue(value); + }, + }); +}; + +const resolveEventStreamSerdeConfig = (input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input), +}); + +class EventStreamSerde { + marshaller; + serializer; + deserializer; + serdeContext; + defaultContentType; + compositeErrorRegistry; + constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, compositeErrorRegistry, }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + this.compositeErrorRegistry = compositeErrorRegistry; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, initialMessageType, }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: initialMessageType ?? "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType }, + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body, + }; + } + for await (const page of eventStream) { + yield page; + } + }, + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body, + }; + } + let unionMember = ""; + for (const key in event) { + if (!hasOwn(event, key)) + continue; + if (key !== "__type") { + unionMember = key; + break; + } + } + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders, + }; + return { + headers, + body, + }; + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, initialMessageType, }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + let unionMember = ""; + for (const key in event) { + if (!hasOwn(event, key)) + continue; + if (key !== "__type") { + unionMember = key; + break; + } + } + const body = event[unionMember].body; + if (unionMember === (initialMessageType ?? "initial-response")) { + const dataObject = await this.deserializer.read(responseSchema, body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject, + }; + } + else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + if (eventStreamSchema.isStructSchema()) { + const out = {}; + let hasBindings = false; + for (const [name, member] of eventStreamSchema.structIterator()) { + const { eventHeader, eventPayload } = member.getMergedTraits(); + hasBindings = hasBindings || Boolean(eventHeader || eventPayload); + if (eventPayload) { + if (member.isBlobSchema()) { + out[name] = body; + } + else if (member.isStringSchema()) { + out[name] = (this.serdeContext?.utf8Encoder ?? toUtf8)(body); + } + else if (member.isStructSchema()) { + out[name] = await this.deserializer.read(member, body); + } + } + else if (eventHeader) { + const value = event[unionMember].headers[name]?.value; + if (value != null) { + if (member.isNumericSchema()) { + if (value && typeof value === "object" && "bytes" in value) { + out[name] = BigInt(value.toString()); + } + else { + out[name] = Number(value); + } + } + else { + out[name] = value; + } + } + } + } + return { + [unionMember]: await this.readEventMember(eventStreamSchema, body, hasBindings, out), + }; + } + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, body), + }; + } + else { + return { + $unknown: event, + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; + } + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); + } + for (const key in firstEvent.value) { + if (!hasOwn(firstEvent.value, key)) + continue; + initialResponseContainer[key] = firstEvent.value[key]; + } + } + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + }, + }; + } + async readEventMember(eventStreamSchema, body, hasBindings, out) { + let ErrCtor; + const staticStructuralSchema = eventStreamSchema.getSchema(); + if (Array.isArray(staticStructuralSchema) && staticStructuralSchema[0] === -3) { + const namespace = staticStructuralSchema[1]; + const nsRegistry = TypeRegistry.for(namespace); + this.compositeErrorRegistry?.copyFrom(nsRegistry); + ErrCtor = (this.compositeErrorRegistry ?? nsRegistry)?.getErrorCtor(staticStructuralSchema); + } + const dataObject = hasBindings + ? out + : body.byteLength === 0 + ? {} + : await this.deserializer.read(eventStreamSchema, body); + if (ErrCtor) { + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const metadata = {}; + const $fault = eventStreamSchema.getMergedTraits().error; + if ($fault) { + metadata.$fault = $fault; + } + return Object.assign(new ErrCtor({}), metadata, { + message, + }, dataObject); + } + return dataObject; + } + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = (() => { + const struct = unionSchema.getSchema(); + return struct[4].includes(unionMember); + })(); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(15, value); + } + else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + } + else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } + else { + type = "long"; + } + } + else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } + else if (memberSchema.isStringSchema()) { + type = "string"; + } + else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value, + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } + else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } + else { + serializer.write(eventSchema, event[unionMember]); + } + } + else if (eventSchema.isUnitSchema()) { + serializer.write(eventSchema, {}); + } + else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush() ?? new Uint8Array(); + const body = typeof messageSerialization === "string" + ? (this.serdeContext?.utf8Decoder ?? fromUtf8)(messageSerialization) + : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders, + }; + } +} + +exports.EventStreamCodec = EventStreamCodec; +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.EventStreamSerde = EventStreamSerde; +exports.HeaderMarshaller = HeaderMarshaller; +exports.Int64 = Int64; +exports.MessageDecoderStream = MessageDecoderStream; +exports.MessageEncoderStream = MessageEncoderStream; +exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; +exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; +exports.UniversalEventStreamMarshaller = EventStreamMarshaller$1; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; +exports.getChunkedStream = getChunkedStream; +exports.getMessageUnmarshaller = getMessageUnmarshaller; +exports.getUnmarshalledStream = getUnmarshalledStream; +exports.iterableToReadableStream = iterableToReadableStream; +exports.readableStreamToIterable = readableStreamToIterable; +exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; +exports.universalEventStreamSerdeProvider = eventStreamSerdeProvider$1; + + +/***/ }), + +/***/ 37015: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Uint8ArrayBlobAdapter, sdkStreamMixin, splitEvery, splitHeader, fromBase64, _parseEpochTimestamp, _parseRfc7231DateTime, _parseRfc3339DateTimeWithOffset, LazyJsonString, NumericValue, toUtf8, fromUtf8, generateIdempotencyToken, toBase64, dateToUtcString, quoteHeader } = __webpack_require__(26591); +const { HttpRequest, HttpResponse, hasOwn, isValidHostname } = __webpack_require__(74875); +const { parseQueryString, parseUrl } = __webpack_require__(74875); +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.isValidHostname = isValidHostname; +exports.parseQueryString = parseQueryString; +exports.parseUrl = parseUrl; +const { TypeRegistry, NormalizedSchema, translateTraits } = __webpack_require__(31829); +const { FieldPosition } = __webpack_require__(88867); + +const collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return Uint8ArrayBlobAdapter.mutate(await fromContext); +}; + +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +class SerdeContext { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class HttpProtocol extends SerdeContext { + options; + compositeErrorRegistry; + constructor(options) { + super(); + this.options = options; + this.compositeErrorRegistry = TypeRegistry.for(options.defaultNamespace); + for (const etr of options.errorTypeRegistries ?? []) { + this.compositeErrorRegistry.copyFrom(etr); + } + } + getRequestType() { + return HttpRequest; + } + getResponseType() { + return HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + if (!request.query) { + request.query = {}; + } + for (const [k, v] of endpoint.url.searchParams.entries()) { + request.query[k] = v; + } + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + request.headers[name] = endpoint.headers[name].join(", "); + } + } + return request; + } + else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : undefined; + request.path = endpoint.path; + request.query = { + ...endpoint.query, + }; + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + request.headers[name] = endpoint.headers[name]; + } + } + return request; + } + } + setHostPrefix(request, operationSchema, input) { + if (this.serdeContext?.disableHostPrefix) { + return; + } + const inputNs = NormalizedSchema.of(operationSchema.input); + const opTraits = translateTraits(operationSchema.traits ?? {}); + if (opTraits.endpoint) { + let hostPrefix = opTraits.endpoint?.[0]; + if (typeof hostPrefix === "string") { + for (const [name, member] of inputNs.structIterator()) { + if (!member.getMergedTraits().hostLabel) { + continue; + } + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + if (!isValidHostname(request.hostname)) { + throw new Error(`[${request.hostname}] is not a valid hostname.`); + } + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], + }; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest, + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer, + }); + } + async loadEventStreamCapability() { + const { EventStreamSerde, eventStreamSerdeProvider } = __webpack_require__(49458); + const marshaller = this.resolveEventStreamMarshaller(eventStreamSerdeProvider); + return new EventStreamSerde({ + marshaller, + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType(), + compositeErrorRegistry: this.compositeErrorRegistry, + }); + } + resolveEventStreamMarshaller(importedProvider) { + const context = this.serdeContext; + if (context.eventStreamMarshaller) { + return context.eventStreamMarshaller; + } + return importedProvider(this.serdeContext); + } + getDefaultContentType() { + throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } +} + +class HttpBindingProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = _input && typeof _input === "object" ? _input : {}; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const payloadMemberNames = []; + const payloadMemberSchemas = []; + let hasNonHttpBindingMember = false; + let payload; + const request = new HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } + else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + for (const [key, value] of traitSearchParams) { + query[key] = value; + } + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { + if (memberTraits.httpLabel) { + if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) { + throw new Error(`No value provided for input HTTP label: ${memberName}.`); + } + } + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns, + }); + } + } + else { + payload = inputMemberValue; + } + } + else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + } + else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); + } + else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + } + else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + } + else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const key in inputMemberValue) { + if (!hasOwn(inputMemberValue, key)) + continue; + const val = inputMemberValue[key]; + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + } + else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + } + else { + hasNonHttpBindingMember = true; + payloadMemberNames.push(memberName); + payloadMemberSchemas.push(memberNs); + } + } + if (hasNonHttpBindingMember && input) { + const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#"); + const requiredMembers = ns.getSchema()[6]; + const payloadSchema = [ + 3, + namespace, + name, + ns.getMergedTraits(), + payloadMemberNames, + payloadMemberSchemas, + undefined, + ]; + if (requiredMembers) { + payloadSchema[6] = requiredMembers; + } + else { + payloadSchema.pop(); + } + serializer.write(payloadSchema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const key in data) { + if (!hasOwn(data, key)) + continue; + if (!(key in query)) { + const val = data[key]; + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + ...traits, + httpQuery: key, + httpQueryParams: undefined, + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== undefined) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } + else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + if (dataFromBody[member] != null) { + dataObject[member] = dataFromBody[member]; + } + } + } + } + else if (nonHttpBindingMembers.discardResponseBody) { + await collectBody(response.body, context); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } + else { + dataObject = arg4; + } + let discardResponseBody = true; + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + discardResponseBody = false; + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns, + }); + } + else { + dataObject[memberName] = sdkStreamMixin(response.body); + } + } + else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } + else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && + headerListValueSchema.getSchema() === 4) { + sections = splitEvery(value, ",", 2); + } + else { + sections = splitHeader(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } + else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } + else if (memberTraits.httpPrefixHeaders !== undefined) { + dataObject[memberName] = {}; + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const value = response.headers[header]; + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); + } + } + } + else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } + else { + nonHttpBindingMembers.push(memberName); + } + } + nonHttpBindingMembers.discardResponseBody = discardResponseBody; + return nonHttpBindingMembers; + } +} + +class RpcProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const input = _input && typeof _input === "object" ? _input : {}; + const request = new HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "/", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName] of ns.structIterator()) { + if (memberName !== eventStreamMember && input[memberName] != null) { + initialRequest[memberName] = input[memberName]; + } + } + payload = await this.serializeEventStream({ + eventStream: input[eventStreamMember], + requestSchema: ns, + initialRequest, + }); + } + } + else { + serializer.write(schema, input); + payload = serializer.flush(); + } + } + request.headers = Object.assign(request.headers, headers); + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject, + }); + } + else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } +} + +const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== undefined) { + const labelValue = labelValueProvider(); + if (labelValue == null || labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel + ? labelValue + .split("/") + .map((segment) => extendedEncodeURIComponent(segment)) + .join("/") + : extendedEncodeURIComponent(labelValue)); + } + else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath; +}; + +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +class RequestBuilder { + input; + context; + query = {}; + method = ""; + headers = {}; + path = ""; + body = null; + hostname = ""; + resolvePathStack = []; + constructor(input, context) { + this.input = input; + this.context = context; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers, + }); + } + hn(hostname) { + this.hostname = hostname; + return this; + } + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + h(headers) { + this.headers = headers; + return this; + } + q(query) { + this.query = query; + return this; + } + b(body) { + this.body = body; + return this; + } + m(method) { + this.method = method; + return this; + } +} + +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && + (ns.getSchema() === 5 || + ns.getSchema() === 6 || + ns.getSchema() === 7)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings + ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) + ? 6 + : Boolean(httpQuery) || Boolean(httpLabel) + ? 5 + : undefined + : undefined; + return bindingFormat ?? settings.timestampFormat.default; +} + +class FromStringShapeDeserializer extends SerdeContext { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + read(_schema, data) { + const ns = NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); + } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? fromBase64)(data); + } + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return _parseRfc3339DateTimeWithOffset(data); + case 6: + return _parseRfc7231DateTime(data); + case 7: + return _parseEpochTimestamp(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + if (ns.isNumericSchema()) { + return Number(data); + } + if (ns.isBigIntegerSchema()) { + return BigInt(data); + } + if (ns.isBigDecimalSchema()) { + return new NumericValue(data, "bigDecimal"); + } + if (ns.isBooleanSchema()) { + return String(data).toLowerCase() === "true"; + } + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? toUtf8)((this.serdeContext?.base64Decoder ?? fromBase64)(base64String)); + } +} + +class HttpInterceptingShapeDeserializer extends SerdeContext { + codecDeserializer; + stringDeserializer; + constructor(codecDeserializer, codecSettings) { + super(); + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema, data) { + const ns = NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } + else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } + } + return this.codecDeserializer.read(ns, data); + } +} + +class ToStringShapeSerializer extends SerdeContext { + settings; + stringBuffer = ""; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + this.stringBuffer = dateToUtcString(value); + break; + case 7: + this.stringBuffer = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1000); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + if (ns.isIdempotencyToken()) { + this.stringBuffer = generateIdempotencyToken(); + } + else { + this.stringBuffer = String(value); + } + } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +} + +class HttpInterceptingShapeSerializer { + codecSerializer; + stringSerializer; + buffer; + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== undefined) { + const buffer = this.buffer; + this.buffer = undefined; + return buffer; + } + return this.codecSerializer.flush(); + } +} + +class Field { + name; + kind; + values; + constructor({ name, kind = FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + if (runtimeConfig.logger && runtimeConfig.logger.constructor?.name !== "NoOpLogger") { + runtimeConfig.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"), runtimeConfig.logger); + } + return { + setHttpHandler(handler) { + runtimeConfig.requestHandler = handler; + }, + httpHandler() { + return runtimeConfig.requestHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.requestHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.requestHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + requestHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +const CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && + Object.keys(headers) + .map((str) => str.toLowerCase()) + .indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + if (length != null) { + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length), + }; + } + } + catch (ignored) { + } + } + } + return next({ + ...args, + request, + }); + }; +} +const contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true, +}; +const getContentLengthPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + }, +}); + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +exports.Field = Field; +exports.Fields = Fields; +exports.FromStringShapeDeserializer = FromStringShapeDeserializer; +exports.HttpBindingProtocol = HttpBindingProtocol; +exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer; +exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer; +exports.HttpProtocol = HttpProtocol; +exports.RequestBuilder = RequestBuilder; +exports.RpcProtocol = RpcProtocol; +exports.SerdeContext = SerdeContext; +exports.ToStringShapeSerializer = ToStringShapeSerializer; +exports.buildQueryString = buildQueryString; +exports.collectBody = collectBody; +exports.contentLengthMiddleware = contentLengthMiddleware; +exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; +exports.determineTimestampFormat = determineTimestampFormat; +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; +exports.extendedEncodeURIComponent = extendedEncodeURIComponent; +exports.getContentLengthPlugin = getContentLengthPlugin; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.requestBuilder = requestBuilder; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; +exports.resolvedPath = resolvedPath; + + +/***/ }), + +/***/ 89368: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Readable } = __webpack_require__(57075); +const { NoOpLogger, normalizeProvider } = __webpack_require__(40417); +const { HttpResponse, HttpRequest } = __webpack_require__(37015); +const { parseRfc7231DateTime, v4 } = __webpack_require__(26591); +const { hasOwn } = __webpack_require__(74875); + +const isStreamingPayload = (request) => request?.body instanceof Readable || + (typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream); + +const CLOCK_SKEW_ERROR_CODES = [ + "AccessDeniedException", + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch", +]; +const THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException", +]; +const TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; +const NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN"]; + +const isRetryableByTrait = (error) => error?.$retryable !== undefined; +const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name); +const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; +const isBrowserNetworkError = (error) => { + const errorMessages = new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed", + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; + } + return errorMessages.has(error.message); +}; +const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || + THROTTLING_ERROR_CODES.includes(error.name) || + error.$retryable?.throttling == true; +const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || + isClockSkewCorrectedError(error) || + (error.name === "InvalidSignatureException" && error.message?.includes("Signature expired")) || + TRANSIENT_ERROR_CODES.includes(error.name) || + NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || + NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || + TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || + isBrowserNetworkError(error) || + isNodeJsHttp2TransientError(error) || + (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1)); +const isServerError = (error) => { + if (error.$metadata?.httpStatusCode !== undefined) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; + } + return false; + } + return false; +}; +function isNodeJsHttp2TransientError(error) { + return error.code === "ERR_HTTP2_STREAM_ERROR" && error.message.includes("NGHTTP2_REFUSED_STREAM"); +} + +const DEFAULT_RETRY_DELAY_BASE = 100; +const MAXIMUM_RETRY_DELAY = 20 * 1000; +const THROTTLING_RETRY_DELAY_BASE = 500; +const INITIAL_RETRY_TOKENS = 500; +const RETRY_COST = 5; +const TIMEOUT_RETRY_COST = 10; +const NO_RETRY_INCREMENT = 1; +const INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +const REQUEST_HEADER = "amz-sdk-request"; + +function parseRetryAfterHeader(response, logger) { + if (!HttpResponse.isInstance(response)) { + return; + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const h = header.toLowerCase(); + if (h === "retry-after") { + const retryAfter = response.headers[header]; + let retryAfterSeconds = NaN; + if (retryAfter.endsWith("GMT")) { + try { + const date = parseRfc7231DateTime(retryAfter); + retryAfterSeconds = (date.getTime() - Date.now()) / 1000; + } + catch (e) { + logger?.trace?.("Failed to parse retry-after header"); + logger?.trace?.(e); + } + } + else if (retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter.match(/ GMT, ([\d.]+)$/)?.[1]); + } + else if (retryAfter.match(/^((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter); + } + else if (Date.parse(retryAfter) >= Date.now()) { + retryAfterSeconds = (Date.parse(retryAfter) - Date.now()) / 1000; + } + if (isNaN(retryAfterSeconds)) { + return; + } + return new Date(Date.now() + retryAfterSeconds * 1000); + } + else if (h === "x-amz-retry-after") { + const v = response.headers[header]; + const backoffMilliseconds = Number(v); + if (isNaN(backoffMilliseconds)) { + logger?.trace?.(`Failed to parse x-amz-retry-after=${v}`); + return; + } + return new Date(Date.now() + backoffMilliseconds); + } + } +} +function getRetryAfterHint(response, logger) { + return parseRetryAfterHeader(response, logger); +} + +const asSdkError = (error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); +}; + +function bindRetryMiddleware(isStreamingPayload) { + return (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken((context["partition_id"] ?? "") + (context.__retryLongPoll ? ":longpoll" : "")); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = HttpRequest.isInstance(request); + if (isRequest) { + request.headers[INVOCATION_ID_HEADER] = v4(); + } + while (true) { + try { + if (isRequest) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } + catch (e) { + const retryErrorInfo = getRetryErrorInfo(e, options.logger); + lastError = asSdkError(e); + if (isRequest && isStreamingPayload(request)) { + (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } + catch (ignoredRefreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += (retryToken?.$retryLog?.acquisitionDelay ?? 0) + delay; + if (delay > 0) { + await cooldown(delay); + } + } + } + } + else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) { + context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; + } + return retryStrategy.retry(next, args); + } + }; +} +const cooldown = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && + typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && + typeof retryStrategy.recordSuccess !== "undefined"; +const getRetryErrorInfo = (error, logger) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error), + }; + const retryAfterHint = parseRetryAfterHeader(error.$response, logger); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; +}; +const getRetryErrorType = (error) => { + if (isThrottlingError(error)) + return "THROTTLING"; + if (isTransientError(error)) + return "TRANSIENT"; + if (isServerError(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}; +const retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true, +}; +function bindGetRetryPlugin(isStreamingPayload) { + const retryMiddleware = bindRetryMiddleware(isStreamingPayload); + return (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + }, + }); +} + +class DefaultRateLimiter { + static setTimeoutFn = (fn, delay) => setTimeout(fn, delay); + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + enabled = false; + availableTokens = 0; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + const retryErrorInfo = response; + const isThrottling = retryErrorInfo?.errorType === "THROTTLING" || isThrottlingError(retryErrorInfo?.error ?? response); + if (isThrottling) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } + else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + getCurrentTimeInSeconds() { + return Date.now() / 1000; + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + while (amount > this.availableTokens) { + const delay = ((amount - this.availableTokens) / this.fillRate) * 1000; + await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay)); + this.refillTokenBucket(); + } + this.availableTokens = this.availableTokens - amount; + } + refillTokenBucket() { + const timestamp = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp; + return; + } + const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; + this.availableTokens = Math.min(this.maxCapacity, this.availableTokens + fillAmount); + this.lastTimestamp = timestamp; + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.availableTokens = Math.min(this.availableTokens, this.maxCapacity); + } + updateMeasuredRate() { + const t = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } +} + +class Retry { + static v2026 = typeof process !== "undefined" && process.env?.SMITHY_NEW_RETRIES_2026 === "true"; + static delay() { + return Retry.v2026 ? 50 : 100; + } + static throttlingDelay() { + return Retry.v2026 ? 1_000 : 500; + } + static cost() { + return Retry.v2026 ? 14 : 5; + } + static throttlingCost() { + return Retry.v2026 ? 5 : 10; + } + static modifiedCostType() { + return Retry.v2026 ? "THROTTLING" : "TRANSIENT"; + } +} + +class DefaultRetryBackoffStrategy { + x = Retry.delay(); + computeNextBackoffDelay(i) { + const b = Math.random(); + const r = 2; + const t_i = b * Math.min(this.x * r ** i, MAXIMUM_RETRY_DELAY); + return Math.floor(t_i); + } + setDelayBase(delay) { + this.x = delay; + } +} + +class DefaultRetryToken { + delay; + count; + cost; + longPoll; + $retryLog = { + acquisitionDelay: 0, + }; + constructor(delay, count, cost, longPoll) { + this.delay = delay; + this.count = count; + this.cost = cost; + this.longPoll = longPoll; + } + getRetryCount() { + return this.count; + } + getRetryDelay() { + return Math.min(MAXIMUM_RETRY_DELAY, this.delay); + } + getRetryCost() { + return this.cost; + } + isLongPoll() { + return this.longPoll; + } +} + +var RETRY_MODES; +(function (RETRY_MODES) { + RETRY_MODES["STANDARD"] = "standard"; + RETRY_MODES["ADAPTIVE"] = "adaptive"; +})(RETRY_MODES || (RETRY_MODES = {})); +const DEFAULT_MAX_ATTEMPTS = 3; +const DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD; + +const refusal = { + incompatible: 1, + attempts: 2, + capacity: 3, +}; +let StandardRetryStrategy$1 = class StandardRetryStrategy { + mode = RETRY_MODES.STANDARD; + retryBackoffStrategy; + capacity = INITIAL_RETRY_TOKENS; + maxAttemptsProvider; + baseDelay; + constructor(arg1) { + if (typeof arg1 === "number") { + this.maxAttemptsProvider = async () => arg1; + } + else if (typeof arg1 === "function") { + this.maxAttemptsProvider = arg1; + } + else if (arg1 && typeof arg1 === "object") { + this.maxAttemptsProvider = async () => arg1.maxAttempts; + this.baseDelay = arg1.baseDelay; + this.retryBackoffStrategy = arg1.backoff; + } + this.maxAttemptsProvider ??= async () => DEFAULT_MAX_ATTEMPTS; + this.baseDelay ??= Retry.delay(); + this.retryBackoffStrategy ??= new DefaultRetryBackoffStrategy(); + } + async acquireInitialRetryToken(retryTokenScope) { + return new DefaultRetryToken(Retry.delay(), 0, undefined, Retry.v2026 && retryTokenScope.includes(":longpoll")); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + const retryCode = this.retryCode(token, errorInfo, maxAttempts); + const shouldRetry = retryCode === 0; + const isLongPoll = token.isLongPoll?.(); + if (shouldRetry || isLongPoll) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? Retry.throttlingDelay() : this.baseDelay); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + let retryDelay = delayFromErrorType; + if (errorInfo.retryAfterHint instanceof Date) { + retryDelay = Math.max(delayFromErrorType, Math.min(errorInfo.retryAfterHint.getTime() - Date.now(), delayFromErrorType + 5_000)); + } + if (!shouldRetry) { + const longPollBackoff = Retry.v2026 && retryCode === refusal.capacity && isLongPoll ? retryDelay : 0; + if (longPollBackoff > 0) { + await new Promise((r) => setTimeout(r, longPollBackoff)); + } + } + else { + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + const nextToken = new DefaultRetryToken(0, token.getRetryCount() + 1, capacityCost, token.isLongPoll?.() ?? false); + await new Promise((r) => setTimeout(r, retryDelay)); + nextToken.$retryLog.acquisitionDelay = retryDelay; + return nextToken; + } + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.min(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async maxAttempts() { + return this.maxAttemptsProvider(); + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } + catch (ignored) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + retryCode(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + const retryableStatus = this.isRetryableError(errorInfo.errorType) ? 0 : refusal.incompatible; + const attemptStatus = attempts < maxAttempts ? 0 : refusal.attempts; + const capacityStatus = this.capacity >= this.getCapacityCost(errorInfo.errorType) ? 0 : refusal.capacity; + return retryableStatus || attemptStatus || capacityStatus; + } + getCapacityCost(errorType) { + return errorType === Retry.modifiedCostType() ? Retry.throttlingCost() : Retry.cost(); + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +}; + +let AdaptiveRetryStrategy$1 = class AdaptiveRetryStrategy { + mode = RETRY_MODES.ADAPTIVE; + rateLimiter; + standardRetryStrategy; + constructor(maxAttemptsProvider, options) { + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = options + ? new StandardRetryStrategy$1({ + maxAttempts: typeof maxAttemptsProvider === "number" ? maxAttemptsProvider : 3, + ...options, + }) + : new StandardRetryStrategy$1(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + const token = await this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + await this.rateLimiter.getSendToken(); + return token; + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + const token = await this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + await this.rateLimiter.getSendToken(); + return token; + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } + async maxAttemptsProvider() { + return this.standardRetryStrategy.maxAttempts(); + } +}; + +class ConfiguredRetryStrategy extends StandardRetryStrategy$1 { + computeNextBackoffDelay; + constructor(maxAttempts, computeNextBackoffDelay = Retry.delay()) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } + else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + this.retryBackoffStrategy.computeNextBackoffDelay = (completedAttempt) => { + const nextAttempt = completedAttempt + 1; + return this.computeNextBackoffDelay(nextAttempt); + }; + } +} + +const getDefaultRetryQuota = (initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = NO_RETRY_INCREMENT; + const retryCost = RETRY_COST; + const timeoutRetryCost = TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); + const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; + const retrieveRetryTokens = (error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); + } + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }; + const releaseRetryTokens = (capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }; + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens, + }); +}; + +const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + +const defaultRetryDecider = (error) => { + if (!error) { + return false; + } + return isRetryableByTrait(error) || isClockSkewError(error) || isThrottlingError(error) || isTransientError(error); +}; + +class StandardRetryStrategy { + maxAttemptsProvider; + retryDecider; + delayDecider; + retryQuota; + mode = RETRY_MODES.STANDARD; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(INITIAL_RETRY_TOKENS); + } + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } + catch (ignored) { + maxAttempts = DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (HttpRequest.isInstance(request)) { + request.headers[INVOCATION_ID_HEADER] = v4(); + } + while (true) { + try { + if (HttpRequest.isInstance(request)) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); + } + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } + catch (e) { + const err = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider(isThrottlingError(err) ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE, attempts); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; + } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } + } + } +} +const getDelayFromRetryAfterHeader = (response) => { + if (!HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return Math.min(retryAfterSeconds * 1000, 20_000); + const retryAfterDate = new Date(retryAfter); + return Math.min(retryAfterDate.getTime() - Date.now(), 20_000); +}; + +class AdaptiveRetryStrategy extends StandardRetryStrategy { + rateLimiter; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.mode = RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + }, + }); + } +} + +const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +const CONFIG_MAX_ATTEMPTS = "max_attempts"; +const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + default: DEFAULT_MAX_ATTEMPTS, +}; +const resolveRetryConfig = (input, defaults) => { + const { retryStrategy, retryMode } = input; + const { defaultMaxAttempts = DEFAULT_MAX_ATTEMPTS, defaultBaseDelay = Retry.delay() } = defaults ?? {}; + const maxAttemptsProvider = normalizeProvider(input.maxAttempts ?? defaultMaxAttempts); + let controller = retryStrategy + ? Promise.resolve(retryStrategy) + : undefined; + const getDefault = async () => { + const maxAttempts = await maxAttemptsProvider(); + const adaptive = (await normalizeProvider(retryMode)()) === RETRY_MODES.ADAPTIVE; + if (adaptive) { + return new AdaptiveRetryStrategy$1(maxAttemptsProvider, { + maxAttempts, + baseDelay: defaultBaseDelay, + }); + } + return new StandardRetryStrategy$1({ + maxAttempts, + baseDelay: defaultBaseDelay, + }); + }; + return Object.assign(input, { + maxAttempts: maxAttemptsProvider, + retryStrategy: () => (controller ??= getDefault()), + }); +}; +const ENV_RETRY_MODE = "AWS_RETRY_MODE"; +const CONFIG_RETRY_MODE = "retry_mode"; +const NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: DEFAULT_RETRY_MODE, +}; + +const omitRetryHeadersMiddleware = () => (next) => async (args) => { + const { request } = args; + if (HttpRequest.isInstance(request)) { + delete request.headers[INVOCATION_ID_HEADER]; + delete request.headers[REQUEST_HEADER]; + } + return next(args); +}; +const omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true, +}; +const getOmitRetryHeadersPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + }, +}); + +const retryMiddleware = bindRetryMiddleware(isStreamingPayload); +const getRetryPlugin = bindGetRetryPlugin(isStreamingPayload); + +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy$1; +exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; +exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; +exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; +exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; +exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; +exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE; +exports.DefaultRateLimiter = DefaultRateLimiter; +exports.DeprecatedAdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.DeprecatedStandardRetryStrategy = StandardRetryStrategy; +exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; +exports.ENV_RETRY_MODE = ENV_RETRY_MODE; +exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; +exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; +exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; +exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS; +exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS; +exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; +exports.REQUEST_HEADER = REQUEST_HEADER; +exports.RETRY_COST = RETRY_COST; +exports.RETRY_MODES = RETRY_MODES; +exports.Retry = Retry; +exports.StandardRetryStrategy = StandardRetryStrategy$1; +exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; +exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; +exports.defaultDelayDecider = defaultDelayDecider; +exports.defaultRetryDecider = defaultRetryDecider; +exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; +exports.getRetryAfterHint = getRetryAfterHint; +exports.getRetryPlugin = getRetryPlugin; +exports.isBrowserNetworkError = isBrowserNetworkError; +exports.isClockSkewCorrectedError = isClockSkewCorrectedError; +exports.isClockSkewError = isClockSkewError; +exports.isNodeJsHttp2TransientError = isNodeJsHttp2TransientError; +exports.isRetryableByTrait = isRetryableByTrait; +exports.isServerError = isServerError; +exports.isThrottlingError = isThrottlingError; +exports.isTransientError = isTransientError; +exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; +exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; +exports.resolveRetryConfig = resolveRetryConfig; +exports.retryMiddleware = retryMiddleware; +exports.retryMiddlewareOptions = retryMiddlewareOptions; + + +/***/ }), + +/***/ 31829: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { getSmithyContext, HttpResponse, toEndpointV1 } = __webpack_require__(74875); + +const deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +const operation = (namespace, name, traits, input, output) => ({ + name, + namespace, + traits, + input, + output, +}); + +const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + try { + const parsed = await config.protocol.deserializeResponse(operation(ns, n, t, i, o), { + ...config, + ...context, + }, response); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (ignored) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (HttpResponse.isInstance(response)) { + const { headers = {}, statusCode } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (ignored) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + const endpoint = context.endpointV2 + ? async () => toEndpointV1(context.endpointV2) + : config.endpoint; + const request = await config.protocol.serializeRequest(operation(ns, n, t, i, o), args.input, { + ...config, + ...context, + endpoint, + }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + }, + }; +} + +class Schema { + name; + namespace; + traits; + static assign(instance, values) { + const schema = Object.assign(instance, values); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list = lhs; + return list.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +} + +class ListSchema extends Schema { + static symbol = Symbol.for("@smithy/lis"); + valueSchema; + symbol = ListSchema.symbol; +} +const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema, +}); + +class MapSchema extends Schema { + static symbol = Symbol.for("@smithy/map"); + keySchema; + valueSchema; + symbol = MapSchema.symbol; +} +const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema, +}); + +class OperationSchema extends Schema { + static symbol = Symbol.for("@smithy/ope"); + input; + output; + symbol = OperationSchema.symbol; +} +const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output, +}); + +class StructureSchema extends Schema { + static symbol = Symbol.for("@smithy/str"); + memberNames; + memberList; + symbol = StructureSchema.symbol; +} +const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList, +}); + +class ErrorSchema extends StructureSchema { + static symbol = Symbol.for("@smithy/err"); + ctor; + symbol = ErrorSchema.symbol; +} +const error = (namespace, name, traits, memberNames, memberList, _ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor: null, +}); + +const traitsCache = []; +function translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + if (traitsCache[indicator]) { + return traitsCache[indicator]; + } + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams", + ]) { + if (((indicator >> i++) & 1) === 1) { + traits[trait] = 1; + } + } + return (traitsCache[indicator] = traits); +} + +const anno = { + it: Symbol.for("@smithy/nor-struct-it"), + ns: Symbol.for("@smithy/ns"), +}; +const simpleSchemaCacheN = []; +const simpleSchemaCacheS = {}; +class NormalizedSchema { + ref; + memberName; + static symbol = Symbol.for("@smithy/nor"); + symbol = NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (isMemberSchema(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, translateTraits(traitSet)); + } + } + else { + this.memberTraits = 0; + } + if (schema instanceof NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema); + this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (isStaticSchema(this.schema)) { + this.name = `${this.schema[1]}#${this.schema[2]}`; + this.traits = this.schema[3]; + } + else { + this.name = this.memberName ?? String(schema); + this.traits = 0; + } + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const ns = lhs; + return ns.symbol === this.symbol; + } + return isPrototype; + } + static of(ref) { + const keyAble = typeof ref === "function" || (typeof ref === "object" && ref !== null); + if (typeof ref === "number") { + if (simpleSchemaCacheN[ref]) { + return simpleSchemaCacheN[ref]; + } + } + else if (typeof ref === "string") { + if (simpleSchemaCacheS[ref]) { + return simpleSchemaCacheS[ref]; + } + } + else if (keyAble) { + if (ref[anno.ns]) { + return ref[anno.ns]; + } + } + const sc = deref(ref); + if (sc instanceof NormalizedSchema) { + return sc; + } + if (isMemberSchema(sc)) { + const [ns, traits] = sc; + if (ns instanceof NormalizedSchema) { + Object.assign(ns.getMergedTraits(), translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + const ns = new NormalizedSchema(sc); + if (keyAble) { + return (ref[anno.ns] = ns); + } + if (typeof sc === "string") { + return (simpleSchemaCacheS[sc] = ns); + } + if (typeof sc === "number") { + return (simpleSchemaCacheN[sc] = ns); + } + return ns; + } + getSchema() { + const sc = this.schema; + if (Array.isArray(sc) && sc[0] === 0) { + return sc[4]; + } + return sc; + } + getName(withNamespace = false) { + const { name } = this; + const short = !withNamespace && name && name.includes("#"); + return short ? name.split("#")[1] : name || undefined; + } + getMemberName() { + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isListSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 64 && sc < 128 + : sc[0] === 1; + } + isMapSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 128 && sc <= 0b1111_1111 + : sc[0] === 2; + } + isStructSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + const id = sc[0]; + return (id === 3 || + id === -3 || + id === 4); + } + isUnionSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + return sc[0] === 4; + } + isBlobSchema() { + const sc = this.getSchema(); + return sc === 21 || sc === 42; + } + isTimestampSchema() { + const sc = this.getSchema(); + return (typeof sc === "number" && + sc >= 4 && + sc <= 7); + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isDocumentSchema() { + return this.getSchema() === 15; + } + isStringSchema() { + return this.getSchema() === 0; + } + isBooleanSchema() { + return this.getSchema() === 2; + } + isNumericSchema() { + return this.getSchema() === 1; + } + isBigIntegerSchema() { + return this.getSchema() === 17; + } + isBigDecimalSchema() { + return this.getSchema() === 19; + } + isStreaming() { + const { streaming } = this.getMergedTraits(); + return !!streaming || this.getSchema() === 42; + } + isIdempotencyToken() { + return !!this.getMergedTraits().idempotencyToken; + } + getMergedTraits() { + return (this.normalizedTraits ?? + (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits(), + })); + } + getMemberTraits() { + return translateTraits(this.memberTraits); + } + getOwnTraits() { + return translateTraits(this.traits); + } + getKeySchema() { + const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; + if (!isDoc && !isMap) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + const memberSchema = isDoc + ? 15 + : (schema[4] ?? 0); + return member([memberSchema, 0], "key"); + } + getValueSchema() { + const sc = this.getSchema(); + const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; + const memberSchema = typeof sc === "number" + ? 0b0011_1111 & sc + : sc && typeof sc === "object" && (isMap || isList) + ? sc[3 + sc[0]] + : isDoc + ? 15 + : void 0; + if (memberSchema != null) { + return member([memberSchema, 0], isMap ? "value" : "member"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + getMemberSchema(memberName) { + const struct = this.getSchema(); + if (this.isStructSchema() && struct[4].includes(memberName)) { + const i = struct[4].indexOf(memberName); + const memberSchema = struct[5][i]; + return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); + } + if (this.isDocumentSchema()) { + return member([15, 0], memberName); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`); + } + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } + catch (ignored) { } + return buffer; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct = this.getSchema(); + const z = struct[4].length; + let it = struct[anno.it]; + if (it && z === it.length) { + yield* it; + return; + } + it = Array(z); + for (let i = 0; i < z; ++i) { + const k = struct[4][i]; + const v = member([struct[5][i], 0], k); + yield (it[i] = [k, v]); + } + struct[anno.it] = it; + } +} +function member(memberSchema, memberName) { + if (memberSchema instanceof NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true, + }); + } + const internalCtorAccess = NormalizedSchema; + return new internalCtorAccess(memberSchema, memberName); +} +const isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; +const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; + +class SimpleSchema extends Schema { + static symbol = Symbol.for("@smithy/sim"); + schemaRef; + symbol = SimpleSchema.symbol; +} +const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); +const simAdapter = (namespace, name, traits, schemaRef) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); + +const SCHEMA = { + BLOB: 0b0001_0101, + STREAMING_BLOB: 0b0010_1010, + BOOLEAN: 0b0000_0010, + STRING: 0b0000_0000, + NUMERIC: 0b0000_0001, + BIG_INTEGER: 0b0001_0001, + BIG_DECIMAL: 0b0001_0011, + DOCUMENT: 0b0000_1111, + TIMESTAMP_DEFAULT: 0b0000_0100, + TIMESTAMP_DATE_TIME: 0b0000_0101, + TIMESTAMP_HTTP_DATE: 0b0000_0110, + TIMESTAMP_EPOCH_SECONDS: 0b0000_0111, + LIST_MODIFIER: 0b0100_0000, + MAP_MODIFIER: 0b1000_0000, +}; + +class TypeRegistry { + namespace; + schemas; + exceptions; + static registries = new Map(); + constructor(namespace, schemas = new Map(), exceptions = new Map()) { + this.namespace = namespace; + this.schemas = schemas; + this.exceptions = exceptions; + } + static for(namespace) { + if (!TypeRegistry.registries.has(namespace)) { + TypeRegistry.registries.set(namespace, new TypeRegistry(namespace)); + } + return TypeRegistry.registries.get(namespace); + } + copyFrom(other) { + const { schemas, exceptions } = this; + for (const [k, v] of other.schemas) { + if (!schemas.has(k)) { + schemas.set(k, v); + } + } + for (const [k, v] of other.exceptions) { + if (!exceptions.has(k)) { + exceptions.set(k, v); + } + } + } + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + for (const r of [this, TypeRegistry.for(qualifiedName.split("#")[0])]) { + r.schemas.set(qualifiedName, schema); + } + } + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + if (!shapeId.includes("#")) { + const suffix = "#" + shapeId; + const candidates = []; + for (const [shapeId, schema] of this.schemas.entries()) { + if (shapeId.endsWith(suffix)) { + candidates.push(schema); + } + } + if (candidates.length === 1) { + return candidates[0]; + } + } + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + registerError(es, ctor) { + const $error = es; + const ns = $error[1]; + for (const r of [this, TypeRegistry.for(ns)]) { + r.schemas.set(ns + "#" + $error[2], $error); + r.exceptions.set($error, ctor); + } + } + getErrorCtor(es) { + const $error = es; + if (this.exceptions.has($error)) { + return this.exceptions.get($error); + } + const registry = TypeRegistry.for($error[1]); + return registry.exceptions.get($error); + } + getBaseException() { + for (const exceptionKey of this.exceptions.keys()) { + if (Array.isArray(exceptionKey)) { + const [, ns, name] = exceptionKey; + const id = ns + "#" + name; + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return exceptionKey; + } + } + } + return undefined; + } + find(predicate) { + for (const schema of this.schemas.values()) { + if (predicate(schema)) { + return schema; + } + } + return undefined; + } + clear() { + this.schemas.clear(); + this.exceptions.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } +} + +exports.ErrorSchema = ErrorSchema; +exports.ListSchema = ListSchema; +exports.MapSchema = MapSchema; +exports.NormalizedSchema = NormalizedSchema; +exports.OperationSchema = OperationSchema; +exports.SCHEMA = SCHEMA; +exports.Schema = Schema; +exports.SimpleSchema = SimpleSchema; +exports.StructureSchema = StructureSchema; +exports.TypeRegistry = TypeRegistry; +exports.deref = deref; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.error = error; +exports.getSchemaSerdePlugin = getSchemaSerdePlugin; +exports.isStaticSchema = isStaticSchema; +exports.list = list; +exports.map = map; +exports.op = op; +exports.operation = operation; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.sim = sim; +exports.simAdapter = simAdapter; +exports.simpleSchemaCacheN = simpleSchemaCacheN; +exports.simpleSchemaCacheS = simpleSchemaCacheS; +exports.struct = struct; +exports.traitsCache = traitsCache; +exports.translateTraits = translateTraits; + + +/***/ }), + +/***/ 26591: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { createHmac, createHash, getRandomValues } = __webpack_require__(77598); +const { hasOwn, HttpResponse } = __webpack_require__(74875); +exports.hasOwn = hasOwn; +const { ReadStream, lstatSync, fstatSync } = __webpack_require__(73024); +const { toEndpointV1 } = __webpack_require__(19564); +const { Readable, Writable, PassThrough } = __webpack_require__(57075); + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? Buffer.from(input, encoding) : Buffer.from(input); +}; + +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = fromString(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; + +const fromUtf8$1 = (input) => { + const buf = fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toBase64$1 = (_input) => { + let input; + if (typeof _input === "string") { + input = fromUtf8$1(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; + +function bindUint8ArrayBlobAdapter(toUtf8, fromUtf8, toBase64, fromBase64) { + return class Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + if (typeof source === "string") { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate(fromBase64(source)); + } + return Uint8ArrayBlobAdapter.mutate(fromUtf8(source)); + } + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + static mutate(source) { + Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + if (encoding === "base64") { + return toBase64(this); + } + return toUtf8(this); + } + }; +} + +const toUtf8$1 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +const decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bindV4(getRandomValues) { + if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { + return () => crypto.randomUUID(); + } + return () => { + const rnds = new Uint8Array(16); + getRandomValues(rnds); + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + return (decimalToHex[rnds[0]] + + decimalToHex[rnds[1]] + + decimalToHex[rnds[2]] + + decimalToHex[rnds[3]] + + "-" + + decimalToHex[rnds[4]] + + decimalToHex[rnds[5]] + + "-" + + decimalToHex[rnds[6]] + + decimalToHex[rnds[7]] + + "-" + + decimalToHex[rnds[8]] + + decimalToHex[rnds[9]] + + "-" + + decimalToHex[rnds[10]] + + decimalToHex[rnds[11]] + + decimalToHex[rnds[12]] + + decimalToHex[rnds[13]] + + decimalToHex[rnds[14]] + + decimalToHex[rnds[15]]); + }; +} + +const copyDocumentWithTransform = (source, _schemaRef, _transform = (_) => _) => source; + +const parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}; +const expectBoolean = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +const expectNumber = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +const expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}; +const expectLong = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +const expectInt = expectLong; +const expectInt32 = (value) => expectSizedInt(value, 32); +const expectShort = (value) => expectSizedInt(value, 16); +const expectByte = (value) => expectSizedInt(value, 8); +const expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== undefined && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +const castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +const expectNonNull = (value, location) => { + if (value === null || value === undefined) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}; +const expectObject = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +const expectString = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +const expectUnion = (value) => { + if (value === null || value === undefined) { + return undefined; + } + const asObject = expectObject(value); + const setKeys = []; + for (const k in asObject) { + if (!hasOwn(asObject, k)) + continue; + if (asObject[k] != null) { + setKeys.push(k); + } + } + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +const strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +const strictParseFloat = strictParseDouble; +const strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +const parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +const limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +const handleFloat = limitedParseDouble; +const limitedParseFloat = limitedParseDouble; +const limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +const parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +const strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +const strictParseInt = strictParseLong; +const strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +const strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +const strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +const stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message) + .split("\n") + .slice(0, 5) + .filter((s) => !s.includes("stackTraceWarning")) + .join("\n"); +}; +const logger = { + warn: console.warn, +}; + +const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +const parseRfc3339DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +const RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/); +const parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET$1.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +const IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); +const parseRfc7231DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + match = RFC_850_DATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds, + })); + } + match = ASC_TIME$1.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +const parseEpochTimestamp = (value) => { + if (value === null || value === undefined) { + return undefined; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } + else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } + else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } + else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1000)); +}; +const buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); +}; +const parseTwoDigitYear = (value) => { + const thisYear = new Date().getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; +const adjustRfc850Year = (input) => { + if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); + } + return input; +}; +const parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +const isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +const parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +const parseMilliseconds = (value) => { + if (value === null || value === undefined) { + return 0; + } + return strictParseFloat32("0." + value) * 1000; +}; +const parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } + else if (directionStr == "-") { + direction = -1; + } + else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1000; +}; +const stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; + +const LazyJsonString = function LazyJsonString(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + }, + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } + else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; + +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} + +const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; +const mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; +const time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; +const date = `(\\d?\\d)`; +const year = `(\\d{4})`; +const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); +const IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`); +const RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`); +const ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`); +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const _parseEpochTimestamp = (value) => { + if (value == null) { + return void 0; + } + let num = NaN; + if (typeof value === "number") { + num = value; + } + else if (typeof value === "string") { + if (!/^-?\d*\.?\d+$/.test(value)) { + throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); + } + num = Number.parseFloat(value); + } + else if (typeof value === "object" && value.tag === 1) { + num = value.value; + } + if (isNaN(num) || Math.abs(num) === Infinity) { + throw new TypeError("Epoch timestamps must be valid finite numbers."); + } + return new Date(Math.round(num * 1000)); +}; +const _parseRfc3339DateTimeWithOffset = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC3339 timestamps must be strings"); + } + const matches = RFC3339_WITH_OFFSET.exec(value); + if (!matches) { + throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); + } + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + range(monthStr, 1, 12); + range(dayStr, 1, 31); + range(hours, 0, 23); + range(minutes, 0, 59); + range(seconds, 0, 60); + const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); + date.setUTCFullYear(Number(yearStr)); + if (offsetStr.toUpperCase() != "Z") { + const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; + const scalar = sign === "-" ? 1 : -1; + date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); + } + return date; +}; +const _parseRfc7231DateTime = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC7231 timestamps must be strings."); + } + let day; + let month; + let year; + let hour; + let minute; + let second; + let fraction; + let matches; + if ((matches = IMF_FIXDATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + } + else if ((matches = RFC_850_DATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + year = (Number(year) + 1900).toString(); + } + else if ((matches = ASC_TIME.exec(value))) { + [, month, day, hour, minute, second, fraction, year] = matches; + } + if (year && second) { + const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); + range(day, 1, 31); + range(hour, 0, 23); + range(minute, 0, 59); + range(second, 0, 60); + const date = new Date(timestamp); + date.setUTCFullYear(Number(year)); + return date; + } + throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); +}; +function range(v, min, max) { + const _v = Number(v); + if (_v < min || _v > max) { + throw new Error(`Value ${_v} out of range [${min}, ${max}]`); + } +} + +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } + else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} + +const splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = undefined; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + } + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z = v.length; + if (z < 2) { + return v; + } + if (v[0] === `"` && v[z - 1] === `"`) { + v = v.slice(1, z - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +const format = /^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; +class NumericValue { + string; + type; + constructor(string, type) { + this.string = string; + this.type = type; + if (!format.test(string)) { + throw new Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${string}"`); + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === "bigDecimal" && format.test(_nv.string)); + } +} +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +const calculateBodyLength = (body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } + else if (body instanceof ReadStream) { + if (body.path != null) { + return lstatSync(body.path).size; + } + else if (typeof body.fd === "number") { + return fstatSync(body.fd).size; + } + } + throw new Error(`Body Length computation failed for ${body}`); +}; + +const toUint8Array = (data) => { + if (data instanceof Uint8Array) { + return data; + } + if (typeof data === "string") { + return fromUtf8$1(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}; + +function concatBytes(arrays, length) { + if (length === undefined) { + length = 0; + for (const bytes of arrays) { + length += bytes.byteLength; + } + } + const result = new Uint8Array(length); + let offset = 0; + for (const buf of arrays) { + result.set(buf, offset); + offset += buf.byteLength; + } + return result; +} + +const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (ignored) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (ignored) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2 + ? async () => toEndpointV1(context.endpointV2) + : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, + }; +} + +class Hash { + algorithmIdentifier; + secret; + hash; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update(toUint8Array(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret + ? createHmac(this.algorithmIdentifier, castSourceData(this.secret)) + : createHash(this.algorithmIdentifier); + } +} +function castSourceData(toCast, encoding) { + if (Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return fromString(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return fromArrayBuffer(toCast); +} + +let ChecksumStream$1 = class ChecksumStream extends Readable { + expectedChecksum; + checksumSourceLocation; + checksum; + source; + base64Encoder; + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + super(); + if (typeof source.pipe !== "function") { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + this.source = source; + this.base64Encoder = base64Encoder ?? toBase64$1; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.on("data", this.onSourceData); + this.source.on("end", this.onSourceEnd); + this.source.on("error", this.onSourceError); + this.source.on("close", this.onSourceClose); + this.source.pause(); + } + onSourceData = (chunk) => { + if (this.destroyed) { + return; + } + try { + this.checksum.update(chunk); + } + catch (e) { + this.destroy(e); + return; + } + if (!this.push(chunk)) { + this.source.pause(); + } + }; + onSourceEnd = async () => { + if (this.destroyed) { + return; + } + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + return; + } + } + catch (e) { + this.destroy(e); + return; + } + this.push(null); + }; + onSourceError = (error) => { + this.destroy(error); + }; + onSourceClose = () => { + if (!this.destroyed && !this.source.readableEnded) { + this.destroy(new Error("Connection lost or stream closed before all data was received.")); + } + }; + _read(_size) { + this.source.resume(); + } + _destroy(error, callback) { + this.source?.removeListener("data", this.onSourceData); + this.source?.removeListener("end", this.onSourceEnd); + this.source?.removeListener("error", this.onSourceError); + this.source?.removeListener("close", this.onSourceClose); + this.source?.destroy(); + callback(error); + } +}; + +const isReadableStream = (stream) => typeof ReadableStream === "function" && + (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); +const isBlob = (blob) => { + return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); +}; + +const fromUtf8 = (input) => new TextEncoder().encode(input); + +const chars = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`; +Object.entries(chars).reduce((acc, [i, c]) => { + acc[c] = Number(i); + return acc; +}, {}); +const alphabetByValue = chars.split(""); +const bitsPerLetter = 6; +const bitsPerByte = 8; +const maxLetterValue = 0b111111; + +function toBase64(_input) { + let input; + if (typeof _input === "string") { + input = fromUtf8(_input); + } + else { + input = _input; + } + const isArrayLike = typeof input === "object" && typeof input.length === "number"; + const isUint8Array = typeof input === "object" && + typeof input.byteOffset === "number" && + typeof input.byteLength === "number"; + if (!isArrayLike && !isUint8Array) { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + let str = ""; + for (let i = 0; i < input.length; i += 3) { + let bits = 0; + let bitLength = 0; + for (let j = i, limit = Math.min(i + 3, input.length); j < limit; j++) { + bits |= input[j] << ((limit - j - 1) * bitsPerByte); + bitLength += bitsPerByte; + } + const bitClusterCount = Math.ceil(bitLength / bitsPerLetter); + bits <<= bitClusterCount * bitsPerLetter - bitLength; + for (let k = 1; k <= bitClusterCount; k++) { + const offset = (bitClusterCount - k) * bitsPerLetter; + str += alphabetByValue[(bits & (maxLetterValue << offset)) >> offset]; + } + str += "==".slice(0, 4 - bitClusterCount); + } + return str; +} + +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} + +const createChecksumStream$1 = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + if (!isReadableStream(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + const encoder = base64Encoder ?? toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream.prototype); + return readable; +}; + +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && isReadableStream(init.source)) { + return createChecksumStream$1(init); + } + return new ChecksumStream$1(init); +} + +class ByteArrayCollector { + allocByteArray; + byteLength = 0; + byteArrays = []; + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} + +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + return chunk?.byteLength ?? chunk?.length ?? 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} + +function createBufferedReadable(upstream, size, logger) { + if (isReadableStream(upstream)) { + return createBufferedReadableStream(upstream, size, logger); + } + const downstream = new Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = modeOf(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push(flush(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} + +const getAwsChunkedEncodingStream$1 = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + bodyLengthChecker !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const reader = readableStream.getReader(); + return new ReadableStream({ + async pull(controller) { + const { value, done } = await reader.read(); + if (done) { + controller.enqueue(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + controller.enqueue(`${checksumLocationName}:${checksum}\r\n`); + controller.enqueue(`\r\n`); + } + controller.close(); + } + else { + controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\r\n${value}\r\n`); + } + }, + }); +}; + +function getAwsChunkedEncodingStream(stream, options) { + const readable = stream; + const readableStream = stream; + if (isReadableStream(readableStream)) { + return getAwsChunkedEncodingStream$1(readableStream, options); + } + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readable) : undefined; + const awsChunkedEncodingStream = new Readable({ + read: () => { }, + }); + readable.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + if (length === 0) { + return; + } + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readable.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +} + +async function headStream$1(stream, bytes) { + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += value?.byteLength ?? 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} + +const headStream = (stream, bytes) => { + if (isReadableStream(stream)) { + return headStream$1(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector$1(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = concatBytes(this.buffers); + resolve(bytes); + }); + }); +}; +let Collector$1 = class Collector extends Writable { + buffers = []; + limit = Infinity; + bytesBuffered = 0; + _write(chunk, encoding, callback) { + this.buffers.push(chunk); + this.bytesBuffered += chunk.byteLength ?? 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return new TextDecoder("utf-8").decode(input); +}; + +const streamCollector$1 = async (stream) => { + if (isBlob(stream)) { + return collectBlob(stream); + } + return collectReadableStream(stream); +}; +async function collectBlob(blob) { + return blob.arrayBuffer().then((ab) => new Uint8Array(ab)); +} +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let length = 0; + while (true) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + if (done) { + break; + } + } + return concatBytes(chunks, length); +} + +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1 = "The stream has already been transformed."; +const sdkStreamMixin$1 = (stream) => { + if (!isBlobInstance(stream) && !isReadableStream(stream)) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1); + } + transformed = true; + return await streamCollector$1(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return toBase64(buf); + } + else if (encoding === "hex") { + return toHex(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return toUtf8(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if (isReadableStream(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; + +const streamCollector = (stream) => { + if (isBlob(stream)) { + return collectBlob(stream); + } + if (isReadableStream(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + const nodeStream = stream; + nodeStream.pipe(collector); + nodeStream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = concatBytes(this.bufferedBytes); + resolve(bytes); + }); + }); +}; +class Collector extends Writable { + bufferedBytes = []; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +} + +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!(stream instanceof Readable)) { + try { + return sdkStreamMixin$1(stream); + } + catch (ignored) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await streamCollector(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return Readable.toWeb(stream); + }, + }); +}; + +async function splitStream$1(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} + +async function splitStream(stream) { + if (isReadableStream(stream) || isBlob(stream)) { + return splitStream$1(stream); + } + const stream1 = new PassThrough(); + const stream2 = new PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} + +class Uint8ArrayBlobAdapter extends bindUint8ArrayBlobAdapter(toUtf8$1, fromUtf8$1, toBase64$1, fromBase64) { +} +const _getRandomValues = getRandomValues; +const v4 = bindV4(_getRandomValues); +const generateIdempotencyToken = v4; + +exports.ChecksumStream = ChecksumStream$1; +exports.Hash = Hash; +exports.LazyJsonString = LazyJsonString; +exports.NumericValue = NumericValue; +exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; +exports._parseEpochTimestamp = _parseEpochTimestamp; +exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset; +exports._parseRfc7231DateTime = _parseRfc7231DateTime; +exports.calculateBodyLength = calculateBodyLength; +exports.concatBytes = concatBytes; +exports.copyDocumentWithTransform = copyDocumentWithTransform; +exports.createBufferedReadable = createBufferedReadable; +exports.createChecksumStream = createChecksumStream; +exports.dateToUtcString = dateToUtcString; +exports.deserializerMiddleware = deserializerMiddleware; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.expectBoolean = expectBoolean; +exports.expectByte = expectByte; +exports.expectFloat32 = expectFloat32; +exports.expectInt = expectInt; +exports.expectInt32 = expectInt32; +exports.expectLong = expectLong; +exports.expectNonNull = expectNonNull; +exports.expectNumber = expectNumber; +exports.expectObject = expectObject; +exports.expectShort = expectShort; +exports.expectString = expectString; +exports.expectUnion = expectUnion; +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromBase64 = fromBase64; +exports.fromHex = fromHex; +exports.fromString = fromString; +exports.fromUtf8 = fromUtf8$1; +exports.generateIdempotencyToken = generateIdempotencyToken; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +exports.getSerdePlugin = getSerdePlugin; +exports.handleFloat = handleFloat; +exports.headStream = headStream; +exports.isArrayBuffer = isArrayBuffer; +exports.isBlob = isBlob; +exports.isReadableStream = isReadableStream; +exports.limitedParseDouble = limitedParseDouble; +exports.limitedParseFloat = limitedParseFloat; +exports.limitedParseFloat32 = limitedParseFloat32; +exports.logger = logger; +exports.nv = nv; +exports.parseBoolean = parseBoolean; +exports.parseEpochTimestamp = parseEpochTimestamp; +exports.parseRfc3339DateTime = parseRfc3339DateTime; +exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; +exports.parseRfc7231DateTime = parseRfc7231DateTime; +exports.quoteHeader = quoteHeader; +exports.sdkStreamMixin = sdkStreamMixin; +exports.serializerMiddleware = serializerMiddleware; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.splitEvery = splitEvery; +exports.splitHeader = splitHeader; +exports.splitStream = splitStream; +exports.streamCollector = streamCollector; +exports.strictParseByte = strictParseByte; +exports.strictParseDouble = strictParseDouble; +exports.strictParseFloat = strictParseFloat; +exports.strictParseFloat32 = strictParseFloat32; +exports.strictParseInt = strictParseInt; +exports.strictParseInt32 = strictParseInt32; +exports.strictParseLong = strictParseLong; +exports.strictParseShort = strictParseShort; +exports.toBase64 = toBase64$1; +exports.toHex = toHex; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8$1; +exports.v4 = v4; + + +/***/ }), + +/***/ 74875: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { SMITHY_CONTEXT_KEY } = __webpack_require__(88867); + +const getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {}); + +function hasOwn(o, k) { + return Object.prototype.hasOwnProperty.call(o, k); +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +const isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}; + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9.-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } + else if (Array.isArray(query[key])) { + query[key].push(value); + } + else { + query[key] = [query[key], value]; + } + } + } + return query; +} + +const parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = parseQueryString(search); + } + return { + hostname, + port: port ? parseInt(port) : undefined, + protocol, + path: pathname, + query, + }; +}; + +const toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + const v1Endpoint = parseUrl(endpoint.url); + if (endpoint.headers) { + v1Endpoint.headers = {}; + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + v1Endpoint.headers[name.toLowerCase()] = endpoint.headers[name].join(", "); + } + } + return v1Endpoint; + } + return endpoint; + } + return parseUrl(endpoint); +}; + +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getSmithyContext = getSmithyContext; +exports.hasOwn = hasOwn; +exports.isValidHostLabel = isValidHostLabel; +exports.isValidHostname = isValidHostname; +exports.normalizeProvider = normalizeProvider; +exports.parseQueryString = parseQueryString; +exports.parseUrl = parseUrl; +exports.toEndpointV1 = toEndpointV1; + + +/***/ }), + +/***/ 57255: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { getSmithyContext, hasOwn } = __webpack_require__(30673); +exports.getSmithyContext = getSmithyContext; +const { HttpRequest } = __webpack_require__(62049); +const { requestBuilder } = __webpack_require__(62049); +exports.requestBuilder = requestBuilder; +const { HttpApiKeyAuthLocation } = __webpack_require__(88867); + +const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; +}; + +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; +} +const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = getSmithyContext(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer, + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}; + +const httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware", +}; +const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + }, +}); + +const httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "serializerMiddleware", +}; +const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider, + }), httpAuthSchemeMiddlewareOptions); + }, +}); + +const defaultErrorHandler = (signingProperties) => (error) => { + throw error; +}; +const defaultSuccessHandler = (httpResponse, signingProperties) => { }; +const httpSigningMiddleware = (config) => (next, context) => async (args) => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties), + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}; + +const httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware", +}; +const getHttpSigningPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions); + }, +}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}; +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); + } + else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return undefined; + }; +} +const get = (fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return undefined; + } + cursor = cursor[step]; + } + return cursor; +}; + +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {}, + }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} + +class DefaultIdentityProviderConfig { + authSchemes = new Map(); + constructor(config) { + for (const key in config) { + if (!hasOwn(config, key)) + continue; + const value = config[key]; + if (value !== undefined) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +} + +class HttpApiKeyAuthSigner { + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = HttpRequest.clone(httpRequest); + if (signingProperties.in === HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } + else if (signingProperties.in === HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme + ? `${signingProperties.scheme} ${identity.apiKey}` + : identity.apiKey; + } + else { + throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + + "but found: `" + + signingProperties.in + + "`"); + } + return clonedRequest; + } +} + +class HttpBearerAuthSigner { + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } +} + +class NoAuthSigner { + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +} + +const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; +}; +const EXPIRATION_MS = 300_000; +const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined; +const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === undefined) { + return undefined; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}; + +exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig; +exports.EXPIRATION_MS = EXPIRATION_MS; +exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner; +exports.HttpBearerAuthSigner = HttpBearerAuthSigner; +exports.NoAuthSigner = NoAuthSigner; +exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction; +exports.createPaginator = createPaginator; +exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh; +exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin; +exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin; +exports.getHttpSigningPlugin = getHttpSigningPlugin; +exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions; +exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware; +exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions; +exports.httpSigningMiddleware = httpSigningMiddleware; +exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions; +exports.isIdentityExpired = isIdentityExpired; +exports.memoizeIdentityProvider = memoizeIdentityProvider; +exports.normalizeProvider = normalizeProvider; +exports.setFeature = setFeature; + + +/***/ }), + +/***/ 51260: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { nv, NumericValue, calculateBodyLength, generateIdempotencyToken, fromBase64, _parseEpochTimestamp } = __webpack_require__(34129); +const { hasOwn, getSmithyContext } = __webpack_require__(30673); +const { HttpRequest, collectBody, SerdeContext, RpcProtocol } = __webpack_require__(62049); +const { NormalizedSchema, deref, TypeRegistry } = __webpack_require__(39875); + +const majorUint64 = 0; +const majorNegativeInt64 = 1; +const majorUnstructuredByteString = 2; +const majorUtf8String = 3; +const majorList = 4; +const majorMap = 5; +const majorTag = 6; +const majorSpecial = 7; +const specialFalse = 20; +const specialTrue = 21; +const specialNull = 22; +const specialUndefined = 23; +const extendedOneByte = 24; +const extendedFloat16 = 25; +const extendedFloat32 = 26; +const extendedFloat64 = 27; +const minorIndefinite = 31; +function alloc(size) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); +} +const tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); +function tag(data) { + data[tagSymbol] = true; + return data; +} + +const USE_BUFFER$3 = typeof Buffer !== "undefined"; +const textDecoder$1 = new TextDecoder(); +let payload$1 = alloc(0); +let isBuffer$1 = false; +let dataView$2 = new DataView(payload$1.buffer, payload$1.byteOffset, payload$1.byteLength); +let _offset = 0; +function setPayload(bytes) { + payload$1 = bytes; + isBuffer$1 = USE_BUFFER$3 && payload$1 instanceof Buffer; + dataView$2 = new DataView(payload$1.buffer, payload$1.byteOffset, payload$1.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (minor === minorIndefinite && 2 <= major && major <= 5) { + return decodeIndefinite(at, to); + } + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: { + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } + else { + switch (minor) { + case extendedOneByte: + if (to - at < 2) { + overflow$1(1); + } + unsignedInt = payload$1[at + 1]; + offset = 2; + break; + case extendedFloat16: + if (to - at < 3) { + overflow$1(2); + } + unsignedInt = dataView$2.getUint16(at + 1); + offset = 3; + break; + case extendedFloat32: + if (to - at < 5) { + overflow$1(4); + } + unsignedInt = dataView$2.getUint32(at + 1); + offset = 5; + break; + case extendedFloat64: + if (to - at < 9) { + overflow$1(8); + } + { + const hi = dataView$2.getUint32(at + 1); + if (hi < 0x00200000) { + unsignedInt = hi * 4294967296 + dataView$2.getUint32(at + 5); + } + else { + unsignedInt = dataView$2.getBigUint64(at + 1); + } + } + offset = 9; + break; + default: + unexpectedMinor(minor); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt$1(unsignedInt); + } + else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } + else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt$1(negativeInt); + } + else { + return decodeTagValue(at, to, minor, unsignedInt, offset); + } + } + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + default: + return decodeSpecial(at, to); + } +} +function decodeIndefinite(at, to) { + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } +} +function bytesToFloat16$1(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + if (exponent === 0b00000) { + if (fraction === 0) { + return 0; + } + return scalar * (Math.pow(2, 1 - 15) * (fraction / 1024)); + } + else if (exponent === 0b11111) { + if (fraction === 0) { + return scalar * Infinity; + } + return NaN; + } + return scalar * (Math.pow(2, exponent - 15) * (1 + fraction / 1024)); +} +function decodeMap(at, to) { + const mapDataLength = decodeCount$1(at, to); + if (mapDataLength < 25) { + return decodeMapSmall(at, to, mapDataLength); + } + return decodeMapLarge(at, to, mapDataLength); +} +function decodeMapLarge(at, to, mapDataLength) { + const offset = _offset; + at += offset; + const base = at; + const map = Object.create(null); + for (let i = 0; i < mapDataLength; ++i) { + const key = decodeUtf8String(at, to); + at += _offset; + const valMajor = (payload$1[at] & 0b1110_0000) >> 5; + if (valMajor === majorUtf8String) { + map[key] = decodeUtf8String(at, to); + } + else { + map[key] = decode(at, to); + } + at += _offset; + } + _offset = offset + (at - base); + Object.setPrototypeOf(map, Object.prototype); + return map; +} +function decodeMapSmall(at, to, mapDataLength) { + const offset = _offset; + at += offset; + const base = at; + const map = {}; + for (let i = 0; i < mapDataLength; ++i) { + const key = decodeUtf8String(at, to); + at += _offset; + map[key] = decode(at, to); + at += _offset; + } + _offset = offset + (at - base); + return map; +} +function decodeList(at, to) { + const listDataLength = decodeCount$1(at, to); + const offset = _offset; + at += offset; + const base = at; + const list = Array(listDataLength); + for (let i = 0; i < listDataLength; ++i) { + list[i] = decode(at, to); + at += _offset; + } + _offset = offset + (at - base); + return list; +} +function decodeUtf8String(at, to) { + const length = decodeCount$1(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + overflow$1(length); + } + _offset = offset + length; + if (length < 24) { + return decodeUtf8StringCached(at, length); + } + if (isBuffer$1) { + return payload$1.toString("utf-8", at, at + length); + } + return textDecoder$1.decode(payload$1.subarray(at, at + length)); +} +const stringCache$1 = new Array(2048); +const stringCacheEpochs$1 = new Uint16Array(2048); +let cacheEpoch$1 = 0; +function advanceDecodingEpoch() { + cacheEpoch$1 = (cacheEpoch$1 + 1) & 0b1111_1111_1111_1111; +} +function decodeUtf8StringCached(at, length) { + let h = length; + for (let i = 0; i < length; ++i) { + h = (h * 31 + payload$1[at + i]) | 0; + } + const slot = (h >>> 0) & 2047; + const cached = stringCache$1[slot]; + if (cached !== undefined) { + if (cached.length === length) { + let match = true; + for (let i = 0; i < length; ++i) { + if (cached.charCodeAt(i) !== payload$1[at + i]) { + match = false; + break; + } + } + if (match) { + stringCacheEpochs$1[slot] = cacheEpoch$1; + return cached; + } + } + } + const result = isBuffer$1 + ? payload$1.toString("utf-8", at, at + length) + : textDecoder$1.decode(payload$1.subarray(at, at + length)); + if (stringCacheEpochs$1[slot] !== cacheEpoch$1) { + stringCache$1[slot] = result; + stringCacheEpochs$1[slot] = cacheEpoch$1; + } + return result; +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount$1(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + overflow$1(length); + } + const value = payload$1.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeTagValue(at, to, minor, unsignedInt, offset) { + if (minor === 2 || minor === 3) { + const length = decodeCount$1(at + offset, to); + let b = BigInt(0); + const start = at + offset + _offset; + for (let i = start; i < start + length; ++i) { + b = (b << BigInt(8)) | BigInt(payload$1[i]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b - BigInt(1) : b; + } + else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [rawExponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const absMantissa = BigInt(normalizer) * BigInt(mantissa); + const mantissaDigits = String(absMantissa); + const sign = mantissa < 0 ? "-" : ""; + let numericString; + const isSmallExponent = typeof rawExponent === "number" && Math.abs(rawExponent) <= 2 ** 28; + if (isSmallExponent) { + const exponent = rawExponent; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + mantissaDigits; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + } + else { + const bigExponent = BigInt(rawExponent); + if (mantissaDigits.length === 1) { + numericString = sign + mantissaDigits + "e" + String(bigExponent); + } + else { + const adjustedExp = bigExponent + BigInt(mantissaDigits.length - 1); + numericString = sign + mantissaDigits[0] + "." + mantissaDigits.slice(1) + "e" + String(adjustedExp); + } + } + _offset = offset + _offset; + return nv(numericString); + } + else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt$1(unsignedInt), value }); + } +} +function decodeSpecial(at, to) { + const minor = payload$1[at] & 0b0001_1111; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16$1(payload$1[at + 1], payload$1[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView$2.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView$2.getFloat64(at + 1); + default: + unexpectedMinor(minor); + } +} +function decodeCount$1(at, to) { + const minor = payload$1[at] & 0b0001_1111; + if (minor < 24) { + _offset = 1; + return minor; + } + switch (minor) { + case extendedOneByte: + if (to - at < 2) { + overflow$1(1); + } + _offset = 2; + return payload$1[at + 1]; + case extendedFloat16: + if (to - at < 3) { + overflow$1(2); + } + _offset = 3; + return dataView$2.getUint16(at + 1); + case extendedFloat32: + if (to - at < 5) { + overflow$1(4); + } + _offset = 5; + return dataView$2.getUint32(at + 1); + case extendedFloat64: + if (to - at < 9) { + overflow$1(8); + } + _offset = 9; + return demote(dataView$2.getBigUint64(at + 1)); + default: + unexpectedMinor(minor); + } +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map = {}; + for (; at < to;) { + if (payload$1[at] === 0b1111_1111) { + _offset = at - base + 2; + return map; + } + const key = decodeUtf8String(at, to); + at += _offset; + map[key] = decode(at, to); + at += _offset; + } + throw new Error("expected break marker."); +} +function decodeListIndefinite(at, to) { + at += 1; + const list = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + _offset = at - base + 2; + return list; + } + list.push(decode(at, to)); + at += _offset; + } + throw new Error("expected break marker."); +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + if (USE_BUFFER$3) { + return data.toString("utf-8", 0, data.length); + } + return textDecoder$1.decode(data); + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (major !== majorUtf8String) { + unexpectedMajorInIndefiniteString(major); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector = []; + for (const base = at; at < to;) { + if (payload$1[at] === 0b1111_1111) { + const data = alloc(vector.length); + data.set(vector, 0); + _offset = at - base + 2; + return data; + } + const major = (payload$1[at] & 0b1110_0000) >> 5; + const minor = payload$1[at] & 0b0001_1111; + if (major !== majorUnstructuredByteString) { + unexpectedMajorInIndefiniteString(major); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i = 0; i < bytes.length; ++i) { + vector.push(bytes[i]); + } + } + throw new Error("expected break marker."); +} +function castBigInt$1(bigInt) { + if (typeof bigInt === "number") { + return bigInt; + } + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); + } + return num; +} +function overflow$1(n) { + throw new Error(`length ${n} greater than remaining buf len.`); +} +function unexpectedMinor(minor) { + throw new Error(`unexpected minor value ${minor}.`); +} +function unexpectedMajorInIndefiniteString(major) { + throw new Error(`unexpected major type ${major} in indefinite string.`); +} + +const USE_BUFFER$2 = typeof Buffer !== "undefined"; +const encodeStringCache = new Map(); +let encodeCacheEpoch$1 = 0; +let encodeCacheSaturated$1 = false; +const initialSize = 2048; +let data = alloc(initialSize); +let dataView$1 = new DataView(data.buffer, data.byteOffset, data.byteLength); +let cursor$1 = 0; +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + if (typeof input === "string") { + const len = input.length; + if (USE_BUFFER$2) { + ensureSpace(len * 3 + 9); + if (len > 23) { + encodeHeader$1(majorUtf8String, Buffer.byteLength(input)); + cursor$1 += data.write(input, cursor$1); + } + else { + encodeStringCached(input); + } + } + else { + const maxBytes = len * 3; + ensureSpace(maxBytes + 9); + const headerPos = cursor$1; + const result = new TextEncoder().encodeInto(input, data.subarray(cursor$1 + 9)); + const byteLen = result.written; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else if (byteLen < 65536) { + headerSize = 3; + } + else if (byteLen < 4294967296) { + headerSize = 5; + } + else { + headerSize = 9; + } + if (headerSize < 9) { + data.copyWithin(headerPos + headerSize, headerPos + 9, headerPos + 9 + byteLen); + } + cursor$1 = headerPos; + encodeInteger(majorUtf8String, byteLen); + cursor$1 += byteLen; + } + continue; + } + if (data.byteLength - cursor$1 < 9) { + ensureSpace(64); + } + if (typeof input === "number") { + if (Number.isInteger(input) && input >= -9007199254740992 && input <= 0x1fffffffffffff) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + data[cursor$1++] = value >> 8; + data[cursor$1++] = value & 0xff; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + dataView$1.setUint32(cursor$1, hi); + dataView$1.setUint32(cursor$1 + 4, lo); + cursor$1 += 8; + } + continue; + } + data[cursor$1++] = (majorSpecial << 5) | extendedFloat64; + dataView$1.setFloat64(cursor$1, input); + cursor$1 += 8; + continue; + } + else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + if (value < BigInt("18446744073709551616")) { + const n = Number(value); + if (n < 4294967296) { + encodeInteger(major, n); + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + dataView$1.setBigUint64(cursor$1, value); + cursor$1 += 8; + } + } + else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b = value; + let i = 0; + while (bigIntBytes.byteLength - ++i >= 0) { + bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2 + 16); + data[cursor$1++] = nonNegative ? 0b110_00010 : 0b110_00011; + encodeHeader$1(majorUnstructuredByteString, bigIntBytes.byteLength); + data.set(bigIntBytes, cursor$1); + cursor$1 += bigIntBytes.byteLength; + } + continue; + } + else if (input === null) { + data[cursor$1++] = (majorSpecial << 5) | specialNull; + continue; + } + else if (typeof input === "boolean") { + data[cursor$1++] = (majorSpecial << 5) | (input ? specialTrue : specialFalse); + continue; + } + else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } + else if (Array.isArray(input)) { + encodeInteger(majorList, input.length); + ensureSpace(input.length * 9 + 64); + for (let i = input.length - 1; i >= 0; --i) { + encodeStack.push(input[i]); + } + continue; + } + else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2 + 9); + encodeInteger(majorUnstructuredByteString, input.length); + data.set(input, cursor$1); + cursor$1 += input.byteLength; + continue; + } + else if (typeof input === "object") { + if (input instanceof NumericValue) { + let str = input.string; + let expOffset = BigInt(0); + const eIndex = str.search(/[eE]/); + if (eIndex !== -1) { + expOffset = BigInt(str.slice(eIndex + 1)); + str = str.slice(0, eIndex); + } + const decimalIndex = str.indexOf("."); + const fractionDigits = decimalIndex === -1 ? 0 : str.length - decimalIndex - 1; + const exponent = expOffset - BigInt(fractionDigits); + const mantissa = BigInt(str.replace(".", "")); + data[cursor$1++] = 0b110_00100; + encodeInteger(majorList, 2); + encodeStack.push(mantissa); + encodeStack.push(exponent >= -0x20000000000000n && exponent <= 0x1fffffffffffffn ? Number(exponent) : exponent); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader$1(majorTag, input.tag); + continue; + } + else { + throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); + } + } + const keys = Object.keys(input); + const len = keys.length; + encodeInteger(majorMap, len); + for (let i = len - 1; i >= 0; --i) { + encodeStack.push(input[keys[i]]); + encodeStack.push(keys[i]); + } + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); + } +} +function advanceEncodingEpoch() { + encodeCacheEpoch$1 = (encodeCacheEpoch$1 + 1) & 0b1111_1111_1111_1111; + encodeCacheSaturated$1 = false; +} +function toUint8Array() { + const out = alloc(cursor$1); + out.set(data.subarray(0, cursor$1), 0); + cursor$1 = 0; + return out; +} +function resize(size) { + const old = data; + data = alloc(size); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } + else { + data.set(old, 0); + } + } + dataView$1 = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeStringCached(input) { + const cached = encodeStringCache.get(input); + if (cached !== undefined) { + data.set(cached.bytes, cursor$1); + cursor$1 += cached.bytes.length; + cached.epoch = encodeCacheEpoch$1; + return; + } + const start = cursor$1; + const byteLen = Buffer.byteLength(input); + encodeInteger(majorUtf8String, byteLen); + cursor$1 += data.write(input, cursor$1); + const bytes = Uint8Array.prototype.slice.call(data, start, cursor$1); + if (encodeStringCache.size >= 2048) { + if (encodeCacheSaturated$1) { + return; + } + let evicted = 0; + for (const [key, entry] of encodeStringCache) { + if (evicted >= 1024) { + break; + } + if (entry.epoch !== encodeCacheEpoch$1) { + encodeStringCache.delete(key); + evicted++; + } + } + if (evicted === 0) { + encodeCacheSaturated$1 = true; + return; + } + } + if (encodeStringCache.size < 2048) { + encodeStringCache.set(input, { epoch: encodeCacheEpoch$1, bytes }); + } +} +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor$1; + if (remaining < bytes) { + if (cursor$1 < 16_000_000) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } + else { + resize(data.byteLength + bytes + 16_000_000); + } + } +} +function encodeHeader$1(major, value) { + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + dataView$1.setUint16(cursor$1, value); + cursor$1 += 2; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + dataView$1.setBigUint64(cursor$1, typeof value === "bigint" ? value : BigInt(value)); + cursor$1 += 8; + } +} +function encodeInteger(major, value) { + if (value < 24) { + data[cursor$1++] = (major << 5) | value; + } + else if (value < 256) { + data[cursor$1++] = (major << 5) | 24; + data[cursor$1++] = value; + } + else if (value < 65536) { + data[cursor$1++] = (major << 5) | extendedFloat16; + data[cursor$1++] = value >> 8; + data[cursor$1++] = value & 0xff; + } + else if (value < 4294967296) { + data[cursor$1++] = (major << 5) | extendedFloat32; + dataView$1.setUint32(cursor$1, value); + cursor$1 += 4; + } + else { + data[cursor$1++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + dataView$1.setUint32(cursor$1, hi); + dataView$1.setUint32(cursor$1 + 4, lo); + cursor$1 += 8; + } +} + +const cbor = { + deserialize(payload) { + advanceDecodingEpoch(); + setPayload(payload); + return decode(0, payload.length); + }, + serialize(input) { + advanceEncodingEpoch(); + try { + encode(input); + return toUint8Array(); + } + catch (e) { + toUint8Array(); + throw e; + } + }, + resizeEncodingBuffer(size) { + resize(size); + }, +}; + +const parseCborBody = (streamBody, context) => { + return collectBody(streamBody, context).then(async (bytes) => { + if (bytes.length) { + try { + return cbor.deserialize(bytes); + } + catch (e) { + Object.defineProperty(e, "$responseBodyText", { + value: context.utf8Encoder(bytes), + }); + throw e; + } + } + return {}; + }); +}; +const dateToTag = (date) => { + return tag({ + tag: 1, + value: date.getTime() / 1000, + }); +}; +const parseCborErrorBody = async (errorBody, context) => { + const value = await parseCborBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const loadSmithyRpcV2CborErrorCode = (output, data) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + return cleanValue; + }; + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } +}; +const checkCborResponse = (response) => { + if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { + throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); + } +}; +const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const endpoint = await context.endpoint(); + const { hostname, protocol = "https", port, path: basePath } = endpoint; + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers: { + ...headers, + }, + }; + if (resolvedHostname !== undefined) { + contents.hostname = resolvedHostname; + } + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + contents.headers[name] = endpoint.headers[name]; + } + } + if (body !== undefined) { + contents.body = body; + try { + contents.headers["content-length"] = String(calculateBodyLength(body)); + } + catch (ignored) { } + } + return new HttpRequest(contents); +}; + +class CborShapeSerializer2 extends SerdeContext { + write(schema, value) { + cursor = 0; + const ns = NormalizedSchema.of(schema); + writeValue(ns, value, undefined, this.serdeContext); + } + flush() { + const result = buf.subarray(0, cursor); + cursor = 0; + buf = allocUnsafe(INITIAL_BUFFER_SIZE); + view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + return result; + } +} +const CBOR_STRUCT_CACHE = Symbol.for("@smithy/cbor-struct-cache"); +function loadCborStructIterator(ns) { + const schema = ns.getSchema(); + const existing = schema[CBOR_STRUCT_CACHE]; + if (existing) { + return existing; + } + const memberNames = []; + const memberSchemas = []; + for (const [name, memberSchema] of ns.structIterator()) { + memberNames.push(name); + memberSchemas.push(memberSchema); + } + const encodedKeys = new Array(memberNames.length); + for (let i = 0; i < memberNames.length; ++i) { + encodedKeys[i] = encodeCborStringKey(memberNames[i]); + } + const cache = { memberNames, memberSchemas, encodedKeys }; + schema[CBOR_STRUCT_CACHE] = cache; + return cache; +} +function encodeCborStringKey(s) { + let utf8Bytes; + if (USE_BUFFER$1) { + utf8Bytes = Buffer.from(s, "utf-8"); + } + else { + utf8Bytes = new TextEncoder().encode(s); + } + const byteLen = utf8Bytes.length; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else { + headerSize = 3; + } + const result = new Uint8Array(headerSize + byteLen); + if (headerSize === 1) { + result[0] = (majorUtf8String << 5) | byteLen; + } + else if (headerSize === 2) { + result[0] = (majorUtf8String << 5) | 24; + result[1] = byteLen; + } + else { + result[0] = (majorUtf8String << 5) | extendedFloat16; + result[1] = byteLen >> 8; + result[2] = byteLen & 0xff; + } + result.set(utf8Bytes, headerSize); + return result; +} +const USE_BUFFER$1 = typeof Buffer !== "undefined"; +const textEncoder = new TextEncoder(); +const INITIAL_BUFFER_SIZE = 2048; +let buf = USE_BUFFER$1 ? Buffer.allocUnsafe(INITIAL_BUFFER_SIZE) : new Uint8Array(INITIAL_BUFFER_SIZE); +let view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); +let cursor = 0; +const STRING_CACHE_MAX = 2048; +const stringEncodeCache = new Map(); +let encodeCacheEpoch = 0; +let encodeCacheSaturated = false; +function allocUnsafe(size) { + return USE_BUFFER$1 ? Buffer.allocUnsafe(size) : new Uint8Array(size); +} +function writeValue(ns, value, container, serdeContext) { + if (value == null) { + if (value === undefined && ns.isIdempotencyToken()) { + writeString(generateIdempotencyToken()); + return; + } + ensure(1); + buf[cursor++] = (majorSpecial << 5) | specialNull; + return; + } + if (ns.isUnitSchema()) { + ensure(1); + encodeHeader(majorMap, 0); + return; + } + const isObject = typeof value === "object"; + if (isObject) { + if (ns.isBlobSchema()) { + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + } + if (ns.isTimestampSchema()) { + if (value instanceof Date) { + writeTimestamp(value); + return; + } + } + if (ns.isStructSchema()) { + writeStruct(ns, value, serdeContext); + return; + } + if (Array.isArray(value) && (ns.isListSchema() || ns.isDocumentSchema())) { + writeList(ns, value, ns.isDocumentSchema(), serdeContext); + return; + } + if (ns.isMapSchema()) { + writeMap(ns, value, false, serdeContext); + return; + } + if (value instanceof Date) { + writeTimestamp(value); + return; + } + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + if (value instanceof NumericValue) { + writeNumericValue(value); + return; + } + if (value[tagSymbol]) { + const tagged = value; + writeTag(tagged.tag, tagged.value); + return; + } + if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + writeList(ns, value, true, serdeContext); + } + else { + writeMap(ns, value, true, serdeContext); + } + return; + } + if (ns.isBigDecimalSchema()) { + writeUntypedValue(value); + return; + } + writeMap(ns, value, true, serdeContext); + return; + } + if (typeof value === "string") { + if (ns.isBlobSchema()) { + const bytes = (serdeContext?.base64Decoder ?? fromBase64)(value); + writeBytes(bytes); + return; + } + writeString(value); + return; + } + if (typeof value === "number") { + ensure(9); + if (Number.isInteger(value) && value >= -9007199254740992 && value <= 0x1fffffffffffff) { + writeInteger(value); + } + else { + writeFloat64(value); + } + return; + } + if (typeof value === "boolean") { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | (value ? specialTrue : specialFalse); + return; + } + if (typeof value === "bigint") { + writeBigInt(value); + return; + } + writeString(String(value)); +} +function writeStruct(ns, value, serdeContext) { + if (ns.isUnionSchema()) { + let wrote = false; + for (const [memberName, memberSchema] of ns.structIterator()) { + const item = value[memberName]; + if (item != null) { + ensure(9); + encodeHeader(majorMap, 1); + writeString(memberName); + writeValue(memberSchema, item, ns, serdeContext); + wrote = true; + break; + } + } + if (!wrote) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + ensure(9); + encodeHeader(majorMap, 1); + writeString($unknown[0]); + writeUntypedValue($unknown[1]); + } + else { + ensure(9); + encodeHeader(majorMap, 0); + } + } + return; + } + const cache = loadCborStructIterator(ns); + const { memberNames, memberSchemas, encodedKeys } = cache; + const z = memberNames.length; + let headerSize; + if (z < 24) { + headerSize = 1; + } + else if (z < 256) { + headerSize = 2; + } + else { + headerSize = 3; + } + ensure(headerSize); + const headerPos = cursor; + cursor += headerSize; + let count = 0; + for (let i = 0; i < z; ++i) { + const item = value[memberNames[i]]; + if (item == null && !memberSchemas[i].isIdempotencyToken()) { + continue; + } + const key = encodedKeys[i]; + ensure(key.length); + buf.set(key, cursor); + cursor += key.length; + writeValue(memberSchemas[i], item, ns, serdeContext); + ++count; + } + if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!memberNames.includes(k)) { + writeString(k); + writeUntypedValue(value[k]); + ++count; + } + } + } + if (headerSize === 1) { + buf[headerPos] = (majorMap << 5) | count; + } + else if (headerSize === 2) { + buf[headerPos] = (majorMap << 5) | 24; + buf[headerPos + 1] = count; + } + else { + buf[headerPos] = (majorMap << 5) | extendedFloat16; + buf[headerPos + 1] = count >> 8; + buf[headerPos + 2] = count & 0xff; + } +} +function writeList(ns, value, isDocument, serdeContext) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (isDocument || sparse) { + const items = []; + for (let i = 0; i < value.length; ++i) { + const item = value[i]; + if (isDocument) { + if (item !== undefined) { + items.push(item); + } + } + else { + if (item != null || sparse) { + items.push(item); + } + } + } + ensure(9); + encodeHeader(majorList, items.length); + for (let i = 0; i < items.length; ++i) { + writeValue(valueSchema, items[i], undefined, serdeContext); + } + } + else { + let count = 0; + for (let i = 0; i < value.length; ++i) { + if (value[i] != null) { + ++count; + } + } + ensure(9); + encodeHeader(majorList, count); + for (let i = 0; i < value.length; ++i) { + if (value[i] != null) { + writeValue(valueSchema, value[i], undefined, serdeContext); + } + } + } +} +function writeMap(ns, value, isDocument, serdeContext) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + const keys = []; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + const v = value[k]; + if (isDocument ? v !== undefined : v != null || sparse) { + keys.push(k); + } + } + ensure(9); + encodeHeader(majorMap, keys.length); + for (let i = 0; i < keys.length; ++i) { + const k = keys[i]; + writeString(k); + writeValue(valueSchema, value[k], undefined, serdeContext); + } +} +function writeUntypedValue(value) { + if (value == null) { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | specialNull; + return; + } + if (typeof value === "string") { + writeString(value); + return; + } + if (typeof value === "number") { + ensure(9); + if (Number.isInteger(value) && value >= -9007199254740992 && value <= 0x1fffffffffffff) { + writeInteger(value); + } + else { + writeFloat64(value); + } + return; + } + if (typeof value === "boolean") { + ensure(1); + buf[cursor++] = (majorSpecial << 5) | (value ? specialTrue : specialFalse); + return; + } + if (typeof value === "bigint") { + writeBigInt(value); + return; + } + if (value instanceof Uint8Array) { + writeBytes(value); + return; + } + if (value instanceof Date) { + writeTimestamp(value); + return; + } + if (value instanceof NumericValue) { + writeNumericValue(value); + return; + } + if (value[tagSymbol]) { + const tagged = value; + writeTag(tagged.tag, tagged.value); + return; + } + if (Array.isArray(value)) { + ensure(9); + encodeHeader(majorList, value.length); + for (let i = 0; i < value.length; ++i) { + writeUntypedValue(value[i]); + } + return; + } + if (typeof value === "object") { + const keys = Object.keys(value); + ensure(9); + encodeHeader(majorMap, keys.length); + for (let i = 0; i < keys.length; ++i) { + writeString(keys[i]); + writeUntypedValue(value[keys[i]]); + } + return; + } + writeString(String(value)); +} +function ensure(n) { + if (cursor + n > buf.length) { + let newSize = buf.length * 2; + while (newSize < cursor + n) { + newSize *= 2; + } + const next = allocUnsafe(newSize); + next.set(buf.subarray(0, cursor)); + buf = next; + view = new DataView(next.buffer, next.byteOffset, next.byteLength); + } +} +function encodeHeader(major, value) { + if (value < 24) { + buf[cursor++] = (major << 5) | value; + } + else if (value < 256) { + buf[cursor++] = (major << 5) | 24; + buf[cursor++] = value; + } + else if (value < 65536) { + buf[cursor++] = (major << 5) | extendedFloat16; + buf[cursor++] = value >> 8; + buf[cursor++] = value & 0xff; + } + else if (value < 4294967296) { + buf[cursor++] = (major << 5) | extendedFloat32; + view.setUint32(cursor, value); + cursor += 4; + } + else { + buf[cursor++] = (major << 5) | extendedFloat64; + const hi = (value / 4294967296) | 0; + const lo = (value - hi * 4294967296) | 0; + view.setUint32(cursor, hi); + view.setUint32(cursor + 4, lo); + cursor += 8; + } +} +function encodeBigHeader(major, value) { + const n = Number(value); + if (n < 4294967296) { + encodeHeader(major, n); + return; + } + buf[cursor++] = (major << 5) | extendedFloat64; + view.setBigUint64(cursor, value); + cursor += 8; +} +function writeString(s) { + const len = s.length; + if (len <= 23) { + const cached = stringEncodeCache.get(s); + if (cached) { + ensure(cached.bytes.length); + buf.set(cached.bytes, cursor); + cursor += cached.bytes.length; + cached.epoch = encodeCacheEpoch; + return; + } + const start = cursor; + writeStringUncached(s, len); + const end = cursor; + const bytes = Uint8Array.prototype.slice.call(buf, start, end); + if (stringEncodeCache.size >= STRING_CACHE_MAX) { + if (encodeCacheSaturated) { + return; + } + let evicted = 0; + for (const [key, entry] of stringEncodeCache) { + if (evicted >= 1024) { + break; + } + if (entry.epoch !== encodeCacheEpoch) { + stringEncodeCache.delete(key); + ++evicted; + } + } + if (evicted === 0) { + encodeCacheSaturated = true; + return; + } + } + if (stringEncodeCache.size < STRING_CACHE_MAX) { + stringEncodeCache.set(s, { epoch: encodeCacheEpoch, bytes }); + } + return; + } + writeStringUncached(s, len); +} +function writeStringUncached(s, len) { + if (USE_BUFFER$1) { + const maxBytes = len * 3; + ensure(maxBytes + 9); + const byteLen = Buffer.byteLength(s); + encodeHeader(majorUtf8String, byteLen); + cursor += buf.write(s, cursor); + } + else { + const maxBytes = len * 3; + ensure(maxBytes + 9); + const headerPos = cursor; + const result = textEncoder.encodeInto(s, buf.subarray(headerPos + 9)); + const byteLen = result.written; + let headerSize; + if (byteLen < 24) { + headerSize = 1; + } + else if (byteLen < 256) { + headerSize = 2; + } + else if (byteLen < 65536) { + headerSize = 3; + } + else if (byteLen < 4294967296) { + headerSize = 5; + } + else { + headerSize = 9; + } + if (headerSize < 9) { + buf.copyWithin(headerPos + headerSize, headerPos + 9, headerPos + 9 + byteLen); + } + cursor = headerPos; + encodeHeader(majorUtf8String, byteLen); + cursor += byteLen; + } +} +function writeFloat64(value) { + ensure(9); + buf[cursor++] = (majorSpecial << 5) | extendedFloat64; + view.setFloat64(cursor, value); + cursor += 8; +} +function writeInteger(value) { + ensure(9); + const nonNegative = value >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const abs = nonNegative ? value : -value - 1; + encodeHeader(major, abs); +} +function writeBigInt(value) { + const nonNegative = value >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const abs = nonNegative ? value : -value - BigInt(1); + if (abs < BigInt("18446744073709551616")) { + ensure(9); + encodeBigHeader(major, abs); + } + else { + const binaryStr = abs.toString(2); + const byteLen = Math.ceil(binaryStr.length / 8); + const bigIntBytes = new Uint8Array(byteLen); + let b = abs; + for (let i = byteLen - 1; i >= 0; --i) { + bigIntBytes[i] = Number(b & BigInt(255)); + b >>= BigInt(8); + } + ensure(byteLen + 16); + buf[cursor++] = nonNegative ? 0b110_00010 : 0b110_00011; + encodeHeader(majorUnstructuredByteString, byteLen); + buf.set(bigIntBytes, cursor); + cursor += byteLen; + } +} +function writeBytes(data) { + ensure(data.length + 9); + encodeHeader(majorUnstructuredByteString, data.length); + buf.set(data, cursor); + cursor += data.length; +} +function writeTag(tagValue, innerValue) { + ensure(9); + if (typeof tagValue === "bigint") { + encodeBigHeader(majorTag, tagValue); + } + else { + encodeHeader(majorTag, tagValue); + } + writeUntypedValue(innerValue); +} +function writeNumericValue(nv) { + let str = nv.string; + let expOffset = BigInt(0); + const eIndex = str.search(/[eE]/); + if (eIndex !== -1) { + expOffset = BigInt(str.slice(eIndex + 1)); + str = str.slice(0, eIndex); + } + const decimalIndex = str.indexOf("."); + const fractionDigits = decimalIndex === -1 ? 0 : str.length - decimalIndex - 1; + const exponent = expOffset - BigInt(fractionDigits); + const mantissa = BigInt(str.replace(".", "")); + ensure(9); + buf[cursor++] = 0b110_00100; + encodeHeader(majorList, 2); + ensure(9); + if (exponent >= -0x20000000000000n && exponent <= 0x1fffffffffffffn) { + writeInteger(Number(exponent)); + } + else { + writeBigInt(exponent); + } + writeBigInt(mantissa); +} +function writeTimestamp(date) { + ensure(18); + encodeHeader(majorTag, 1); + const epochSecs = date.getTime() / 1000; + if (Number.isInteger(epochSecs)) { + writeInteger(epochSecs); + } + else { + writeFloat64(epochSecs); + } +} + +class CborShapeDeserializer2 extends SerdeContext { + read(schema, bytes) { + payload = bytes; + isBuffer = USE_BUFFER && bytes instanceof Buffer; + dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + pos = 0; + end = bytes.length; + cacheEpoch = (cacheEpoch + 1) & 0xffff; + return readValue(NormalizedSchema.of(schema)); + } + readValue(_schema, value) { + return transformObject(NormalizedSchema.of(_schema), value); + } +} +const USE_BUFFER = typeof Buffer !== "undefined"; +const textDecoder = new TextDecoder(); +let payload = new Uint8Array(0); +let isBuffer = false; +let dataView = new DataView(new ArrayBuffer(0)); +let pos = 0; +let end = 0; +const STRING_CACHE_SIZE = 2048; +const stringCache = new Array(STRING_CACHE_SIZE); +const stringCacheEpochs = new Uint16Array(STRING_CACHE_SIZE); +let cacheEpoch = 0; +function readValue(ns) { + if (pos >= end) { + throw new Error("unexpected end of CBOR payload."); + } + const major = (payload[pos] & 0b1110_0000) >> 5; + const minor = payload[pos] & 0b0001_1111; + if (minor === minorIndefinite && major >= 2 && major <= 5) { + return readIndefinite(ns, major); + } + switch (major) { + case majorUint64: + return readUnsignedInt(); + case majorNegativeInt64: + return readNegativeInt(); + case majorUnstructuredByteString: + return readByteString(); + case majorUtf8String: + return readUtf8String(); + case majorList: + return readList(ns); + case majorMap: + return readMap(ns); + case majorTag: + return readTag(); + case majorSpecial: + return readSpecial(); + default: + throw new Error(`unexpected CBOR major type ${major}.`); + } +} +function readList(ns) { + const count = decodeCount(); + const memberSchema = ns.isListSchema() ? ns.getValueSchema() : ns; + const list = Array(count); + for (let i = 0; i < count; ++i) { + list[i] = readValue(memberSchema); + } + return list; +} +function readMap(ns) { + const count = decodeCount(); + if (ns.isStructSchema()) { + const startPos = pos; + return readStruct(ns, count, startPos); + } + const valueSchema = ns.isMapSchema() ? ns.getValueSchema() : ns; + const map = {}; + for (let i = 0; i < count; ++i) { + const key = readUtf8String(); + map[key] = readValue(valueSchema); + } + return map; +} +function readStruct(ns, count, startPos) { + const isUnion = ns.isUnionSchema(); + const cache = loadCborStructIterator(ns); + const { memberSchemas, encodedKeys, memberNames } = cache; + const z = encodedKeys.length; + const result = {}; + let unknownKey; + let unknownValue; + let unknownCount = 0; + let hasType = false; + let hint = 0; + for (let i = 0; i < count; ++i) { + const matchIdx = matchStructKey(encodedKeys, z, hint); + if (matchIdx >= 0) { + hint = matchIdx + 1; + if (hint >= z) { + hint = 0; + } + const val = readValue(memberSchemas[matchIdx]); + if (val != null) { + result[memberNames[matchIdx]] = val; + } + } + else { + const key = readUtf8String(); + const val = readValue(NormalizedSchema.of(15)); + if (key === "__type" && typeof val === "string") { + hasType = true; + } + else { + unknownKey = key; + unknownValue = val; + ++unknownCount; + } + } + } + if (isUnion) { + let resultEmpty = true; + for (const _ in result) { + if (!hasOwn(result, _)) + continue; + resultEmpty = false; + break; + } + if (resultEmpty && unknownCount === 1) { + result.$unknown = [unknownKey, unknownValue]; + } + } + else if (hasType) { + pos = startPos; + const docSchema = NormalizedSchema.of(15); + for (let i = 0; i < count; ++i) { + const key = readUtf8String(); + const val = readValue(docSchema); + if (!(key in result)) { + result[key] = val; + } + } + } + return result; +} +function readTag(ns) { + const tagNum = decodeArgument(); + const tagNumber = typeof tagNum === "bigint" ? Number(tagNum) : tagNum; + if (tagNumber === 1) { + const docSchema = NormalizedSchema.of(15); + const epochValue = readValue(docSchema); + return _parseEpochTimestamp(epochValue); + } + if (tagNumber === 2 || tagNumber === 3) { + const byteStr = readByteString(); + let b = BigInt(0); + for (let i = 0; i < byteStr.length; ++i) { + b = (b << BigInt(8)) | BigInt(byteStr[i]); + } + return tagNumber === 3 ? -b - BigInt(1) : b; + } + if (tagNumber === 4) { + const docSchema = NormalizedSchema.of(15); + const pair = readValue(docSchema); + const [rawExponent, mantissa] = pair; + const normalizer = mantissa < 0 ? -1 : 1; + const absMantissa = BigInt(normalizer) * BigInt(mantissa); + const mantissaDigits = String(absMantissa); + const sign = mantissa < 0 ? "-" : ""; + let numericString; + const isSmallExponent = typeof rawExponent === "number" && Math.abs(rawExponent) <= 2 ** 28; + if (isSmallExponent) { + const exponent = rawExponent; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + mantissaDigits; + numericString = + exponent === 0 + ? mantissaStr + : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign + numericString; + } + else { + const bigExponent = BigInt(rawExponent); + if (mantissaDigits.length === 1) { + numericString = sign + mantissaDigits + "e" + String(bigExponent); + } + else { + const adjustedExp = bigExponent + BigInt(mantissaDigits.length - 1); + numericString = sign + mantissaDigits[0] + "." + mantissaDigits.slice(1) + "e" + String(adjustedExp); + } + } + return nv(numericString); + } + const docSchema = NormalizedSchema.of(15); + const innerValue = readValue(docSchema); + return { tag: castBigInt(tagNum), value: innerValue }; +} +function readIndefinite(ns, major) { + switch (major) { + case majorUtf8String: + return readUtf8StringIndefinite(); + case majorUnstructuredByteString: + return readByteStringIndefinite(); + case majorList: + return readListIndefinite(ns); + case majorMap: + return readMapIndefinite(ns); + default: + throw new Error(`unexpected indefinite length for major ${major}.`); + } +} +function readUtf8StringIndefinite() { + pos += 1; + const chunks = []; + let totalLen = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + const combined = new Uint8Array(totalLen); + let offset = 0; + for (let i = 0; i < chunks.length; ++i) { + combined.set(chunks[i], offset); + offset += chunks[i].length; + } + if (USE_BUFFER) { + return Buffer.from(combined.buffer, combined.byteOffset, combined.byteLength).toString("utf-8"); + } + return textDecoder.decode(combined); + } + const bytes = readByteString(); + chunks.push(bytes); + totalLen += bytes.length; + } + throw new Error("expected break marker."); +} +function readByteStringIndefinite() { + pos += 1; + const chunks = []; + let totalLen = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + const combined = new Uint8Array(totalLen); + let offset = 0; + for (let i = 0; i < chunks.length; ++i) { + combined.set(chunks[i], offset); + offset += chunks[i].length; + } + return combined; + } + const bytes = readByteString(); + chunks.push(bytes); + totalLen += bytes.length; + } + throw new Error("expected break marker."); +} +function readListIndefinite(ns) { + pos += 1; + const memberSchema = ns.isListSchema() ? ns.getValueSchema() : ns; + const list = []; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + return list; + } + list.push(readValue(memberSchema)); + } + throw new Error("expected break marker."); +} +function readMapIndefinite(ns) { + pos += 1; + if (ns.isStructSchema()) { + const cache = loadCborStructIterator(ns); + const { memberSchemas, encodedKeys, memberNames } = cache; + const z = encodedKeys.length; + const isUnion = ns.isUnionSchema(); + const result = {}; + let unknownKey; + let unknownValue; + let unknownCount = 0; + let hint = 0; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + if (isUnion) { + let resultEmpty = true; + for (const _ in result) { + if (!hasOwn(result, _)) + continue; + resultEmpty = false; + break; + } + if (resultEmpty && unknownCount === 1) { + result.$unknown = [unknownKey, unknownValue]; + } + } + return result; + } + const matchIdx = matchStructKey(encodedKeys, z, hint); + if (matchIdx >= 0) { + hint = matchIdx + 1; + if (hint >= z) { + hint = 0; + } + const val = readValue(memberSchemas[matchIdx]); + if (val != null) { + result[memberNames[matchIdx]] = val; + } + } + else { + const key = readUtf8String(); + const val = readValue(NormalizedSchema.of(15)); + if (key !== "__type") { + unknownKey = key; + unknownValue = val; + ++unknownCount; + } + } + } + throw new Error("expected break marker."); + } + const valueSchema = ns.isMapSchema() ? ns.getValueSchema() : ns; + const map = {}; + while (pos < end) { + if (payload[pos] === 0xff) { + pos += 1; + return map; + } + const key = readUtf8String(); + map[key] = readValue(valueSchema); + } + throw new Error("expected break marker."); +} +function matchStructKey(encodedKeys, z, hint) { + const hintKey = encodedKeys[hint]; + if (pos + hintKey.length <= end && bytesMatch(pos, hintKey)) { + pos += hintKey.length; + return hint; + } + for (let i = 0; i < z; ++i) { + if (i === hint) { + continue; + } + const ek = encodedKeys[i]; + if (pos + ek.length <= end && bytesMatch(pos, ek)) { + pos += ek.length; + return i; + } + } + return -1; +} +function bytesMatch(at, expected) { + const len = expected.length; + if (payload[at] !== expected[0]) { + return false; + } + for (let i = 1; i < len; ++i) { + if (payload[at + i] !== expected[i]) { + return false; + } + } + return true; +} +function decodeArgument() { + const minor = payload[pos] & 0b0001_1111; + if (minor < 24) { + pos += 1; + return minor; + } + switch (minor) { + case extendedOneByte: + if (end - pos < 2) { + overflow(1); + } + pos += 2; + return payload[pos - 1]; + case extendedFloat16: + if (end - pos < 3) { + overflow(2); + } + pos += 3; + return dataView.getUint16(pos - 2); + case extendedFloat32: + if (end - pos < 5) { + overflow(4); + } + pos += 5; + return dataView.getUint32(pos - 4); + case extendedFloat64: { + if (end - pos < 9) { + overflow(8); + } + pos += 9; + const hi = dataView.getUint32(pos - 8); + if (hi < 0x00200000) { + return hi * 4294967296 + dataView.getUint32(pos - 4); + } + return dataView.getBigUint64(pos - 8); + } + default: + throw new Error(`unexpected minor value ${minor}.`); + } +} +function decodeCount() { + const val = decodeArgument(); + return typeof val === "bigint" ? Number(val) : val; +} +function readUnsignedInt() { + const val = decodeArgument(); + return castBigInt(val); +} +function readNegativeInt() { + const val = decodeArgument(); + if (typeof val === "bigint") { + return BigInt(-1) - val; + } + return -1 - val; +} +function readByteString() { + const length = decodeCount(); + if (end - pos < length) { + overflow(length); + } + const start = pos; + pos += length; + return payload.subarray(start, start + length); +} +function readUtf8String() { + const length = decodeCount(); + if (end - pos < length) { + overflow(length); + } + const start = pos; + pos += length; + if (length < 24) { + return decodeUtf8Cached(start, length); + } + if (isBuffer) { + return payload.toString("utf-8", start, start + length); + } + return textDecoder.decode(payload.subarray(start, start + length)); +} +function decodeUtf8Cached(at, length) { + let h = length; + for (let i = 0; i < length; ++i) { + h = (h * 31 + payload[at + i]) | 0; + } + const slot = (h >>> 0) & (STRING_CACHE_SIZE - 1); + const cached = stringCache[slot]; + if (cached !== undefined && cached.length === length) { + let match = true; + for (let i = 0; i < length; ++i) { + if (cached.charCodeAt(i) !== payload[at + i]) { + match = false; + break; + } + } + if (match) { + stringCacheEpochs[slot] = cacheEpoch; + return cached; + } + } + const result = isBuffer + ? payload.toString("utf-8", at, at + length) + : textDecoder.decode(payload.subarray(at, at + length)); + if (stringCacheEpochs[slot] !== cacheEpoch) { + stringCache[slot] = result; + stringCacheEpochs[slot] = cacheEpoch; + } + return result; +} +function readSpecial() { + const p = pos; + const minor = payload[p] & 0b0001_1111; + switch (minor) { + case specialTrue: + pos = p + 1; + return true; + case specialFalse: + pos = p + 1; + return false; + case specialNull: + pos = p + 1; + return null; + case specialUndefined: + pos = p + 1; + return null; + case extendedFloat16: { + if (end - p < 3) { + overflow(2); + } + pos = p + 3; + return bytesToFloat16(payload[p + 1], payload[p + 2]); + } + case extendedFloat32: { + if (end - p < 5) { + overflow(4); + } + pos = p + 5; + return dataView.getFloat32(p + 1); + } + case extendedFloat64: { + if (end - p < 9) { + overflow(8); + } + pos = p + 9; + return dataView.getFloat64(p + 1); + } + default: + throw new Error(`unexpected minor value ${minor} for major 7.`); + } +} +function bytesToFloat16(a, b) { + const sign = a >> 7; + const exponent = (a & 0b0111_1100) >> 2; + const fraction = ((a & 0b0000_0011) << 8) | b; + const scalar = sign === 0 ? 1 : -1; + if (exponent === 0b00000) { + if (fraction === 0) { + return 0; + } + return scalar * (Math.pow(2, 1 - 15) * (fraction / 1024)); + } + else if (exponent === 0b11111) { + if (fraction === 0) { + return scalar * Infinity; + } + return NaN; + } + return scalar * (Math.pow(2, exponent - 15) * (1 + fraction / 1024)); +} +function castBigInt(value) { + if (typeof value === "number") { + return value; + } + const num = Number(value); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return value; +} +function overflow(n) { + throw new Error(`CBOR: length ${n} greater than remaining buffer length.`); +} +function transformObject(ns, value) { + if (ns.isTimestampSchema()) { + if (typeof value === "number") { + return _parseEpochTimestamp(value); + } + if (typeof value === "object" && value !== null) { + if (value.tag === 1 && "value" in value) { + return _parseEpochTimestamp(value.value); + } + } + } + if (ns.isBlobSchema()) { + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + if (typeof value !== "object" || value === null) { + return value; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (value instanceof NumericValue) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const memberSchema = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(transformObject(memberSchema, item)); + } + return out; + } + const newObject = {}; + if (ns.isMapSchema()) { + const targetSchema = ns.getValueSchema(); + for (const key in value) { + if (!hasOwn(value, key)) + continue; + newObject[key] = transformObject(targetSchema, value[key]); + } + } + else if (ns.isStructSchema()) { + const isUnion = ns.isUnionSchema(); + let keys; + if (isUnion) { + keys = new Set(); + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (k !== "__type") { + keys.add(k); + } + } + } + for (const [key, memberSchema] of ns.structIterator()) { + if (isUnion) { + keys.delete(key); + } + if (value[key] != null) { + newObject[key] = transformObject(memberSchema, value[key]); + } + } + if (isUnion && keys?.size === 1) { + let newObjectEmpty = true; + for (const _ in newObject) { + if (!hasOwn(newObject, _)) + continue; + newObjectEmpty = false; + break; + } + if (newObjectEmpty) { + const k = keys.values().next().value; + newObject.$unknown = [k, value[k]]; + } + } + else if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!(k in newObject)) { + newObject[k] = value[k]; + } + } + } + } + return newObject; +} + +class CborCodec extends SerdeContext { + createSerializer() { + const serializer = new CborShapeSerializer2(); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new CborShapeDeserializer2(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class SmithyRpcV2CborProtocol extends RpcProtocol { + codec = new CborCodec(); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace, errorTypeRegistries, }) { + super({ defaultNamespace, errorTypeRegistries }); + } + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType(), + }); + if (deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } + else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + if (request.body instanceof Uint8Array) { + request.headers["content-length"] = String(request.body.byteLength); + } + } + const { service, operation } = getSmithyContext(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } + else { + request.path += path; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const preferredNamespaces = ["*"]; + const { defaultNamespace } = this.options; + preferredNamespaces.unshift(defaultNamespace); + const [namespace, errorShapeName] = (() => { + if (errorIdentifier.includes("#")) { + return errorIdentifier.split("#"); + } + return [undefined, errorIdentifier]; + })(); + if (namespace) { + preferredNamespaces.unshift(namespace); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server", + }; + const preferredRegistries = [this.compositeErrorRegistry]; + if (namespace) { + preferredRegistries.push(TypeRegistry.for(namespace)); + } + preferredRegistries.push(TypeRegistry.for(defaultNamespace)); + const [errorSchema, ErrorCtor, errorMode] = this.resolveError(errorShapeName, preferredNamespaces, preferredRegistries); + if (errorMode === "native" || errorMode === "synthetic") { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const error = errorMode === "synthetic" ? new ErrorCtor({ name: errorShapeName }) : new Error(errorShapeName); + throw Object.assign(error, errorMetadata, dataObject); + } + const ns = NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor({}); + const output = {}; + for (const [name, member] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member, dataObject[name]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/cbor"; + } +} + +class CborShapeSerializer extends SerdeContext { + value; + write(schema, value) { + this.value = this.serialize(schema, value); + } + serialize(schema, source) { + const ns = NormalizedSchema.of(schema); + if (source == null) { + if (ns.isIdempotencyToken()) { + return generateIdempotencyToken(); + } + return source; + } + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? fromBase64)(source); + } + return source; + } + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date((Number(source) / 1000) | 0)); + } + return dateToTag(source); + } + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i++] = value; + } + } + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key in sourceObject) { + if (!hasOwn(sourceObject, key)) + continue; + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } + } + } + else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + const isUnion = ns.isUnionSchema(); + if (isUnion && Array.isArray(sourceObject.$unknown)) { + const [k, v] = sourceObject.$unknown; + newObject[k] = v; + } + else if (typeof sourceObject.__type === "string") { + for (const k in sourceObject) { + if (!hasOwn(sourceObject, k)) + continue; + if (!(k in newObject)) { + newObject[k] = this.serialize(15, sourceObject[k]); + } + } + } + } + else if (ns.isDocumentSchema()) { + if (Array.isArray(sourceObject)) { + const newArray = []; + let i = 0; + for (const item of sourceObject) { + newArray[i++] = this.serialize(ns.getValueSchema(), item); + } + return newArray; + } + for (const key in sourceObject) { + if (!hasOwn(sourceObject, key)) + continue; + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + } + } + else if (ns.isBigDecimalSchema()) { + return sourceObject; + } + return newObject; + } + return source; + } + flush() { + const buffer = cbor.serialize(this.value); + this.value = undefined; + return buffer; + } +} + +class CborShapeDeserializer extends SerdeContext { + read(schema, bytes) { + const data = cbor.deserialize(bytes); + return this.readValue(schema, data); + } + readValue(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isTimestampSchema()) { + if (typeof value === "number") { + return _parseEpochTimestamp(value); + } + if (typeof value === "object") { + if (value.tag === 1 && "value" in value) { + return _parseEpochTimestamp(value.value); + } + } + } + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || + typeof value === "boolean" || + typeof value === "number" || + typeof value === "string" || + typeof value === "bigint" || + typeof value === "symbol") { + return value; + } + else if (typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + newArray.push(itemValue); + } + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const targetSchema = ns.getValueSchema(); + for (const key in value) { + if (!hasOwn(value, key)) + continue; + const itemValue = this.readValue(targetSchema, value[key]); + newObject[key] = itemValue; + } + } + else if (ns.isStructSchema()) { + const isUnion = ns.isUnionSchema(); + let keys; + if (isUnion) { + keys = new Set(); + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (k !== "__type") { + keys.add(k); + } + } + } + for (const [key, memberSchema] of ns.structIterator()) { + if (isUnion) { + keys.delete(key); + } + if (value[key] != null) { + newObject[key] = this.readValue(memberSchema, value[key]); + } + } + if (isUnion && keys?.size === 1) { + let newObjectEmpty = true; + for (const _ in newObject) { + if (!hasOwn(newObject, _)) + continue; + newObjectEmpty = false; + break; + } + if (newObjectEmpty) { + const k = keys.values().next().value; + newObject.$unknown = [k, value[k]]; + } + } + else if (typeof value.__type === "string") { + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (!(k in newObject)) { + newObject[k] = value[k]; + } + } + } + } + else if (value instanceof NumericValue) { + return value; + } + return newObject; + } + else { + return value; + } + } +} + +exports.CborCodec = CborCodec; +exports.CborShapeDeserializer = CborShapeDeserializer; +exports.CborShapeDeserializer2 = CborShapeDeserializer2; +exports.CborShapeSerializer = CborShapeSerializer; +exports.CborShapeSerializer2 = CborShapeSerializer2; +exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol; +exports.buildHttpRpcRequest = buildHttpRpcRequest; +exports.cbor = cbor; +exports.checkCborResponse = checkCborResponse; +exports.dateToTag = dateToTag; +exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; +exports.parseCborBody = parseCborBody; +exports.parseCborErrorBody = parseCborErrorBody; +exports.tag = tag; +exports.tagSymbol = tagSymbol; + + +/***/ }), + +/***/ 95899: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { createReadStream } = __webpack_require__(73024); +const { Writable } = __webpack_require__(57075); +const { toUint8Array, concatBytes } = __webpack_require__(34129); +const { createHash, createHmac } = __webpack_require__(77598); +const zlib = __webpack_require__(38522); + +async function blobReader(blob, onChunk, chunkSize = 1024 * 1024) { + const size = blob.size; + let totalBytesRead = 0; + while (totalBytesRead < size) { + const slice = blob.slice(totalBytesRead, Math.min(size, totalBytesRead + chunkSize)); + onChunk(new Uint8Array(await slice.arrayBuffer())); + totalBytesRead += slice.size; + } +} + +const blobHasher = async function blobHasher(hashCtor, blob) { + const hash = new hashCtor(); + await blobReader(blob, (chunk) => { + hash.update(chunk); + }); + return hash.digest(); +}; + +class HashCalculator extends Writable { + hash; + constructor(hash, options) { + super(options); + this.hash = hash; + } + _write(chunk, encoding, callback) { + try { + this.hash.update(toUint8Array(chunk)); + } + catch (err) { + return callback(err); + } + callback(); + } +} + +const fileStreamHasher = (hashCtor, fileStream) => new Promise((resolve, reject) => { + if (!isReadStream(fileStream)) { + reject(new Error("Unable to calculate hash for non-file streams.")); + return; + } + const fileStreamTee = createReadStream(fileStream.path, { + start: fileStream.start, + end: fileStream.end, + }); + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + fileStreamTee.pipe(hashCalculator); + fileStreamTee.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", function () { + hash.digest().then(resolve).catch(reject); + }); +}); +const isReadStream = (stream) => typeof stream.path === "string"; + +const readableStreamHasher = (hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); + } + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + readableStream.pipe(hashCalculator); + return new Promise((resolve, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash.digest().then(resolve).catch(reject); + }); + }); +}; + +class Md5Js { + digestLength = 16; + state = Uint32Array.from(INIT$1); + writeBuffer = new DataView(new ArrayBuffer(64)); + bufferLength = 0; + bytesHashed = 0; + update(sourceData) { + const data = toUint8Array(sourceData); + let pos = 0; + let len = data.byteLength; + this.bytesHashed += len; + while (len > 0) { + this.writeBuffer.setUint8(this.bufferLength++, data[pos++]); + --len; + if (this.bufferLength === 64) { + compress(this.state, this.writeBuffer); + this.bufferLength = 0; + } + } + } + async digest() { + const state = Uint32Array.from(this.state); + const buf = new DataView(this.writeBuffer.buffer.slice(0)); + let bufLen = this.bufferLength; + const bits = this.bytesHashed * 8; + buf.setUint8(bufLen++, 0x80); + if (this.bufferLength % 64 >= 56) { + for (let i = bufLen; i < 64; ++i) { + buf.setUint8(i, 0); + } + compress(state, buf); + bufLen = 0; + } + for (let i = bufLen; i < 56; ++i) { + buf.setUint8(i, 0); + } + buf.setUint32(56, bits >>> 0, true); + buf.setUint32(60, Math.floor(bits / 2 ** 32), true); + compress(state, buf); + const out = new Uint8Array(16); + const view = new DataView(out.buffer); + for (let i = 0; i < 4; ++i) { + view.setUint32(i * 4, state[i], true); + } + return out; + } + reset() { + this.state.set(INIT$1); + this.writeBuffer = new DataView(new ArrayBuffer(64)); + this.bufferLength = 0; + this.bytesHashed = 0; + } +} +const INIT$1 = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; +const M = 0xffffffff; +const S = Uint8Array.of(7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21); +const T = Array.from({ length: 64 }, (_, i) => (Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0); +function compress(state, block) { + let a = state[0], b = state[1], c = state[2], d = state[3]; + for (let i = 0; i < 64; ++i) { + let f, g; + if (i < 16) { + f = (b & c) | (~b & d); + g = i; + } + else if (i < 32) { + f = (d & b) | (c & ~d); + g = (5 * i + 1) % 16; + } + else if (i < 48) { + f = b ^ c ^ d; + g = (3 * i + 5) % 16; + } + else { + f = c ^ (b | ~d); + g = (7 * i) % 16; + } + const x = block.getUint32(g * 4, true); + const tmp = d; + d = c; + c = b; + const s = S[(i >> 4) * 4 + (i & 3)]; + const sum = (((a + f) & M) + ((x + T[i]) & M)) & M; + b = (b + (((sum << s) | (sum >>> (32 - s))) >>> 0)) & M; + a = tmp; + } + state[0] = (state[0] + a) & M; + state[1] = (state[1] + b) & M; + state[2] = (state[2] + c) & M; + state[3] = (state[3] + d) & M; +} + +const hasNativeCrypto$1 = (() => { + try { + createHash("md5"); + return true; + } + catch { + return false; + } +})(); +const Md5Node = hasNativeCrypto$1 ? buildNativeClass$2() : Md5Js; +function buildNativeClass$2() { + return class Md5Node { + digestLength = 16; + hash = createHash("md5"); + update(data) { + this.hash.update(toUint8Array(data)); + } + async digest() { + const buf = this.hash.copy().digest(); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + reset() { + this.hash = createHash("md5"); + } + }; +} + +const CRC32_TABLE = new Uint32Array(256); +for (let i = 0; i < 256; ++i) { + let c = i; + for (let j = 0; j < 8; ++j) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + CRC32_TABLE[i] = c >>> 0; +} +const ONES = 0xffff_ffff; +class Crc32Js { + digestLength = 4; + checksum = ONES; + update(data) { + for (let i = 0; i < data.length; ++i) { + this.checksum = (this.checksum >>> 8) ^ CRC32_TABLE[(this.checksum ^ data[i]) & 0xff]; + } + } + digestSync() { + return (this.checksum ^ ONES) >>> 0; + } + async digest() { + const value = this.digestSync(); + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, value, false); + return out; + } + reset() { + this.checksum = ONES; + } +} + +const zlibCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : undefined; +const Crc32Node = zlibCrc32 ? buildNativeClass$1(zlibCrc32) : Crc32Js; +function buildNativeClass$1(nativeCrc32) { + return class Crc32Node { + digestLength = 4; + value = 0; + update(data) { + this.value = nativeCrc32(data, this.value); + } + digestSync() { + return this.value >>> 0; + } + async digest() { + const out = new Uint8Array(4); + new DataView(out.buffer).setUint32(0, this.digestSync(), false); + return out; + } + reset() { + this.value = 0; + } + }; +} + +const BLOCK = 64; +const DIGEST_LENGTH = 32; +const MAX_HASHABLE_LENGTH = 2 ** 53 - 1; +class Sha256Js { + digestLength = DIGEST_LENGTH; + state = Int32Array.from(INIT); + w; + buffer = new Uint8Array(64); + bufferLength = 0; + bytesHashed = 0; + finished = false; + inner; + outer; + constructor(secret) { + if (secret) { + const key = Sha256Js.normalizeKey(secret); + this.inner = new Sha256Js(); + this.outer = new Sha256Js(); + const { inner, outer } = this; + const pad = new Uint8Array(BLOCK * 2); + for (let i = 0; i < BLOCK; ++i) { + pad[i] = 0x36 ^ key[i]; + pad[i + BLOCK] = 0x5c ^ key[i]; + } + inner.update(pad.subarray(0, BLOCK)); + outer.update(pad.subarray(BLOCK)); + } + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished HMAC."); + } + if (this.inner) { + this.inner.update(data); + return; + } + const chunk = toUint8Array(data); + let position = 0; + let { byteLength } = chunk; + this.bytesHashed += byteLength; + if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) { + throw new Error("Cannot hash more than 2^53 - 1 bits"); + } + while (byteLength > 0) { + this.buffer[this.bufferLength++] = chunk[position++]; + byteLength--; + if (this.bufferLength === BLOCK) { + this.hashBuffer(); + this.bufferLength = 0; + } + } + } + async digest() { + const { inner, outer } = this; + if (inner && outer) { + if (this.finished) { + throw new Error("Attempted to digest an already finished HMAC."); + } + this.finished = true; + const innerDigest = inner.digestSync(); + outer.update(innerDigest); + return outer.digestSync(); + } + return this.digestSync(); + } + reset() { + this.state = Int32Array.from(INIT); + this.buffer = new Uint8Array(64); + this.bufferLength = 0; + this.bytesHashed = 0; + } + digestSync() { + const state = this.state.slice(); + const buffer = this.buffer.slice(); + let bufferLength = this.bufferLength; + const bitsHashed = this.bytesHashed * 8; + const bufferView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + bufferView.setUint8(bufferLength++, 0x80); + if ((bufferLength - 1) % BLOCK >= BLOCK - 8) { + for (let i = bufferLength; i < BLOCK; ++i) { + bufferView.setUint8(i, 0); + } + this.hashBufferWith(state, buffer); + bufferLength = 0; + } + for (let i = bufferLength; i < BLOCK - 8; ++i) { + bufferView.setUint8(i, 0); + } + bufferView.setUint32(BLOCK - 8, Math.floor(bitsHashed / 0x100000000), false); + bufferView.setUint32(BLOCK - 4, bitsHashed, false); + this.hashBufferWith(state, buffer); + const out = new Uint8Array(DIGEST_LENGTH); + for (let i = 0; i < 8; ++i) { + out[i * 4] = (state[i] >>> 24) & 0xff; + out[i * 4 + 1] = (state[i] >>> 16) & 0xff; + out[i * 4 + 2] = (state[i] >>> 8) & 0xff; + out[i * 4 + 3] = (state[i] >>> 0) & 0xff; + } + return out; + } + static normalizeKey(secret) { + const key = toUint8Array(secret); + if (key.byteLength > BLOCK) { + const h = new Sha256Js(); + h.update(key); + const out = h.digestSync(); + const padded = new Uint8Array(BLOCK); + padded.set(out); + return padded; + } + if (key.byteLength < BLOCK) { + const padded = new Uint8Array(BLOCK); + padded.set(key); + return padded; + } + return key; + } + hashBuffer() { + this.hashBufferWith(this.state, this.buffer); + } + hashBufferWith(state, buffer) { + const w = (this.w ??= new Int32Array(64)); + let s0 = state[0], s1 = state[1], s2 = state[2], s3 = state[3], s4 = state[4], s5 = state[5], s6 = state[6], s7 = state[7]; + for (let i = 0; i < BLOCK; ++i) { + if (i < 16) { + w[i] = + ((buffer[i * 4] & 0xff) << 24) | + ((buffer[i * 4 + 1] & 0xff) << 16) | + ((buffer[i * 4 + 2] & 0xff) << 8) | + (buffer[i * 4 + 3] & 0xff); + } + else { + let u = w[i - 2]; + const t1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10); + u = w[i - 15]; + const t2 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3); + w[i] = ((t1 + w[i - 7]) | 0) + ((t2 + w[i - 16]) | 0); + } + const t1 = ((((((s4 >>> 6) | (s4 << 26)) ^ ((s4 >>> 11) | (s4 << 21)) ^ ((s4 >>> 25) | (s4 << 7))) + + ((s4 & s5) ^ (~s4 & s6))) | + 0) + + ((s7 + ((K[i] + w[i]) | 0)) | 0)) | + 0; + const t2 = ((((s0 >>> 2) | (s0 << 30)) ^ ((s0 >>> 13) | (s0 << 19)) ^ ((s0 >>> 22) | (s0 << 10))) + + ((s0 & s1) ^ (s0 & s2) ^ (s1 & s2))) | + 0; + s7 = s6; + s6 = s5; + s5 = s4; + s4 = (s3 + t1) | 0; + s3 = s2; + s2 = s1; + s1 = s0; + s0 = (t1 + t2) | 0; + } + state[0] += s0; + state[1] += s1; + state[2] += s2; + state[3] += s3; + state[4] += s4; + state[5] += s5; + state[6] += s6; + state[7] += s7; + } +} +const INIT = new Int32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]); +const K = new Int32Array([ + 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, +]); + +const hasNativeCrypto = (() => { + try { + createHash("sha256"); + return true; + } + catch { + return false; + } +})(); +const Sha256Node = hasNativeCrypto ? buildNativeClass() : Sha256Js; +function buildNativeClass() { + return class Sha256Node { + digestLength = 32; + secret; + hash; + isHmac; + finished = false; + constructor(secret) { + this.secret = secret; + this.isHmac = !!secret; + this.hash = this.createHash(); + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished hash."); + } + this.hash.update(data); + } + async digest() { + let buf; + if (this.isHmac) { + this.finished = true; + buf = this.hash.digest(); + } + else { + buf = this.hash.copy().digest(); + } + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + reset() { + this.hash = this.createHash(); + this.finished = false; + } + createHash() { + return this.secret ? createHmac("sha256", toBuffer(this.secret)) : createHash("sha256"); + } + }; +} +function toBuffer(data) { + if (typeof data === "string") { + return data; + } + if (ArrayBuffer.isView(data)) { + return Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } + return Buffer.from(data); +} + +const { digest, sign, importKey } = globalThis?.crypto?.subtle ?? {}; +const subtle = typeof digest === "function" && typeof sign === "function" && typeof importKey === "function" + ? globalThis.crypto.subtle + : undefined; +const MAX_PENDING_BYTES = 8 * 1024 * 1024; +class Sha256WebCrypto { + digestLength = 32; + secret; + pending = []; + pendingBytes = 0; + fallback; + finished = false; + constructor(secret) { + if (secret) { + this.secret = toUint8Array(secret); + } + } + update(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished HMAC."); + } + if (this.fallback) { + this.fallback.update(data); + return; + } + this.pending.push(data.slice()); + this.pendingBytes += data.byteLength; + if (this.pendingBytes >= MAX_PENDING_BYTES) { + this.switchToFallback(); + } + } + async digest() { + if (this.fallback) { + return this.fallback.digest(); + } + if (this.secret && this.finished) { + throw new Error("Attempted to digest an already finished HMAC."); + } + const data = concatBytes(this.pending); + if (subtle) { + if (this.secret) { + this.finished = true; + const key = await subtle.importKey("raw", this.secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); + const sig = await subtle.sign("HMAC", key, data); + return new Uint8Array(sig); + } + const hash = await subtle.digest("SHA-256", data); + return new Uint8Array(hash); + } + const sha256 = new Sha256Js(this.secret); + sha256.update(data); + return sha256.digest(); + } + reset() { + this.pending = []; + this.pendingBytes = 0; + this.fallback = undefined; + this.finished = false; + } + switchToFallback() { + const sha256Js = new Sha256Js(this.secret); + for (const chunk of this.pending) { + sha256Js.update(chunk); + } + this.fallback = sha256Js; + this.pending = []; + this.pendingBytes = 0; + } +} + +exports.Crc32 = Crc32Node; +exports.Crc32Js = Crc32Js; +exports.Crc32Node = Crc32Node; +exports.Md5 = Md5Node; +exports.Md5Js = Md5Js; +exports.Md5Node = Md5Node; +exports.Sha256 = Sha256Node; +exports.Sha256Js = Sha256Js; +exports.Sha256Node = Sha256Node; +exports.Sha256WebCrypto = Sha256WebCrypto; +exports.blobHasher = blobHasher; +exports.blobReader = blobReader; +exports.fileStreamHasher = fileStreamHasher; +exports.readableStreamHasher = readableStreamHasher; + + +/***/ }), + +/***/ 20895: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { hasOwn } = __webpack_require__(30673); +const { getSmithyContext, normalizeProvider } = __webpack_require__(30673); +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; +const { SMITHY_CONTEXT_KEY, AlgorithmId } = __webpack_require__(88867); +exports.AlgorithmId = AlgorithmId; +const { NormalizedSchema } = __webpack_require__(39875); + +const getAllAliases = (name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; +}; +const getMiddlewareNameWithAliases = (name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}; +const constructStack = () => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = new Set(); + const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] || + priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]); + const removeByName = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const removeByReference = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const cloneTo = (toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }; + const expandRelativeMiddlewareList = (from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } + else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }; + const getMiddlewareList = (debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [], + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === undefined) { + if (debug) { + return; + } + throw new Error(`${entry.toMiddleware} is not found when adding ` + + `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + + `middleware ${entry.relation} ${entry.toMiddleware}`); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries) + .map(expandRelativeMiddlewareList) + .reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }; + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + + `${toOverride.priority} priority in ${toOverride.step} step cannot ` + + `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + + `${entry.priority} priority in ${entry.step} step.`); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options, + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + + `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + + `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + + `"${entry.toMiddleware}" middleware.`); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? + mw.relation + + " " + + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList() + .map((entry) => entry.middleware) + .reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + }, + }; + return stack; +}; +const stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1, +}; +const priorityWeights = { + high: 3, + normal: 2, + low: 1, +}; + +const invalidFunction = (message) => () => { + throw new Error(message); +}; + +const invalidProvider = (message) => () => Promise.reject(message); + +const getCircularReplacer = () => { + const seen = new WeakSet(); + return (key, value) => { + if (typeof value === "object" && value !== null) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }; +}; + +const sleep = (seconds) => { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); +}; + +const waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120, +}; +var WaiterState; +(function (WaiterState) { + WaiterState["ABORTED"] = "ABORTED"; + WaiterState["FAILURE"] = "FAILURE"; + WaiterState["SUCCESS"] = "SUCCESS"; + WaiterState["RETRY"] = "RETRY"; + WaiterState["TIMEOUT"] = "TIMEOUT"; +})(WaiterState || (WaiterState = {})); +const checkExceptions = (result) => { + if (result.state === WaiterState.ABORTED) { + const abortError = new Error(`${JSON.stringify({ + ...result, + reason: "Request was aborted", + }, getCircularReplacer())}`); + abortError.name = "AbortError"; + throw abortError; + } + else if (result.state === WaiterState.TIMEOUT) { + const timeoutError = new Error(`${JSON.stringify({ + ...result, + reason: "Waiter has timed out", + }, getCircularReplacer())}`); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } + else if (result.state !== WaiterState.SUCCESS) { + throw new Error(`${JSON.stringify(result, getCircularReplacer())}`); + } + return result; +}; + +const runPolling = async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const [minDelayMs, maxDelayMs] = [minDelay * 1000, maxDelay * 1000]; + let currentAttempt = 0; + const waitUntil = Date.now() + maxWaitTime * 1000; + const warn403Time = Date.now() + 60_000; + let didWarn403 = false; + while (true) { + if (currentAttempt > 0) { + const delayMs = exponentialBackoffWithJitter(minDelayMs, maxDelayMs, currentAttempt, waitUntil); + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message = "AbortController signal aborted."; + observedResponses[message] |= 0; + observedResponses[message] += 1; + return { state: WaiterState.ABORTED, observedResponses }; + } + if (Date.now() + delayMs > waitUntil) { + return { state: WaiterState.TIMEOUT, observedResponses }; + } + await sleep(delayMs / 1_000); + } + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state !== WaiterState.RETRY) { + return { state, reason, final: reason, observedResponses }; + } + currentAttempt += 1; + if (!didWarn403 && Date.now() >= warn403Time) { + checkWarn403(observedResponses, client); + didWarn403 = true; + } + } +}; +const checkWarn403 = (observedResponses = {}, client) => { + const orderedErrors = Object.keys(observedResponses); + let count403 = 0; + for (const response of orderedErrors) { + const n = observedResponses[response] | 0; + if (response.startsWith("403:")) { + count403 += n; + } + } + const clientLogger = client?.config?.logger; + const warningLogger = typeof clientLogger?.warn === "function" && !clientLogger.constructor?.name?.includes?.("NoOpLogger") + ? clientLogger + : console; + if (count403 >= 3 || orderedErrors[orderedErrors.length - 1]?.startsWith("403:")) { + warningLogger.warn(`@smithy/util-waiter WARN - 403 status code encountered during waiter polling.`); + } +}; +const createMessageFromResponse = (reason) => { + const status = reason?.$response?.statusCode ?? reason?.$metadata?.httpStatusCode; + if (reason?.$responseBodyText) { + return `${status ? status + ": " : ""}Deserialization error for body: ${reason.$responseBodyText}`; + } + if (status) { + if (reason?.$response || reason?.message) { + return `${status ?? "Unknown"}: ${reason?.message}`; + } + return `${status}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason, getCircularReplacer()) ?? "Unknown"); +}; +const exponentialBackoffWithJitter = (minDelayMs, maxDelayMs, attempt, waitUntil) => { + const attemptCountCeiling = Math.log(maxDelayMs / minDelayMs) / Math.log(2) + 1; + if (attempt > attemptCountCeiling) { + return maxDelayMs; + } + const delay = minDelayMs * 2 ** (attempt - 1); + const capped = Math.min(delay, maxDelayMs); + const waitFor = randomInRange(minDelayMs, capped); + if (Date.now() + waitFor > waitUntil) { + const timeRemaining = waitUntil - Date.now(); + return Math.max(0, timeRemaining - 500); + } + return waitFor; +}; +const randomInRange = (min, max) => min + Math.random() * (max - min); + +const validateWaiterOptions = (options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } + else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } + else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } + else if (options.maxWaitTime <= options.minDelay) { + throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } + else if (options.maxDelay < options.minDelay) { + throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } +}; + +const abortTimeout = (abortSignal) => { + let onAbort; + const promise = new Promise((resolve) => { + onAbort = () => resolve({ state: WaiterState.ABORTED }); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + }); + return { + clearListener() { + if (typeof abortSignal.removeEventListener === "function") { + abortSignal.removeEventListener("abort", onAbort); + } + }, + aborted: promise, + }; +}; +const createWaiter = async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options, + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + const finalize = []; + if (options.abortSignal) { + const { aborted, clearListener } = abortTimeout(options.abortSignal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + if (options.abortController?.signal) { + const { aborted, clearListener } = abortTimeout(options.abortController.signal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + return Promise.race(exitConditions).then((result) => { + for (const fn of finalize) { + fn(); + } + return result; + }); +}; + +class Client { + config; + middlewareStack = constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + const { protocol, protocolSettings } = config; + if (protocolSettings) { + if (typeof protocol === "function") { + config.protocol = new protocol(protocolSettings); + } + } + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === undefined && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } + else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } + else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command) + .then((result) => callback(null, result.output), (err) => callback(err)) + .catch(() => { }); + } + else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } +} + +const SENSITIVE_STRING$1 = "***SensitiveInformation***"; +function schemaLogFilter(schema, data) { + if (data == null) { + return data; + } + const ns = NormalizedSchema.of(schema); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } + else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; +} + +class Command { + middlewareStack = constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const additionalSmithyContext = additionalContext[SMITHY_CONTEXT_KEY]; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + ...additionalContext, + [SMITHY_CONTEXT_KEY]: { + ...additionalSmithyContext, + commandInstance: this, + ...smithyContext, + ...(options?.metricsRecorder === undefined ? {} : { metricsRecorder: options.metricsRecorder }), + }, + }; + const { requestHandler } = configuration; + let requestOptions = options ?? {}; + if (requestOptions.metricsRecorder) { + requestOptions = { ...requestOptions }; + delete requestOptions.metricsRecorder; + } + if (smithyContext.eventStream) { + requestOptions = { + isEventStream: true, + ...requestOptions, + }; + } + return stack.resolve((request) => requestHandler.handle(request.request, requestOptions), handlerExecutionContext); + } +} +class ClassBuilder { + _init = () => { }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = undefined; + _outputFilterSensitiveLog = undefined; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext, + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return (CommandRef = class extends Command { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op = closure._operationSchema; + const input = op?.[4] ?? op?.input; + const output = op?.[5] ?? op?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext, + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }); + } +} + +const SENSITIVE_STRING = "***SensitiveInformation***"; + +const createAggregatedClient = (commands, Client, options) => { + for (const [command, CommandCtor] of Object.entries(commands)) { + const methodImpl = async function (args, optionsOrCb, cb) { + const command = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command, optionsOrCb); + } + else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command, optionsOrCb || {}, cb); + } + else { + return this.send(command, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client.prototype[methodName] = methodImpl; + } + const { paginators = {}, waiters = {} } = options ?? {}; + for (const [paginatorName, paginatorFn] of Object.entries(paginators)) { + if (Client.prototype[paginatorName] === void 0) { + Client.prototype[paginatorName] = function (commandInput = {}, paginationConfiguration, ...rest) { + return paginatorFn({ + ...paginationConfiguration, + client: this, + }, commandInput, ...rest); + }; + } + } + for (const [waiterName, waiterFn] of Object.entries(waiters)) { + if (Client.prototype[waiterName] === void 0) { + Client.prototype[waiterName] = async function (commandInput = {}, waiterConfiguration, ...rest) { + let config = waiterConfiguration; + if (typeof waiterConfiguration === "number") { + config = { + maxWaitTime: waiterConfiguration, + }; + } + return waiterFn({ + ...config, + client: this, + }, commandInput, ...rest); + }; + } + } +}; + +class ServiceException extends Error { + static shapeId = "smithy.ts.sdk.synthetic.nonamespace.client#ServiceException"; + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return (ServiceException.prototype.isPrototypeOf(candidate) || + (Boolean(candidate.$fault) && + Boolean(candidate.$metadata) && + (candidate.$fault === "client" || candidate.$fault === "server"))); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === ServiceException) { + return ServiceException.isInstance(instance); + } + if (ServiceException.isInstance(instance)) { + if (this.prototype.isPrototypeOf(instance)) { + return true; + } + const targetId = Object.prototype.hasOwnProperty.call(this, "shapeId") + ? this.shapeId + : undefined; + let candidateHasShapeId = false; + if (targetId) { + let proto = Object.getPrototypeOf(candidate); + while (proto && proto !== Object.prototype) { + const ctor = proto.constructor; + const candidateId = ctor !== ServiceException && Object.prototype.hasOwnProperty.call(ctor, "shapeId") + ? ctor?.shapeId + : undefined; + if (candidateId) { + candidateHasShapeId = true; + if (candidateId === targetId) { + return true; + } + } + proto = Object.getPrototypeOf(proto); + } + } + if (targetId && candidateHasShapeId) { + return false; + } + const targetName = this.name; + if (targetName && targetName.length >= 6) { + if (candidate.name === targetName) { + return true; + } + let proto = Object.getPrototypeOf(candidate); + while (proto && proto !== Object.prototype) { + const ctorName = proto.constructor?.name; + if (ctorName && ctorName !== "Error" && ctorName === targetName) { + return true; + } + proto = Object.getPrototypeOf(proto); + } + } + } + return false; + } +} +const decorateServiceException = (exception, additions = {}) => { + Object.entries(additions) + .filter(([, v]) => v !== undefined) + .forEach(([k, v]) => { + if (exception[k] == undefined || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}; + +const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata, + }); + throw decorateServiceException(response, parsedBody); +}; +const withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}; +const deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +const loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100, + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100, + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 30000, + }; + default: + return {}; + } +}; + +let warningEmitted = false; +const emitWarningIfUnsupportedVersion = (version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}; + +const knownAlgorithms = Object.values(AlgorithmId); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in AlgorithmId) { + if (!hasOwn(AlgorithmId, id)) + continue; + const algorithmId = AlgorithmId[id]; + if (runtimeConfig[algorithmId] === undefined) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId], + }); + } + for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) { + checksumAlgorithms.push({ + algorithmId: () => id, + checksumConstructor: () => ChecksumCtor, + }); + } + return { + addChecksumAlgorithm(algo) { + runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {}; + const id = algo.algorithmId(); + const ctor = algo.checksumConstructor(); + if (knownAlgorithms.includes(id)) { + runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor; + } + else { + runtimeConfig.checksumAlgorithms[id] = ctor; + } + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + const id = checksumAlgorithm.algorithmId(); + if (knownAlgorithms.includes(id)) { + runtimeConfig[id] = checksumAlgorithm.checksumConstructor(); + } + }); + return runtimeConfig; +}; + +const getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + }, + }; +}; +const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}; + +const getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}; +const getDefaultClientConfiguration = getDefaultExtensionConfiguration; +const resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}; + +const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + +const getValueFromTextNode = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (!hasOwn(obj, key)) + continue; + if (obj[key][textNodeName] !== undefined) { + obj[key] = obj[key][textNodeName]; + } + else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}; + +const isSerializableHeaderValue = (value) => { + return value != null; +}; + +class NoOpLogger { + trace() { } + debug() { } + info() { } + warn() { } + error() { } +} + +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } + else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } + else { + instructions = arg1; + } + } + for (const key in instructions) { + if (!hasOwn(instructions, key)) + continue; + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +const convertMap = (target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}; +const take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + if (!hasOwn(instructions, key)) + continue; + applyInstruction(out, source, instructions, key); + } + return out; +}; +const mapWithFilter = (target, filter, instructions) => { + return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } + else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } + else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); +}; +const applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === undefined && (_value = value()) != null; + const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed) { + target[targetKey] = _value; + } + else if (customFilterPassed) { + target[targetKey] = value(); + } + } + else { + const defaultFilterPassed = filter === undefined && value != null; + const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}; +const nonNullish = (_) => _ != null; +const pass = (_) => _; + +const serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}; +const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z"); + +const _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key in obj) { + if (!hasOwn(obj, key)) + continue; + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; +}; + +function makeBuilder(common, service, name, ep) { + return function makeCommand(added, plugins, op, $, smithyContext = {}) { + const epMerged = Object.assign({}, common, added); + return Command.classBuilder() + .ep(epMerged) + .m(function (CommandCtor, clientStack, config, options) { + const list = plugins.call(this, CommandCtor, clientStack, config, options); + list.unshift(ep(config, CommandCtor.getEndpointParameterInstructions())); + return list; + }) + .s(service, op, smithyContext) + .n(name, op.charAt(0).toUpperCase() + op.slice(1) + "Command") + .sc($) + .build(); + }; +} + +exports.Client = Client; +exports.Command = Command; +exports.NoOpLogger = NoOpLogger; +exports.SENSITIVE_STRING = SENSITIVE_STRING; +exports.ServiceException = ServiceException; +exports.WaiterState = WaiterState; +exports._json = _json; +exports.checkExceptions = checkExceptions; +exports.constructStack = constructStack; +exports.convertMap = convertMap; +exports.createAggregatedClient = createAggregatedClient; +exports.createWaiter = createWaiter; +exports.decorateServiceException = decorateServiceException; +exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; +exports.getArrayIfSingleItem = getArrayIfSingleItem; +exports.getChecksumConfiguration = getChecksumConfiguration; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; +exports.getRetryConfiguration = getRetryConfiguration; +exports.getValueFromTextNode = getValueFromTextNode; +exports.invalidFunction = invalidFunction; +exports.invalidProvider = invalidProvider; +exports.isSerializableHeaderValue = isSerializableHeaderValue; +exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; +exports.makeBuilder = makeBuilder; +exports.map = map; +exports.resolveChecksumRuntimeConfig = resolveChecksumRuntimeConfig; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; +exports.resolveRetryRuntimeConfig = resolveRetryRuntimeConfig; +exports.schemaLogFilter = schemaLogFilter; +exports.serializeDateTime = serializeDateTime; +exports.serializeFloat = serializeFloat; +exports.take = take; +exports.throwDefaultError = throwDefaultError; +exports.waiterServiceDefaults = waiterServiceDefaults; +exports.withBaseException = withBaseException; + + +/***/ }), + +/***/ 68702: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { homedir } = __webpack_require__(48161); +const { sep, join } = __webpack_require__(76760); +const { createHash } = __webpack_require__(77598); +const { readFile: readFile$1 } = __webpack_require__(51455); +const { IniSectionType } = __webpack_require__(88867); +const { normalizeProvider } = __webpack_require__(20895); +const { isValidHostLabel } = __webpack_require__(30673); + +class ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = undefined; + tryNextLink = options; + } + else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } +} + +class CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, CredentialsProviderError.prototype); + } +} + +class TokenProviderError extends ProviderError { + name = "TokenProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, TokenProviderError.prototype); + } +} + +const chain = (...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); + } + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } + catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +const fromValue = (staticValue) => () => Promise.resolve(staticValue); + +const memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } + finally { + pending = undefined; + } + return resolved; + }; + if (isExpired === undefined) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; +}; + +const booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}; + +const numberSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}; + +var SelectorType; +(function (SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; +})(SelectorType || (SelectorType = {})); + +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = homedir(); + return homeDirCache[homeDirCacheKey]; +}; + +const ENV_PROFILE = "AWS_PROFILE"; +const DEFAULT_PROFILE = "default"; +const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + +const getSSOTokenFilepath = (id) => { + const hasher = createHash("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return join(getHomeDir(), ".aws", "sso", "cache", `${cacheName}.json`); +}; + +const tokenIntercept = {}; +const getSSOTokenFromFile = async (id) => { + if (tokenIntercept[id]) { + return tokenIntercept[id]; + } + const ssoTokenFilepath = getSSOTokenFilepath(id); + const ssoTokenText = await readFile$1(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); +}; + +const CONFIG_PREFIX_SEPARATOR = "."; + +const getConfigData = (data) => Object.entries(data) + .filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator)); +}) + .reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; +}, { + ...(data.default && { default: data.default }), +}); + +const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || join(getHomeDir(), ".aws", "config"); + +const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || join(getHomeDir(), ".aws", "credentials"); + +const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/; +const profileNameBlockList = ["__proto__", "profile __proto__"]; +const parseIni = (iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = undefined; + currentSubSection = undefined; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } + else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } + else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim(), + ]; + if (value === "") { + currentSubSection = name; + } + else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = undefined; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } + } + } + return map; +}; + +const filePromises = {}; +const fileIntercept = {}; +const readFile = (path, options) => { + if (fileIntercept[path] !== undefined) { + return fileIntercept[path]; + } + if (!filePromises[path] || options?.ignoreCache) { + filePromises[path] = readFile$1(path, "utf8"); + } + return filePromises[path]; +}; + +const swallowError$1 = () => ({}); +const loadSharedConfigFiles = async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = join(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = join(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + readFile(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .then(getConfigData) + .catch(swallowError$1), + readFile(resolvedFilepath, { + ignoreCache: init.ignoreCache, + }) + .then(parseIni) + .catch(swallowError$1), + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1], + }; +}; + +const getSsoSessionData = (data) => Object.entries(data) + .filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) + .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + +const swallowError = () => ({}); +const loadSsoSessionData = async (init = {}) => readFile(init.configFilepath ?? getConfigFilepath()) + .then(parseIni) + .then(getSsoSessionData) + .catch(swallowError); + +const mergeConfigFiles = (...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== undefined) { + Object.assign(merged[key], values); + } + else { + merged[key] = values; + } + } + } + return merged; +}; + +const parseKnownFiles = async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}; + +const externalDataInterceptor = { + getFileRecord() { + return fileIntercept; + }, + interceptFile(path, contents) { + fileIntercept[path] = Promise.resolve(contents); + }, + getTokenRecord() { + return tokenIntercept; + }, + interceptToken(id, contents) { + tokenIntercept[id] = contents; + }, +}; + +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } + catch (ignored) { + return functionString; + } +} + +const fromEnv = (envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === undefined) { + throw new Error(); + } + return config; + } + catch (e) { + throw new CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); + } +}; + +const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = getProfileName(init); + const { configFile, credentialsFile } = await loadSharedConfigFiles(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" + ? { ...profileFromCredentials, ...profileFromConfig } + : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === undefined) { + throw new Error(); + } + return configValue; + } + catch (e) { + throw new CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); + } +}; + +const isFunction = (func) => typeof func === "function"; +const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : fromValue(defaultValue); + +const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); +}; + +const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +const DEFAULT_USE_DUALSTACK_ENDPOINT = false; +const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG), + default: false, +}; +const nodeDualstackConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG), + default: undefined, +}; + +const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +const DEFAULT_USE_FIPS_ENDPOINT = false; +const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG), + default: false, +}; +const nodeFipsConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG), + default: undefined, +}; + +const resolveCustomEndpointsConfig = (input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), + }); +}; + +const getEndpointFromRegion = async (input) => { + const { tls = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}; + +const resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint + ? normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) + : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint, + }); +}; + +const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +const AWS_REGION_ENV = "AWS_REGION"; +const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +const DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +const IMDS_REGION_PATH = "/latest/meta-data/placement/region"; +const IMDS_TOKEN_PATH = "/latest/api/token"; +const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +const X_AWS_EC2_METADATA_TOKEN_TTL = "x-aws-ec2-metadata-token-ttl-seconds"; + +const TIMEOUT_MS = 1000; +const NEG_CACHE_TTL_MS = 60_000; +let negativeCacheUntil = 0; +const getInstanceMetadataRegion = async () => { + if (process.env[ENV_IMDS_DISABLED]) { + return undefined; + } + if (Date.now() < negativeCacheUntil) { + return undefined; + } + try { + const endpoint = resolveImdsEndpoint(); + const token = (await imdsRequest({ + ...endpoint, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + [X_AWS_EC2_METADATA_TOKEN_TTL]: "21600", + }, + })).toString(); + const region = (await imdsRequest({ + ...endpoint, + path: IMDS_REGION_PATH, + method: "GET", + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token, + }, + })) + .toString() + .trim(); + return region || cacheNegativeAndReturnUndefined(); + } + catch { + return cacheNegativeAndReturnUndefined(); + } +}; +const cacheNegativeAndReturnUndefined = () => { + negativeCacheUntil = Date.now() + NEG_CACHE_TTL_MS; + return undefined; +}; +const resolveImdsEndpoint = () => { + const envEndpoint = process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT; + if (envEndpoint) { + const url = new URL(envEndpoint); + return { + hostname: url.hostname.replace(/^\[(.+)]$/, "$1"), + port: url.port ? Number(url.port) : undefined, + }; + } + if (process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE === "IPv6") { + return { hostname: "fd00:ec2::254" }; + } + return { hostname: "169.254.169.254" }; +}; +const imdsRequest = async (options) => { + const { request } = __webpack_require__(37067); + return new Promise((resolve, reject) => { + const req = request({ + hostname: options.hostname, + port: options.port, + path: options.path, + method: options.method, + headers: options.headers, + timeout: TIMEOUT_MS, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + req.on("error", (err) => { + reject(err); + req.destroy(); + }); + req.on("timeout", () => { + reject(new Error("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || statusCode >= 300) { + reject(Object.assign(new Error("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + return; + } + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + resolve(Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); +}; + +const REGION_ENV_NAME = "AWS_REGION"; +const REGION_INI_NAME = "region"; +const NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: async () => { + const region = await getInstanceMetadataRegion(); + if (region) { + return region; + } + throw new Error("Region is missing"); + }, +}; +const NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials", +}; + +const validRegions = new Set(); +const checkRegion = (region, check = isValidHostLabel) => { + if (!validRegions.has(region) && !check(region)) { + if (region === "*") { + console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); + } + else { + throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); + } + } + else { + validRegions.add(region); + } +}; + +const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); + +const getRealRegion = (region) => isFipsRegion(region) + ? ["fips-aws-global", "aws-fips"].includes(region) + ? "us-east-1" + : region.replace(/fips-(dkr-|prod-)?|-fips/, "") + : region; + +const resolveRegionConfig = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: async () => { + const providedRegion = typeof region === "function" ? await region() : region; + const realRegion = getRealRegion(providedRegion); + checkRegion(realRegion); + return realRegion; + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, + }); +}; + +const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; + +const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname + ? regionHostname + : partitionHostname + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; + +const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; + +const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; + } + else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } + } +}; + +const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : (partitionHash[partition]?.endpoint ?? region); + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === undefined) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + } + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint, + }); + return { + partition, + signingService, + hostname, + ...(signingRegion && { signingRegion }), + ...(regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService, + }), + }; +}; + +const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy", +}; + +const resolveDefaultsModeConfig = ({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case undefined: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); + } +}); +const resolveNodeDefaultsModeAuto = async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } + else { + return "cross-region"; + } + } + return "standard"; +}; +const inferPhysicalRegion = async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + return getInstanceMetadataRegion(); +}; + +exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; +exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; +exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; +exports.CredentialsProviderError = CredentialsProviderError; +exports.DEFAULT_PROFILE = DEFAULT_PROFILE; +exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; +exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; +exports.ENV_PROFILE = ENV_PROFILE; +exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; +exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; +exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; +exports.ProviderError = ProviderError; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.SelectorType = SelectorType; +exports.TokenProviderError = TokenProviderError; +exports.booleanSelector = booleanSelector; +exports.chain = chain; +exports.externalDataInterceptor = externalDataInterceptor; +exports.fromStatic = fromStatic; +exports.fromValue = fromValue; +exports.getHomeDir = getHomeDir; +exports.getProfileName = getProfileName; +exports.getRegionInfo = getRegionInfo; +exports.getSSOTokenFilepath = getSSOTokenFilepath; +exports.getSSOTokenFromFile = getSSOTokenFromFile; +exports.loadConfig = loadConfig; +exports.loadSharedConfigFiles = loadSharedConfigFiles; +exports.loadSsoSessionData = loadSsoSessionData; +exports.memoize = memoize; +exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors; +exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors; +exports.numberSelector = numberSelector; +exports.parseKnownFiles = parseKnownFiles; +exports.readFile = readFile; +exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; +exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; +exports.resolveEndpointsConfig = resolveEndpointsConfig; +exports.resolveRegionConfig = resolveRegionConfig; + + +/***/ }), + +/***/ 93846: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { CONFIG_PREFIX_SEPARATOR, booleanSelector, SelectorType, loadConfig } = __webpack_require__(68702); +const { toEndpointV1, getSmithyContext, normalizeProvider, isValidHostLabel, hasOwn } = __webpack_require__(30673); +exports.isValidHostLabel = isValidHostLabel; +exports.middlewareEndpointToEndpointV1 = toEndpointV1; +exports.toEndpointV1 = toEndpointV1; +const { EndpointURLScheme } = __webpack_require__(88867); + +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + configFileSelector: (profile, config) => { + if (profile.services) { + const servicesSectionKey = ["services", profile.services].join(CONFIG_PREFIX_SEPARATOR); + if (!config || !config[servicesSectionKey]) { + throw new Error(`The services section "${profile.services}" specified in the profile is not present in the shared configuration file.`); + } + const servicesSection = config[servicesSectionKey]; + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); + +const ENV_IGNORE_CONFIGURED_ENDPOINT_URLS = "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS"; +const CONFIG_IGNORE_CONFIGURED_ENDPOINT_URLS = "ignore_configured_endpoint_urls"; +const ignoreConfiguredEndpointUrlsConfigSelectors = { + environmentVariableSelector: (env) => booleanSelector(env, ENV_IGNORE_CONFIGURED_ENDPOINT_URLS, SelectorType.ENV), + configFileSelector: (profile) => booleanSelector(profile, CONFIG_IGNORE_CONFIGURED_ENDPOINT_URLS, SelectorType.CONFIG), + default: false, +}; + +const getEndpointFromConfig = async (serviceId) => { + const ignore = await loadConfig(ignoreConfiguredEndpointUrlsConfigSelectors)(); + if (ignore) { + return undefined; + } + return loadConfig(getEndpointUrlConfig(serviceId ?? ""))(); +}; + +const resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } + else if (!isDnsCompatibleBucketName(bucket) || + (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || + bucket.toLowerCase() !== bucket || + bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}; +const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/; +const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +const DOTS_PATTERN = /\.\./; +const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); +const isArnBucketName = (bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}; + +const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config, isClientContextParam = false) => { + const configProvider = async () => { + let configValue; + if (isClientContextParam) { + const clientContextParams = config.clientContextParams; + const nestedValue = clientContextParams?.[configKey]; + configValue = nestedValue ?? config[configKey] ?? config[canonicalEndpointParamKey]; + } + else { + configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + } + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return undefined; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}; + +function bindGetEndpointFromInstructions(getEndpointFromConfig) { + return async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint && !clientConfig.ignoreConfiguredEndpointUrls) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } + else { + endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + context?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${endpointFromConfig}`); + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + if (clientConfig.isCustomEndpoint && clientConfig.endpoint) { + const customEndpoint = await clientConfig.endpoint(); + if (customEndpoint?.headers) { + endpoint.headers ??= {}; + for (const [name, value] of Object.entries(customEndpoint.headers)) { + endpoint.headers[name] = Array.isArray(value) ? value : [value]; + } + } + } + return endpoint; + }; +} +const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== "builtInParams")(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}; + +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { features: {} }; + } + else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +function bindEndpointMiddleware(getEndpointFromConfig) { + const getEndpointFromInstructions = bindGetEndpointFromInstructions(getEndpointFromConfig); + return ({ config, instructions, }) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + setFeature(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + }, + }, { ...config }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet, + }, authScheme.properties); + } + } + return next({ + ...args, + }); + }; + }; +} + +const serializerMiddlewareOption = { + name: "serializerMiddleware"}; +const endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: serializerMiddlewareOption.name, +}; +function bindGetEndpointPlugin(getEndpointFromConfig) { + const endpointMiddleware = bindEndpointMiddleware(getEndpointFromConfig); + return (config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config, + instructions, + }), endpointMiddlewareOptions); + }, + }); +} + +function bindResolveEndpointConfig(getEndpointFromConfig) { + return (input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : undefined; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false), + ignoreConfiguredEndpointUrls: !!input.ignoreConfiguredEndpointUrls, + }); + let configuredEndpointPromise = undefined; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; + }; +} + +class BinaryDecisionDiagram { + nodes; + root; + conditions; + results; + constructor(bdd, root, conditions, results) { + this.nodes = bdd; + this.root = root; + this.conditions = conditions; + this.results = results; + } + static from(bdd, root, conditions, results) { + return new BinaryDecisionDiagram(bdd, root, conditions, results); + } +} + +class EndpointCache { + capacity; + data = new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } + } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const raw = endpointParams[param]; + const val = raw == null ? "\0" : String(raw); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; + } +} + +class EndpointError extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; + } +} + +const debugId = "endpoints"; + +function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); +} + +const customEndpointFunctions = {}; + +const booleanEquals = (value1, value2) => value1 === value2; + +function coalesce(...args) { + for (const arg of args) { + if (arg != null) { + return arg; + } + } + return undefined; +} + +const getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } + else { + pathList.push(part); + } + } + return pathList; +}; + +const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } + else if (Array.isArray(acc)) { + const i = parseInt(index); + return acc[i < 0 ? acc.length + i : i]; + } + return acc[index]; +}, value); + +const isSet = (value) => value != null; + +function ite(condition, trueValue, falseValue) { + return condition ? trueValue : falseValue; +} + +const not = (value) => !value; + +const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); +const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); + +const DEFAULT_PORTS = { + [EndpointURLScheme.HTTP]: 80, + [EndpointURLScheme.HTTPS]: 443, +}; +const parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname, port, protocol = "", path = "", query = {} } = value; + const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query) + .map(([k, v]) => `${k}=${v}`) + .join("&"); + return url; + } + return new URL(value); + } + catch (ignored) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || + (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp, + }; +}; + +function split(value, delimiter, limit) { + if (limit === 1) { + return [value]; + } + if (value === "") { + return [""]; + } + const parts = value.split(delimiter); + if (limit === 0) { + return parts; + } + return parts.slice(0, limit - 1).concat(parts.slice(1).join(delimiter)); +} + +const stringEquals = (value1, value2) => value1 === value2; + +const substring = (input, start, stop, reverse) => { + if (input == null || start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); +}; + +const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + +const endpointFunctions = { + booleanEquals, + coalesce, + getAttr, + isSet, + isValidHostLabel, + ite, + not, + parseURL, + split, + stringEquals, + substring, + uriEncode, +}; + +const evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const { referenceRecord, endpointParams } = options; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr((referenceRecord[refName] ?? endpointParams[refName]), attrName)); + } + else { + evaluatedTemplateArr.push((referenceRecord[parameterName] ?? endpointParams[parameterName])); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); +}; + +const getReferenceValue = ({ ref }, options) => { + return options.referenceRecord[ref] ?? options.endpointParams[ref]; +}; + +const evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } + else if (obj["fn"]) { + return group$2.callFunction(obj, options); + } + else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}; +const callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = Array(argv.length); + for (let i = 0; i < evaluatedArgs.length; ++i) { + const arg = argv[i]; + if (typeof arg === "boolean" || typeof arg === "number") { + evaluatedArgs[i] = arg; + } + else { + evaluatedArgs[i] = group$2.evaluateExpression(arg, "arg", options); + } + } + const namespaceSeparatorIndex = fn.indexOf("."); + if (namespaceSeparatorIndex !== -1) { + const namespaceFunctions = customEndpointFunctions[fn.slice(0, namespaceSeparatorIndex)]; + const customFunction = namespaceFunctions?.[fn.slice(namespaceSeparatorIndex + 1)]; + if (typeof customFunction === "function") { + return customFunction(...evaluatedArgs); + } + } + const callable = endpointFunctions[fn]; + if (typeof callable === "function") { + return callable(...evaluatedArgs); + } + throw new Error(`function ${fn} not loaded in endpointFunctions.`); +}; +const group$2 = { + evaluateExpression, + callFunction, +}; + +const evaluateCondition = (condition, options) => { + const { assign } = condition; + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(condition, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(condition)} = ${toDebugString(value)}`); + const result = value === "" ? true : !!value; + if (assign != null) { + return { result, toAssign: { name: assign, value } }; + } + return { result }; +}; + +const getEndpointHeaders = (headers, options) => Object.entries(headers ?? {}).reduce((acc, [headerKey, headerVal]) => { + acc[headerKey] = headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }); + return acc; +}, {}); + +const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => { + acc[propertyKey] = group$1.getEndpointProperty(propertyVal, options); + return acc; +}, {}); +const getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return group$1.getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}; +const group$1 = { + getEndpointProperty, + getEndpointProperties, +}; + +const getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } + catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}; + +const RESULT = 100_000_000; +const decideEndpoint = (bdd, options) => { + const { nodes, root, results, conditions } = bdd; + let ref = root; + const referenceRecord = {}; + const closure = { + referenceRecord, + endpointParams: options.endpointParams, + logger: options.logger, + }; + while (ref !== 1 && ref !== -1 && ref < RESULT) { + const node_i = 3 * (Math.abs(ref) - 1); + const [condition_i, highRef, lowRef] = [nodes[node_i], nodes[node_i + 1], nodes[node_i + 2]]; + const [fn, argv, assign] = conditions[condition_i]; + const evaluation = evaluateCondition({ fn, assign, argv }, closure); + if (evaluation.toAssign) { + const { name, value } = evaluation.toAssign; + referenceRecord[name] = value; + } + ref = ref >= 0 === evaluation.result ? highRef : lowRef; + } + if (ref >= RESULT) { + const result = results[ref - RESULT]; + if (result[0] === -1) { + const [, errorExpression] = result; + throw new EndpointError(evaluateExpression(errorExpression, "Error", closure)); + } + const [url, properties, headers] = result; + return { + url: getEndpointUrl(url, closure), + properties: getEndpointProperties(properties, closure), + headers: getEndpointHeaders(headers ?? {}, closure), + }; + } + throw new EndpointError(`No matching endpoint.`); +}; + +const evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + const conditionOptions = { + ...options, + referenceRecord: { ...options.referenceRecord }, + }; + let didAssign = false; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, conditionOptions); + if (!result) { + return { result }; + } + if (toAssign) { + didAssign = true; + conditionsReferenceRecord[toAssign.name] = toAssign.value; + conditionOptions.referenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + if (didAssign) { + return { result: true, referenceRecord: conditionsReferenceRecord }; + } + return { result: true }; +}; + +const evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = referenceRecord + ? { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + } + : options; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + const endpointToReturn = { url: getEndpointUrl(url, endpointRuleOptions) }; + if (headers != null) { + endpointToReturn.headers = getEndpointHeaders(headers, endpointRuleOptions); + } + if (properties != null) { + endpointToReturn.properties = getEndpointProperties(properties, endpointRuleOptions); + } + return endpointToReturn; +}; + +const evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const errorRuleOptions = referenceRecord + ? { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + } + : options; + throw new EndpointError(evaluateExpression(error, "Error", errorRuleOptions)); +}; + +const evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } + else if (rule.type === "tree") { + const endpointOrUndefined = group.evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); +}; +const evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const treeRuleOptions = referenceRecord + ? { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } } + : options; + return group.evaluateRules(rules, treeRuleOptions); +}; +const group = { + evaluateRules, + evaluateTreeRule, +}; + +const resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + for (const paramKey in parameters) { + if (!hasOwn(parameters, paramKey)) + continue; + const parameter = parameters[paramKey]; + const endpointParam = endpointParams[paramKey]; + if (endpointParam == null && parameter.default != null) { + endpointParams[paramKey] = parameter.default; + continue; + } + if (parameter.required && endpointParam == null) { + throw new EndpointError(`Missing required parameter: '${paramKey}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}; + +const resolveEndpointRequiredConfig = (input) => { + const { endpoint } = input; + if (endpoint === undefined) { + input.endpoint = async () => { + throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); + }; + } + return input; +}; + +const getEndpointFromInstructions = bindGetEndpointFromInstructions(getEndpointFromConfig); +const resolveEndpointConfig = bindResolveEndpointConfig(getEndpointFromConfig); +const endpointMiddleware = bindEndpointMiddleware(getEndpointFromConfig); +const getEndpointPlugin = bindGetEndpointPlugin(getEndpointFromConfig); + +exports.BinaryDecisionDiagram = BinaryDecisionDiagram; +exports.EndpointCache = EndpointCache; +exports.EndpointError = EndpointError; +exports.customEndpointFunctions = customEndpointFunctions; +exports.decideEndpoint = decideEndpoint; +exports.endpointMiddleware = endpointMiddleware; +exports.endpointMiddlewareOptions = endpointMiddlewareOptions; +exports.getEndpointFromInstructions = getEndpointFromInstructions; +exports.getEndpointPlugin = getEndpointPlugin; +exports.isIpAddress = isIpAddress; +exports.resolveEndpoint = resolveEndpoint; +exports.resolveEndpointConfig = resolveEndpointConfig; +exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; +exports.resolveParams = resolveParams; + + +/***/ }), + +/***/ 41120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Crc32 } = __webpack_require__(95899); +const { hasOwn } = __webpack_require__(30673); +const { toHex, fromHex, toUtf8, fromUtf8 } = __webpack_require__(34129); +const { Readable } = __webpack_require__(57075); +const { TypeRegistry } = __webpack_require__(39875); + +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +class HeaderMarshaller { + toUtf8; + fromUtf8; + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + format(headers) { + const chunks = []; + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex(header.value.replace(/-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true, + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false, + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++), + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false), + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false), + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)), + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength), + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)), + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()), + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${toHex(uuidBytes.subarray(0, 4))}-${toHex(uuidBytes.subarray(4, 6))}-${toHex(uuidBytes.subarray(6, 8))}-${toHex(uuidBytes.subarray(8, 10))}-${toHex(uuidBytes.subarray(10))}`, + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } +} +var HEADER_VALUE_TYPE; +(function (HEADER_VALUE_TYPE) { + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"] = 3] = "short"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"] = 5] = "long"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"] = 7] = "string"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"] = 9] = "uuid"; +})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); +const BOOLEAN_TAG = "boolean"; +const BYTE_TAG = "byte"; +const SHORT_TAG = "short"; +const INT_TAG = "integer"; +const LONG_TAG = "long"; +const BINARY_TAG = "binary"; +const STRING_TAG = "string"; +const TIMESTAMP_TAG = "timestamp"; +const UUID_TAG = "uuid"; +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +const PRELUDE_MEMBER_LENGTH = 4; +const PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +const CHECKSUM_LENGTH = 4; +const MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new Crc32(); + checksummer.update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digestSync()) { + throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digestSync()})`); + } + checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); + if (expectedMessageChecksum !== checksummer.digestSync()) { + throw new Error(`The message checksum (${checksummer.digestSync()}) did not match the expected value of ${expectedMessageChecksum}`); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)), + }; +} + +class EventStreamCodec { + headerMarshaller; + messageBuffer; + isEndOfStream; + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + }, + }; + } + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + checksum.update(out.subarray(0, 8)); + view.setUint32(8, checksum.digestSync(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + checksum.update(out.subarray(8, length - 4)); + view.setUint32(length - 4, checksum.digestSync(), false); + return out; + } + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +} + +class MessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } +} + +class MessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } +} + +class SmithyMessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === undefined) + continue; + yield deserialized; + } + } +} + +class SmithyMessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } +} + +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } + else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } + else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator, + }; +} + +function getUnmarshalledStream(source, options) { + const messageUnmarshaller = getMessageUnmarshaller(options.deserializer, options.toUtf8); + return { + [Symbol.asyncIterator]: async function* () { + for await (const chunk of source) { + const message = options.eventStreamCodec.decode(chunk); + const type = await messageUnmarshaller(message); + if (type === undefined) + continue; + yield type; + } + }, + }; +} +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function (message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } + else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } + else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message, + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } + else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} + +let EventStreamMarshaller$1 = class EventStreamMarshaller { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new SmithyMessageDecoderStream({ + messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder), + }); + } + serialize(inputStream, serializer) { + return new MessageEncoderStream({ + messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true, + }); + } +}; +const eventStreamSerdeProvider$1 = (options) => new EventStreamMarshaller$1(options); + +class EventStreamMarshaller { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new EventStreamMarshaller$1({ + utf8Decoder, + utf8Encoder, + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readableToIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +} +const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); +async function* readableToIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } +} + +const readableStreamToIterable = (readableStream) => ({ + [Symbol.asyncIterator]: async function* () { + const reader = readableStream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) + return; + yield value; + } + } + finally { + reader.releaseLock(); + } + }, +}); +const iterableToReadableStream = (asyncIterable) => { + const iterator = asyncIterable[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const { done, value } = await iterator.next(); + if (done) { + return controller.close(); + } + controller.enqueue(value); + }, + }); +}; + +const resolveEventStreamSerdeConfig = (input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input), +}); + +class EventStreamSerde { + marshaller; + serializer; + deserializer; + serdeContext; + defaultContentType; + compositeErrorRegistry; + constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, compositeErrorRegistry, }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + this.compositeErrorRegistry = compositeErrorRegistry; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, initialMessageType, }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: initialMessageType ?? "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType }, + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body, + }; + } + for await (const page of eventStream) { + yield page; + } + }, + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body, + }; + } + let unionMember = ""; + for (const key in event) { + if (!hasOwn(event, key)) + continue; + if (key !== "__type") { + unionMember = key; + break; + } + } + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders, + }; + return { + headers, + body, + }; + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, initialMessageType, }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + let unionMember = ""; + for (const key in event) { + if (!hasOwn(event, key)) + continue; + if (key !== "__type") { + unionMember = key; + break; + } + } + const body = event[unionMember].body; + if (unionMember === (initialMessageType ?? "initial-response")) { + const dataObject = await this.deserializer.read(responseSchema, body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject, + }; + } + else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + if (eventStreamSchema.isStructSchema()) { + const out = {}; + let hasBindings = false; + for (const [name, member] of eventStreamSchema.structIterator()) { + const { eventHeader, eventPayload } = member.getMergedTraits(); + hasBindings = hasBindings || Boolean(eventHeader || eventPayload); + if (eventPayload) { + if (member.isBlobSchema()) { + out[name] = body; + } + else if (member.isStringSchema()) { + out[name] = (this.serdeContext?.utf8Encoder ?? toUtf8)(body); + } + else if (member.isStructSchema()) { + out[name] = await this.deserializer.read(member, body); + } + } + else if (eventHeader) { + const value = event[unionMember].headers[name]?.value; + if (value != null) { + if (member.isNumericSchema()) { + if (value && typeof value === "object" && "bytes" in value) { + out[name] = BigInt(value.toString()); + } + else { + out[name] = Number(value); + } + } + else { + out[name] = value; + } + } + } + } + return { + [unionMember]: await this.readEventMember(eventStreamSchema, body, hasBindings, out), + }; + } + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, body), + }; + } + else { + return { + $unknown: event, + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; + } + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); + } + for (const key in firstEvent.value) { + if (!hasOwn(firstEvent.value, key)) + continue; + initialResponseContainer[key] = firstEvent.value[key]; + } + } + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + }, + }; + } + async readEventMember(eventStreamSchema, body, hasBindings, out) { + let ErrCtor; + const staticStructuralSchema = eventStreamSchema.getSchema(); + if (Array.isArray(staticStructuralSchema) && staticStructuralSchema[0] === -3) { + const namespace = staticStructuralSchema[1]; + const nsRegistry = TypeRegistry.for(namespace); + this.compositeErrorRegistry?.copyFrom(nsRegistry); + ErrCtor = (this.compositeErrorRegistry ?? nsRegistry)?.getErrorCtor(staticStructuralSchema); + } + const dataObject = hasBindings + ? out + : body.byteLength === 0 + ? {} + : await this.deserializer.read(eventStreamSchema, body); + if (ErrCtor) { + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const metadata = {}; + const $fault = eventStreamSchema.getMergedTraits().error; + if ($fault) { + metadata.$fault = $fault; + } + return Object.assign(new ErrCtor({}), metadata, { + message, + }, dataObject); + } + return dataObject; + } + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = (() => { + const struct = unionSchema.getSchema(); + return struct[4].includes(unionMember); + })(); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(15, value); + } + else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + } + else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } + else { + type = "long"; + } + } + else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } + else if (memberSchema.isStringSchema()) { + type = "string"; + } + else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value, + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } + else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } + else { + serializer.write(eventSchema, event[unionMember]); + } + } + else if (eventSchema.isUnitSchema()) { + serializer.write(eventSchema, {}); + } + else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush() ?? new Uint8Array(); + const body = typeof messageSerialization === "string" + ? (this.serdeContext?.utf8Decoder ?? fromUtf8)(messageSerialization) + : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders, + }; + } +} + +exports.EventStreamCodec = EventStreamCodec; +exports.EventStreamMarshaller = EventStreamMarshaller; +exports.EventStreamSerde = EventStreamSerde; +exports.HeaderMarshaller = HeaderMarshaller; +exports.Int64 = Int64; +exports.MessageDecoderStream = MessageDecoderStream; +exports.MessageEncoderStream = MessageEncoderStream; +exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; +exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; +exports.UniversalEventStreamMarshaller = EventStreamMarshaller$1; +exports.eventStreamSerdeProvider = eventStreamSerdeProvider; +exports.getChunkedStream = getChunkedStream; +exports.getMessageUnmarshaller = getMessageUnmarshaller; +exports.getUnmarshalledStream = getUnmarshalledStream; +exports.iterableToReadableStream = iterableToReadableStream; +exports.readableStreamToIterable = readableStreamToIterable; +exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; +exports.universalEventStreamSerdeProvider = eventStreamSerdeProvider$1; + + +/***/ }), + +/***/ 62049: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Uint8ArrayBlobAdapter, sdkStreamMixin, splitEvery, splitHeader, fromBase64, _parseEpochTimestamp, _parseRfc7231DateTime, _parseRfc3339DateTimeWithOffset, LazyJsonString, NumericValue, toUtf8, fromUtf8, generateIdempotencyToken, toBase64, dateToUtcString, quoteHeader, parseEpochTimestamp, parseRfc7231DateTime, parseRfc3339DateTimeWithOffset } = __webpack_require__(34129); +const { HttpRequest, HttpResponse, hasOwn, isValidHostname, getSmithyContext } = __webpack_require__(30673); +const { parseQueryString, parseUrl } = __webpack_require__(30673); +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.isValidHostname = isValidHostname; +exports.parseQueryString = parseQueryString; +exports.parseUrl = parseUrl; +const { TypeRegistry, NormalizedSchema, translateTraits, deref } = __webpack_require__(39875); +const { FieldPosition } = __webpack_require__(88867); + +const collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return Uint8ArrayBlobAdapter.mutate(await fromContext); +}; + +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +class SerdeContext { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class HttpProtocol extends SerdeContext { + options; + compositeErrorRegistry; + constructor(options) { + super(); + this.options = options; + this.compositeErrorRegistry = new TypeRegistry(options.defaultNamespace); + for (const etr of options.errorTypeRegistries ?? []) { + this.compositeErrorRegistry.copyFrom(etr); + } + } + getRequestType() { + return HttpRequest; + } + getResponseType() { + return HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + if (!request.query) { + request.query = {}; + } + for (const [k, v] of endpoint.url.searchParams.entries()) { + request.query[k] = v; + } + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + request.headers[name] = endpoint.headers[name].join(", "); + } + } + return request; + } + else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : undefined; + request.path = endpoint.path; + request.query = { + ...endpoint.query, + }; + if (endpoint.headers) { + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + request.headers[name] = endpoint.headers[name]; + } + } + return request; + } + } + setHostPrefix(request, operationSchema, input) { + if (this.serdeContext?.disableHostPrefix) { + return; + } + const inputNs = NormalizedSchema.of(operationSchema.input); + const opTraits = translateTraits(operationSchema.traits ?? {}); + if (opTraits.endpoint) { + let hostPrefix = opTraits.endpoint?.[0]; + if (typeof hostPrefix === "string") { + for (const [name, member] of inputNs.structIterator()) { + if (!member.getMergedTraits().hostLabel) { + continue; + } + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + if (!isValidHostname(request.hostname)) { + throw new Error(`[${request.hostname}] is not a valid hostname.`); + } + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], + }; + } + resolveError(name, namespaces, registries) { + const defaultErrorSchema = [-3, "", "Error", 0, [], [], 0]; + let schema; + for (const registry of registries) { + for (const ns of namespaces) { + try { + if (ns === "*") { + schema = registry.getSchema(name); + } + else { + schema = registry.getSchema(ns + "#" + name); + } + const errorCtor = registry.getErrorCtor(schema); + if (errorCtor) { + return [schema, errorCtor, "modeled"]; + } + else { + const syntheticErrorSchema = registry.getBaseException(); + if (syntheticErrorSchema) { + const syntheticErrorCtor = registry.getErrorCtor(syntheticErrorSchema); + if (syntheticErrorCtor) { + return [schema, syntheticErrorCtor, "synthetic"]; + } + } + } + } + catch (ignored) { + } + } + } + for (const registry of registries) { + const syntheticErrorSchema = registry.getBaseException(); + if (syntheticErrorSchema) { + const syntheticErrorCtor = registry.getErrorCtor(syntheticErrorSchema); + if (syntheticErrorCtor) { + return [syntheticErrorSchema, syntheticErrorCtor, "synthetic"]; + } + } + } + return [defaultErrorSchema, Error, "native"]; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest, + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer, + }); + } + async loadEventStreamCapability() { + const { EventStreamSerde, eventStreamSerdeProvider } = __webpack_require__(41120); + const marshaller = this.resolveEventStreamMarshaller(eventStreamSerdeProvider); + return new EventStreamSerde({ + marshaller, + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType(), + compositeErrorRegistry: this.compositeErrorRegistry, + }); + } + getDefaultContentType() { + throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } + resolveEventStreamMarshaller(importedProvider) { + const context = this.serdeContext; + if (context.eventStreamMarshaller) { + return context.eventStreamMarshaller; + } + return importedProvider(this.serdeContext); + } +} + +class HttpBindingProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = _input && typeof _input === "object" ? _input : {}; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const payloadMemberNames = []; + const payloadMemberSchemas = []; + let hasNonHttpBindingMember = false; + let payload; + const request = new HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } + else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + for (const [key, value] of traitSearchParams) { + query[key] = value; + } + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { + if (memberTraits.httpLabel) { + if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) { + throw new Error(`No value provided for input HTTP label: ${memberName}.`); + } + } + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns, + }); + } + } + else { + payload = inputMemberValue; + } + } + else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + } + else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); + } + else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + } + else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + } + else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const key in inputMemberValue) { + if (!hasOwn(inputMemberValue, key)) + continue; + const val = inputMemberValue[key]; + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + } + else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + } + else { + hasNonHttpBindingMember = true; + payloadMemberNames.push(memberName); + payloadMemberSchemas.push(memberNs); + } + } + if (hasNonHttpBindingMember && input) { + const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#"); + const requiredMembers = ns.getSchema()[6]; + const payloadSchema = [ + 3, + namespace, + name, + ns.getMergedTraits(), + payloadMemberNames, + payloadMemberSchemas, + undefined, + ]; + if (requiredMembers) { + payloadSchema[6] = requiredMembers; + } + else { + payloadSchema.pop(); + } + serializer.write(payloadSchema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const key in data) { + if (!hasOwn(data, key)) + continue; + if (!(key in query)) { + const val = data[key]; + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + ...traits, + httpQuery: key, + httpQueryParams: undefined, + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== undefined) { + buffer.push(serializable); + } + } + query[traits.httpQuery] = buffer; + } + else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + if (dataFromBody[member] != null) { + dataObject[member] = dataFromBody[member]; + } + } + } + } + else if (nonHttpBindingMembers.discardResponseBody) { + await collectBody(response.body, context); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } + else { + dataObject = arg4; + } + let discardResponseBody = true; + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + discardResponseBody = false; + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns, + }); + } + else { + dataObject[memberName] = sdkStreamMixin(response.body); + } + } + else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } + else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && + headerListValueSchema.getSchema() === 4) { + sections = splitEvery(value, ",", 2); + } + else { + sections = splitHeader(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list; + } + else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } + else if (memberTraits.httpPrefixHeaders !== undefined) { + dataObject[memberName] = {}; + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const value = response.headers[header]; + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); + } + } + } + else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } + else { + nonHttpBindingMembers.push(memberName); + } + } + nonHttpBindingMembers.discardResponseBody = discardResponseBody; + return nonHttpBindingMembers; + } +} + +class RpcProtocol extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const input = _input && typeof _input === "object" ? _input : {}; + const request = new HttpRequest({ + protocol: "", + hostname: "", + port: undefined, + path: "/", + fragment: undefined, + query: query, + headers: headers, + body: undefined, + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName] of ns.structIterator()) { + if (memberName !== eventStreamMember && input[memberName] != null) { + initialRequest[memberName] = input[memberName]; + } + } + payload = await this.serializeEventStream({ + eventStream: input[eventStreamMember], + requestSchema: ns, + initialRequest, + }); + } + } + else { + serializer.write(schema, input); + payload = serializer.flush(); + } + } + request.headers = Object.assign(request.headers, headers); + request.query = query; + request.body = payload; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject, + }); + } + else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } +} + +const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== undefined) { + const labelValue = labelValueProvider(); + if (labelValue == null || labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel + ? labelValue + .split("/") + .map((segment) => extendedEncodeURIComponent(segment)) + .join("/") + : extendedEncodeURIComponent(labelValue)); + } + else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath; +}; + +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +class RequestBuilder { + input; + context; + query = {}; + method = ""; + headers = {}; + path = ""; + body = null; + hostname = ""; + resolvePathStack = []; + constructor(input, context) { + this.input = input; + this.context = context; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers, + }); + } + hn(hostname) { + this.hostname = hostname; + return this; + } + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + h(headers) { + this.headers = headers; + return this; + } + q(query) { + this.query = query; + return this; + } + b(body) { + this.body = body; + return this; + } + m(method) { + this.method = method; + return this; + } +} + +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && + (ns.getSchema() === 5 || + ns.getSchema() === 6 || + ns.getSchema() === 7)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings + ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) + ? 6 + : Boolean(httpQuery) || Boolean(httpLabel) + ? 5 + : undefined + : undefined; + return bindingFormat ?? settings.timestampFormat.default; +} + +class FromStringShapeDeserializer extends SerdeContext { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + read(_schema, data) { + const ns = NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); + } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? fromBase64)(data); + } + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return _parseRfc3339DateTimeWithOffset(data); + case 6: + return _parseRfc7231DateTime(data); + case 7: + return _parseEpochTimestamp(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + if (ns.isNumericSchema()) { + return Number(data); + } + if (ns.isBigIntegerSchema()) { + return BigInt(data); + } + if (ns.isBigDecimalSchema()) { + return new NumericValue(data, "bigDecimal"); + } + if (ns.isBooleanSchema()) { + return String(data).toLowerCase() === "true"; + } + return data; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? toUtf8)((this.serdeContext?.base64Decoder ?? fromBase64)(base64String)); + } +} + +class HttpInterceptingShapeDeserializer extends SerdeContext { + codecDeserializer; + stringDeserializer; + constructor(codecDeserializer, codecSettings) { + super(); + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema, data) { + const ns = NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } + else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } + } + return this.codecDeserializer.read(ns, data); + } +} + +class ToStringShapeSerializer extends SerdeContext { + settings; + stringBuffer = ""; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + this.stringBuffer = dateToUtcString(value); + break; + case 7: + this.stringBuffer = String(value.getTime() / 1000); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1000); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + if (ns.isIdempotencyToken()) { + this.stringBuffer = generateIdempotencyToken(); + } + else { + this.stringBuffer = String(value); + } + } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +} + +class HttpInterceptingShapeSerializer { + codecSerializer; + stringSerializer; + buffer; + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== undefined) { + const buffer = this.buffer; + this.buffer = undefined; + return buffer; + } + return this.codecSerializer.flush(); + } +} + +class Field { + name; + kind; + values; + constructor({ name, kind = FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; + } + add(value) { + this.values.push(value); + } + set(values) { + this.values = values; + } + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + toString() { + return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); + } + get() { + return this.values; + } +} + +class Fields { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +} + +const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + if (runtimeConfig.logger && runtimeConfig.logger.constructor?.name !== "NoOpLogger") { + runtimeConfig.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"), runtimeConfig.logger); + } + return { + setHttpHandler(handler) { + runtimeConfig.requestHandler = handler; + }, + httpHandler() { + return runtimeConfig.requestHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.requestHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.requestHandler.httpHandlerConfigs(); + }, + }; +}; +const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + requestHandler: httpHandlerExtensionConfiguration.httpHandler(), + }; +}; + +const CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && + Object.keys(headers) + .map((str) => str.toLowerCase()) + .indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + if (length != null) { + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length), + }; + } + } + catch (ignored) { + } + } + } + return next({ + ...args, + request, + }); + }; +} +const contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true, +}; +const getContentLengthPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + }, +}); + +const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); +const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; + +const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = escapeUri(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${escapeUri(value[i])}`); + } + } + else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} + +class SerdeContextConfig { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } +} + +class UnionSerde { + from; + to; + keys; + constructor(from, to) { + this.from = from; + this.to = to; + const keys = Object.keys(this.from); + const set = new Set(keys); + set.delete("__type"); + this.keys = set; + } + mark(key) { + this.keys.delete(key); + } + hasUnknown() { + return this.keys.size === 1 && Object.keys(this.to).length === 0; + } + writeUnknown() { + if (this.hasUnknown()) { + const k = this.keys.values().next().value; + const v = this.from[k]; + this.to.$unknown = [k, v]; + } + } +} + +let canParseBuffer; +function detectBufferParsing() { + if (canParseBuffer === undefined) { + try { + if (typeof Buffer !== "function") { + canParseBuffer = false; + } + else { + const result = JSON.parse(Buffer.from([0x7b, 0x7d])); + canParseBuffer = result !== null && typeof result === "object"; + } + } + catch { + canParseBuffer = false; + } + } + return canParseBuffer; +} + +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + const inSafeRange = value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER; + if (inSafeRange) { + if (isRepresentable(numericString, value)) { + return value; + } + return new NumericValue(numericString, "bigDecimal"); + } + else { + if (isFractionalBigNumeric(numericString)) { + return new NumericValue(numericString, "bigDecimal"); + } + if (/[eE]/.test(numericString)) { + return expandExponentToBigInt(numericString); + } + return BigInt(numericString); + } + } + } + return value; +} +function isFractionalBigNumeric(s) { + const dotIndex = s.indexOf("."); + if (dotIndex === -1) { + return false; + } + const eIndex = s.search(/[eE]/); + if (eIndex === -1) { + return true; + } + const fracDigits = eIndex - dotIndex - 1; + const exp = parseInt(s.slice(eIndex + 1), 10); + return exp < fracDigits; +} +function isRepresentable(numericString, value) { + if (numericString === String(value)) { + return true; + } + if (Object.is(value, -0)) { + return true; + } + if (/[eE]/.test(numericString)) { + return expandToDecimal(numericString) === expandToDecimal(String(value)); + } + const normalized = numericString.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + const canonical = String(value); + if (normalized === canonical) { + return true; + } + if (/[eE]/.test(canonical)) { + return normalized === expandToDecimal(canonical); + } + return false; +} +function expandToDecimal(s) { + const negative = s.startsWith("-"); + const abs = negative ? s.slice(1) : s; + const eIndex = abs.search(/[eE]/); + let result; + if (eIndex === -1) { + result = abs; + } + else { + const exp = parseInt(abs.slice(eIndex + 1), 10); + const mantissa = abs.slice(0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let intLen; + if (dotIndex === -1) { + digits = mantissa; + intLen = mantissa.length; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + intLen = dotIndex; + } + digits = digits.replace(/0+$/, "") || "0"; + const newDotPos = intLen + exp; + if (digits === "0") { + result = "0"; + } + else if (newDotPos <= 0) { + result = "0." + "0".repeat(-newDotPos) + digits; + } + else if (newDotPos >= digits.length) { + result = digits + "0".repeat(newDotPos - digits.length); + } + else { + result = digits.slice(0, newDotPos) + "." + digits.slice(newDotPos); + } + } + if (result.includes(".")) { + result = result.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); + } + return (negative ? "-" : "") + result; +} +function expandExponentToBigInt(s) { + const eIndex = s.search(/[eE]/); + const exp = parseInt(s.slice(eIndex + 1), 10); + const negative = s.startsWith("-"); + const mantissa = s.slice(negative ? 1 : 0, eIndex); + const dotIndex = mantissa.indexOf("."); + let digits; + let shift; + if (dotIndex === -1) { + digits = mantissa; + shift = exp; + } + else { + digits = mantissa.slice(0, dotIndex) + mantissa.slice(dotIndex + 1); + const fracDigits = mantissa.length - dotIndex - 1; + shift = exp - fracDigits; + } + digits = digits.replace(/0+$/, "") || "0"; + const result = BigInt(digits) * 10n ** BigInt(shift + (mantissa.replace(".", "").length - digits.length)); + return negative ? -result : result; +} + +const REVIVER_SYMBOL = Symbol.for("@aws-sdk/reviver"); +function needsReviver(schema) { + const ns = NormalizedSchema.of(schema); + const raw = ns.getSchema(); + if (Array.isArray(raw) && ns.isStructSchema()) { + if (REVIVER_SYMBOL in raw) { + return raw[REVIVER_SYMBOL]; + } + const result = _check(ns, new Set()); + raw[REVIVER_SYMBOL] = result; + return result; + } + return _check(ns, new Set()); +} +function _check(ns, seen) { + const raw = ns.getSchema(); + if (seen.has(raw)) { + return false; + } + seen.add(raw); + if (ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + return true; + } + if (ns.isStructSchema()) { + for (const [, memberSchema] of ns.structIterator()) { + if (_check(memberSchema, seen)) { + return true; + } + } + } + else if (ns.isListSchema() || ns.isMapSchema()) { + if (_check(ns.getValueSchema(), seen)) { + return true; + } + } + else if (ns.isDocumentSchema()) { + return true; + } + return false; +} + +const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? toUtf8)(body)); + +async function parseJsonBody(streamBody, context, schema) { + let parsingInput; + if (detectBufferParsing() && typeof streamBody?.[Symbol.asyncIterator] === "function") { + const buffer = await collectBody(streamBody, context); + if (typeof Buffer === "function") { + if (Buffer.isBuffer(buffer)) { + parsingInput = buffer; + } + else { + parsingInput = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + } + } + if (!parsingInput) { + parsingInput = await collectBodyString(streamBody, context); + } + if (parsingInput.length === 0) { + return {}; + } + const reviver = schema && needsReviver(schema) ? jsonReviver : undefined; + try { + return JSON.parse(parsingInput, reviver); + } + catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: typeof parsingInput === "string" ? parsingInput : parsingInput.toString("utf8"), + }); + } + throw e; + } +} +const parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; +const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); +const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; +}; +const loadRestJsonErrorCode = (output, data) => { + return loadErrorCode(output, data, ["header", "code", "type"]); +}; +const loadJsonRpcErrorCode = (output, data, queryCompat = false) => { + return loadErrorCode(output, data, queryCompat ? ["code", "header", "type"] : ["type", "code", "header"]); +}; +const loadSmithyRpcV2JsonErrorCode = (output, data) => { + if (data?.__type !== undefined) { + let cleanValue = data.__type; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + return cleanValue; + } +}; +const loadErrorCode = ({ headers }, data, order) => { + while (order.length > 0) { + const location = order.shift(); + switch (location) { + case "header": + const headerKey = findKey(headers ?? {}, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(headers[headerKey]); + } + break; + case "code": + const codeKey = findKey(data ?? {}, "code"); + if (codeKey && data[codeKey] !== undefined) { + return sanitizeErrorCode(data[codeKey]); + } + break; + case "type": + if (data?.__type !== undefined) { + return sanitizeErrorCode(data.__type); + } + break; + } + } +}; + +function writeKey(obj) { + Object.defineProperty(obj, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true }); +} + +class JsonShapeDeserializer2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + let parsed; + if (typeof data === "string") { + if (data.length === 0) { + return {}; + } + parsed = JSON.parse(data, reviver); + } + else if (data instanceof Uint8Array && detectBufferParsing()) { + if (data.byteLength === 0) { + return {}; + } + const buf = Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + parsed = JSON.parse(buf, reviver); + } + else { + parsed = await parseJsonBody(data, this.serdeContext, schema); + } + return this._read(schema, parsed); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + return this._readStruct(ns, value); + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + if (this.needsTransform(listMember)) { + for (let i = 0; i < value.length; ++i) { + value[i] = this._read(listMember, value[i]); + } + } + return value; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const map = value; + if (this.needsTransform(mapMember)) { + for (const k in map) { + if (!hasOwn(map, k)) + continue; + if (k === "__proto__") { + writeKey(map); + } + map[k] = this._read(mapMember, map[k]); + } + } + return map; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (!(v instanceof NumericValue)) { + value[i] = this._read(ns, v); + } + } + } + else { + const doc = value; + for (const k in doc) { + if (!hasOwn(doc, k)) + continue; + if (k === "__proto__") { + writeKey(doc); + } + const v = doc[k]; + if (!(v instanceof NumericValue)) { + doc[k] = this._read(ns, v); + } + } + } + } + } + return value; + } + _readStruct(ns, record) { + const union = ns.isUnionSchema(); + const out = {}; + let nameMap; + const hasType = typeof record.__type === "string"; + const { jsonName } = this.settings; + if (jsonName && hasType) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + if (hasType) { + nameMap[fromKey] = memberName; + } + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (hasType) { + for (const k in record) { + if (!hasOwn(record, k)) + continue; + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + needsTransform(ns) { + if (ns.isBlobSchema() || + ns.isTimestampSchema() || + ns.isBigIntegerSchema() || + ns.isBigDecimalSchema() || + ns.isNumericSchema()) { + return true; + } + if (ns.isDocumentSchema() || ns.isStructSchema() || ns.isListSchema() || ns.isMapSchema()) { + return true; + } + if (ns.isStringSchema() && ns.getMergedTraits().mediaType) { + return true; + } + return false; + } +} + +class JsonBytesStringAdapter extends Uint8Array { + string = null; + static allocUnsafe(bytes) { + if (typeof Buffer === "function") { + const buffer = Buffer.allocUnsafe(bytes); + return new JsonBytesStringAdapter(buffer.buffer, buffer.byteOffset, buffer.byteLength); + } + return new JsonBytesStringAdapter(bytes); + } + toString() { + return this.s(); + } + valueOf() { + return this.s(); + } + includes(searchString, position) { + if (typeof searchString === "string") { + return this.s().includes(searchString, position); + } + return Uint8Array.prototype.includes.call(this, searchString, position); + } + indexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().indexOf(searchString, position); + } + return Uint8Array.prototype.indexOf.call(this, searchString, position); + } + lastIndexOf(searchString, position) { + if (typeof searchString === "string") { + return this.s().lastIndexOf(searchString, position); + } + const fn = Uint8Array.prototype.lastIndexOf; + if (position !== undefined) { + return fn.call(this, searchString, position); + } + return fn.call(this, searchString); + } + startsWith(searchString, position) { + return this.s().startsWith(searchString, position); + } + endsWith(searchString, endPosition) { + return this.s().endsWith(searchString, endPosition); + } + match(regexp) { + return this.s().match(regexp); + } + replace(searchValue, replaceValue) { + return this.s().replace(searchValue, replaceValue); + } + search(regexp) { + return this.s().search(regexp); + } + split(separator, limit) { + return this.s().split(separator, limit); + } + substring(start, end) { + return this.s().substring(start, end); + } + trim() { + return this.s().trim(); + } + trimStart() { + return this.s().trimStart(); + } + trimEnd() { + return this.s().trimEnd(); + } + charAt(pos) { + return this.s().charAt(pos); + } + charCodeAt(index) { + return this.s().charCodeAt(index); + } + padStart(maxLength, fillString) { + return this.s().padStart(maxLength, fillString); + } + padEnd(maxLength, fillString) { + return this.s().padEnd(maxLength, fillString); + } + repeat(count) { + return this.s().repeat(count); + } + toUpperCase() { + return this.s().toUpperCase(); + } + toLowerCase() { + return this.s().toLowerCase(); + } + s() { + if (this.string == null) { + const n = Date.now(); + if (n > warned + 60_000) { + console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. " + + "It has been automatically converted to string. In a future version this will throw an error."); + warned = n; + } + this.string = toUtf8(this); + } + return this.string; + } +} +var warned = 0; + +const encoder = new TextEncoder(); +const OPEN_BRACE = 0x7b; +const CLOSE_BRACE = 0x7d; +const OPEN_BRACKET = 0x5b; +const CLOSE_BRACKET = 0x5d; +const QUOTE = 0x22; +const COLON = 0x3a; +const COMMA = 0x2c; +const BACKSLASH = 0x5c; +const TRUE = new Uint8Array([0x74, 0x72, 0x75, 0x65]); +const FALSE = new Uint8Array([0x66, 0x61, 0x6c, 0x73, 0x65]); +const NULL = new Uint8Array([0x6e, 0x75, 0x6c, 0x6c]); +const ESCAPE_TABLE = new Array(128).fill(null); +ESCAPE_TABLE[0x08] = "b"; +ESCAPE_TABLE[0x09] = "t"; +ESCAPE_TABLE[0x0a] = "n"; +ESCAPE_TABLE[0x0c] = "f"; +ESCAPE_TABLE[0x0d] = "r"; +ESCAPE_TABLE[0x22] = '"'; +ESCAPE_TABLE[0x5c] = "\\"; +for (let i = 0; i < 0x20; i++) { + if (ESCAPE_TABLE[i] === null) { + ESCAPE_TABLE[i] = "u00" + i.toString(16).padStart(2, "0"); + } +} +const INITIAL_BUFFER_SIZE = 2048; +function alloc(size) { + return JsonBytesStringAdapter.allocUnsafe(size); +} +class JsonShapeSerializer2 extends SerdeContextConfig { + settings; + json; + i = 0; + rootSchema; + rawValue; + passthrough = false; + constructor(settings) { + super(); + this.settings = settings; + this.json = alloc(INITIAL_BUFFER_SIZE); + } + write(schema, value) { + this.i = 0; + this.rawValue = value; + this.rootSchema = NormalizedSchema.of(schema); + this.passthrough = this.rootSchema.isBlobSchema() || this.rootSchema.isStringSchema(); + if (!this.passthrough) { + this.writeValue(this.rootSchema, value, undefined); + } + } + writeDiscriminatedDocument(schema, value) { + this.i = 0; + this.rootSchema = NormalizedSchema.of(schema); + const ns = this.rootSchema; + if (ns.isStructSchema() && value != null && typeof value === "object") { + this.writeValue(ns, value, undefined); + const prefix = `"__type":"${ns.getName(true) ?? "Unknown"}",`; + const z = prefix.length; + this.ensure(z); + this.json.copyWithin(1 + z, 1, this.i); + encoder.encodeInto(prefix, this.json.subarray(1)); + this.i += z; + } + else { + this.writeValue(ns, value, undefined); + } + } + flush() { + this.rootSchema = undefined; + const finalPosition = this.i; + this.i = 0; + const raw = this.rawValue; + this.rawValue = undefined; + if (finalPosition === 0) { + return raw; + } + const result = this.json.subarray(0, finalPosition); + this.json = alloc(INITIAL_BUFFER_SIZE); + return result; + } + ensure(byteCount) { + const { i, json } = this; + if (i + byteCount > json.length) { + let newSize = json.length * 2; + while (newSize < i + byteCount) { + newSize *= 2; + } + const next = alloc(newSize); + next.set(this.json); + this.json = next; + } + } + writeAscii(s) { + const z = s.length; + this.ensure(z); + let { i, json } = this; + for (let j = 0; j < z; ++j) { + json[i] = s.charCodeAt(j); + i += 1; + } + this.i = i; + } + writeAsciiQuoted(s) { + const z = s.length; + this.ensure(z + 4); + let { json, i } = this; + json[i++] = QUOTE; + for (let j = 0; j < z; ++j) { + json[i++] = s.charCodeAt(j); + } + json[i++] = QUOTE; + this.i = i; + } + writeJsonString(s) { + this.ensure(s.length * 3 + 2); + this.json[this.i++] = QUOTE; + const z = s.length; + for (let j = 0; j < z; ++j) { + const c = s.charCodeAt(j); + if (c > 0x22 && c < 0x5c) { + this.json[this.i++] = c; + } + else if (c < 0x80) { + const esc = ESCAPE_TABLE[c]; + if (esc !== null) { + this.ensure(esc.length + 1); + this.json[this.i++] = BACKSLASH; + for (let k = 0; k < esc.length; k++) { + this.json[this.i++] = esc.charCodeAt(k); + } + } + else { + this.json[this.i++] = c; + } + } + else if (c >= 0xd800 && c <= 0xdbff) { + const next = j + 1 < z ? s.charCodeAt(j + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + this.ensure(4); + const { written } = encoder.encodeInto(s.substring(j, j + 2), this.json.subarray(this.i)); + this.i += written; + ++j; + } + else { + this.ensure(6); + this.writeUnicodeEscape(c); + } + } + else if (c >= 0xdc00 && c <= 0xdfff) { + this.ensure(6); + this.writeUnicodeEscape(c); + } + else { + let { i, json } = this; + if (c < 0x800) { + json[i++] = 0xc0 | (c >> 6); + json[i++] = 0x80 | (c & 0x3f); + } + else { + json[i++] = 0xe0 | (c >> 12); + json[i++] = 0x80 | ((c >> 6) & 0x3f); + json[i++] = 0x80 | (c & 0x3f); + } + this.i = i; + } + } + this.json[this.i++] = QUOTE; + } + writeUnicodeEscape(code) { + let { json, i } = this; + json[i++] = BACKSLASH; + json[i++] = 0x75; + const hex = code.toString(16).padStart(4, "0"); + for (let j = 0; j < 4; ++j) { + json[i++] = hex.charCodeAt(j); + } + this.i = i; + } + static B64 = (() => { + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const table = new Uint8Array(64); + for (let i = 0; i < 64; ++i) { + table[i] = chars.charCodeAt(i); + } + return table; + })(); + writeBase64(data) { + const b64Len = Math.ceil(data.length / 3) * 4; + this.ensure(b64Len + 2); + const json = this.json; + const B64 = JsonShapeSerializer2.B64; + let i = this.i; + json[i++] = QUOTE; + const len = data.length; + const remainder = len % 3; + const mainLen = len - remainder; + for (let j = 0; j < mainLen; j += 3) { + const a = data[j]; + const b = data[j + 1]; + const c = data[j + 2]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[((b & 0x0f) << 2) | (c >> 6)]; + json[i++] = B64[c & 0x3f]; + } + if (remainder === 2) { + const a = data[mainLen]; + const b = data[mainLen + 1]; + json[i++] = B64[a >> 2]; + json[i++] = B64[((a & 0x03) << 4) | (b >> 4)]; + json[i++] = B64[(b & 0x0f) << 2]; + json[i++] = 0x3d; + } + else if (remainder === 1) { + const a = data[mainLen]; + json[i++] = B64[a >> 2]; + json[i++] = B64[(a & 0x03) << 4]; + json[i++] = 0x3d; + json[i++] = 0x3d; + } + json[i++] = QUOTE; + this.i = i; + } + writeValue(schema, value, container) { + if (value == null) { + if (container?.isStructSchema()) { + if (value === undefined) { + const ns = NormalizedSchema.of(schema); + if (ns.isIdempotencyToken()) { + this.writeAsciiQuoted(generateIdempotencyToken()); + return; + } + } + return; + } + this.ensure(4); + this.json.set(NULL, this.i); + this.i += 4; + return; + } + const ns = NormalizedSchema.of(schema); + const isObject = typeof value === "object"; + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + this.writeJsonString(LazyJsonString.from(value).toString()); + return; + } + } + } + if (this.settings.bigNumberAsString && value != null && (ns.isBigIntegerSchema() || ns.isBigDecimalSchema())) { + const asString = value instanceof NumericValue ? value.string : String(value); + this.writeAsciiQuoted(asString); + return; + } + if (isObject) { + if (ns.isStructSchema()) { + this.writeStruct(ns, value); + return; + } + if (Array.isArray(value) && (ns.isListSchema() || ns.isDocumentSchema())) { + this.writeList(ns, value, ns.isDocumentSchema()); + return; + } + if (ns.isMapSchema()) { + this.writeMap(ns, value, false); + return; + } + if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { + this.writeBase64(value); + return; + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + this.writeTimestamp(ns, value); + return; + } + if (value instanceof NumericValue) { + this.writeAscii(value.string); + return; + } + if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.writeList(ns, value, true); + } + else { + this.writeMap(ns, value, true); + } + return; + } + const json = JSON.stringify(value); + this.writeAscii(json); + return; + } + if (typeof value === "string") { + if (ns.isBlobSchema()) { + const b64 = (this.serdeContext?.base64Encoder ?? toBase64)(value); + this.writeAsciiQuoted(b64); + return; + } + this.writeJsonString(value); + return; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || Number.isNaN(value)) { + this.writeAsciiQuoted(String(value)); + return; + } + const numStr = String(value); + this.writeAscii(numStr); + return; + } + if (typeof value === "boolean") { + this.ensure(5); + let { i, json } = this; + if (value) { + json.set(TRUE, i); + i += 4; + } + else { + json.set(FALSE, i); + i += 5; + } + this.i = i; + return; + } + if (typeof value === "bigint") { + this.writeAscii(value.toString()); + return; + } + this.writeAscii(String(value)); + } + writeStruct(ns, value) { + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let wroteAny = false; + const hasType = typeof value.__type === "string"; + let writtenKeys; + if (hasType) { + writtenKeys = new Set(); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const item = value[memberName]; + if (item == null && !memberSchema.isIdempotencyToken()) { + continue; + } + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + const targetKey = this.settings.jsonName ? (memberSchema.getMergedTraits().jsonName ?? memberName) : memberName; + if (writtenKeys) { + writtenKeys.add(memberName); + writtenKeys.add(targetKey); + } + this.writeAsciiQuoted(targetKey); + this.json[this.i++] = COLON; + this.writeValue(memberSchema, item, ns); + } + if (!wroteAny && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, ns); + } + } + else if (hasType) { + for (const k in value) { + if (writtenKeys.has(k)) { + continue; + } + writtenKeys.add(k); + const v = value[k]; + if (wroteAny) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + wroteAny = true; + this.writeAsciiQuoted(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(15, v, undefined); + } + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeList(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let hasSpecials = false; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity || (v == null && !sparse)) { + hasSpecials = true; + break; + } + } + let json; + if (!hasSpecials) { + json = JSON.stringify(value); + } + else { + const out = []; + for (let i = 0; i < value.length; ++i) { + const v = value[i]; + if (v == null && !sparse) + continue; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + out.push(String(v)); + } + else { + out.push(v); + } + } + json = JSON.stringify(out); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACKET; + let wroteFirstItem = false; + for (let i = 0; i < value.length; ++i) { + const item = value[i]; + if (isDocument ? item === undefined : item == null && !sparse) { + continue; + } + if (wroteFirstItem) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + this.writeValue(valueSchema, item, undefined); + wroteFirstItem = true; + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACKET; + } + writeMap(ns, value, isDocument) { + const sparse = !!ns.getMergedTraits().sparse; + const valueSchema = ns.getValueSchema(); + if (!isDocument) { + if (valueSchema.isStringSchema() || valueSchema.isNumericSchema() || valueSchema.isBooleanSchema()) { + let modifications; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + const v = value[k]; + if (Number.isNaN(v) || v === Infinity || v === -Infinity) { + (modifications ??= {})[k] = v; + value[k] = String(v); + } + else if (v === null && !sparse) { + (modifications ??= {})[k] = null; + value[k] = undefined; + } + } + const json = JSON.stringify(value); + if (modifications) { + Object.assign(value, modifications); + } + this.ensure(json.length * 3); + this.i += encoder.encodeInto(json, this.json.subarray(this.i)).written; + return; + } + } + this.ensure(2); + this.json[this.i++] = OPEN_BRACE; + let first = true; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + const v = value[k]; + if (isDocument ? v === undefined : v == null && !sparse) { + continue; + } + if (!first) { + this.ensure(1); + this.json[this.i++] = COMMA; + } + first = false; + this.writeJsonString(k); + this.ensure(1); + this.json[this.i++] = COLON; + this.writeValue(valueSchema, v, undefined); + } + this.ensure(1); + this.json[this.i++] = CLOSE_BRACE; + } + writeTimestamp(ns, value) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: { + const iso = value.toISOString().replace(".000Z", "Z"); + this.writeAsciiQuoted(iso); + return; + } + case 6: { + this.writeAsciiQuoted(dateToUtcString(value)); + return; + } + case 7: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + default: { + const epochSecs = String(value.getTime() / 1000); + this.writeAscii(epochSecs); + return; + } + } + } +} + +class JsonCodec2 extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer2(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer2(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +class SmithyRpcV2JsonProtocol extends RpcProtocol { + codec = new JsonCodec2({ + timestampFormat: { + useTrait: false, + default: 7, + }, + jsonName: false, + bigNumberAsString: true, + }); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace, errorTypeRegistries, }) { + super({ defaultNamespace, errorTypeRegistries }); + } + getShapeId() { + return "smithy.protocols#rpcv2Json"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-json", + accept: this.getDefaultContentType(), + }); + if (deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } + else if (!request.body) { + request.body = "{}"; + } + const { service, operation } = getSmithyContext(context); + const path = `/service/${service}/operation/${operation}`; + if (request.path.endsWith("/")) { + request.path += path.slice(1); + } + else { + request.path += path; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2JsonErrorCode(response, dataObject) ?? "Unknown"; + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode <= 500 ? "client" : "server", + }; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const registry = this.compositeErrorRegistry; + const nsRegistry = TypeRegistry.for(namespace); + registry.copyFrom(nsRegistry); + let errorSchema; + try { + errorSchema = registry.getSchema(errorName); + } + catch (ignored) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const syntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + registry.copyFrom(syntheticRegistry); + const baseExceptionSchema = registry.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = registry.getErrorCtor(baseExceptionSchema); + throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = registry.getErrorCtor(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor({}); + const output = {}; + const errorDeserializer = this.codec.createDeserializer(); + for (const [name, member] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = errorDeserializer.readObject(member, dataObject[name]); + } + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message, + }, output); + } + getDefaultContentType() { + return "application/json"; + } +} + +class JsonShapeDeserializer extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema, data) { + const reviver = needsReviver(schema) ? jsonReviver : undefined; + return this._read(schema, typeof data === "string" ? JSON.parse(data, reviver) : await parseJsonBody(data, this.serdeContext, schema)); + } + readObject(schema, data) { + return this._read(schema, data); + } + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const union = ns.isUnionSchema(); + const out = {}; + let nameMap = void 0; + const { jsonName } = this.settings; + if (jsonName) { + nameMap = {}; + } + let unionSerde; + if (union) { + unionSerde = new UnionSerde(record, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + nameMap[fromKey] = memberName; + } + if (union) { + unionSerde.mark(fromKey); + } + if (record[fromKey] != null) { + out[memberName] = this._read(memberSchema, record[fromKey]); + } + } + if (union) { + unionSerde.writeUnknown(); + } + else if (typeof record.__type === "string") { + for (const k in record) { + if (!hasOwn(record, k)) + continue; + const v = record[k]; + const t = jsonName ? (nameMap[k] ?? k) : k; + if (!(t in out)) { + out[t] = v; + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(this._read(listMember, item)); + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + for (const _k in value) { + if (!hasOwn(value, _k)) + continue; + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._read(mapMember, value[_k]); + } + return out; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return fromBase64(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != undefined) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject) { + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + if (k === "__proto__") { + writeKey(out); + } + const v = value[k]; + if (v instanceof NumericValue) { + out[k] = v; + } + else { + out[k] = this._read(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +class JsonReplacer { + values = new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; + } + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; + } +} + +class JsonShapeSerializer extends SerdeContextConfig { + settings; + buffer; + useReplacer = false; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema, value) { + this.rootSchema = NormalizedSchema.of(schema); + this.buffer = this._write(this.rootSchema, value); + } + flush() { + const { rootSchema, useReplacer } = this; + this.rootSchema = undefined; + this.useReplacer = false; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + if (!useReplacer) { + return JSON.stringify(this.buffer); + } + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + writeDiscriminatedDocument(schema, value) { + this.write(schema, value); + if (typeof this.buffer === "object") { + this.buffer.__type = NormalizedSchema.of(schema).getName(true); + } + } + _write(schema, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema); + if (isObject) { + if (ns.isStructSchema()) { + const record = value; + const out = {}; + const { jsonName } = this.settings; + let nameMap = void 0; + if (jsonName) { + nameMap = {}; + } + let outCount = 0; + for (const [memberName, memberSchema] of ns.structIterator()) { + const serializableValue = this._write(memberSchema, record[memberName], ns); + if (serializableValue !== undefined) { + let targetKey = memberName; + if (jsonName) { + targetKey = memberSchema.getMergedTraits().jsonName ?? memberName; + nameMap[memberName] = targetKey; + } + out[targetKey] = serializableValue; + outCount++; + } + } + if (ns.isUnionSchema() && outCount === 0) { + const { $unknown } = record; + if (Array.isArray($unknown)) { + const [k, v] = $unknown; + if (k === "__proto__") { + writeKey(out); + } + out[k] = this._write(15, v); + } + } + else if (typeof record.__type === "string") { + for (const k in record) { + if (!hasOwn(record, k)) + continue; + const v = record[k]; + const targetKey = jsonName ? (nameMap[k] ?? k) : k; + if (!(targetKey in out)) { + out[targetKey] = this._write(15, v); + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const _k in value) { + if (!hasOwn(value, _k)) + continue; + const _v = value[_k]; + if (sparse || _v != null) { + if (_k === "__proto__") { + writeKey(out); + } + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + if (value instanceof Uint8Array && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return dateToUtcString(value); + case 7: + return value.getTime() / 1000; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1000; + } + } + if (value instanceof NumericValue) { + this.useReplacer = true; + } + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return generateIdempotencyToken(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + } + return value; + } + if (typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + return value; + } + if (typeof value === "string" && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + if (typeof value === "bigint") { + this.useReplacer = true; + } + if (ns.isDocumentSchema()) { + if (isObject) { + if (value instanceof Uint8Array) { + return (this.serdeContext?.base64Encoder ?? toBase64)(value); + } + const out = Array.isArray(value) ? [] : {}; + for (const k in value) { + if (!hasOwn(value, k)) + continue; + const v = value[k]; + if (k === "__proto__") { + writeKey(out); + } + if (v instanceof NumericValue) { + this.useReplacer = true; + out[k] = v; + } + else { + out[k] = this._write(ns, v); + } + } + return out; + } + else { + return structuredClone(value); + } + } + return value; + } +} + +class JsonCodec extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } +} + +exports.Field = Field; +exports.Fields = Fields; +exports.FromStringShapeDeserializer = FromStringShapeDeserializer; +exports.HttpBindingProtocol = HttpBindingProtocol; +exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer; +exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer; +exports.HttpProtocol = HttpProtocol; +exports.JsonCodec = JsonCodec; +exports.JsonCodec2 = JsonCodec2; +exports.JsonShapeDeserializer = JsonShapeDeserializer; +exports.JsonShapeDeserializer2 = JsonShapeDeserializer2; +exports.JsonShapeSerializer = JsonShapeSerializer; +exports.JsonShapeSerializer2 = JsonShapeSerializer2; +exports.RequestBuilder = RequestBuilder; +exports.RpcProtocol = RpcProtocol; +exports.SerdeContext = SerdeContext; +exports.SmithyRpcV2JsonProtocol = SmithyRpcV2JsonProtocol; +exports.ToStringShapeSerializer = ToStringShapeSerializer; +exports.buildQueryString = buildQueryString; +exports.collectBody = collectBody; +exports.contentLengthMiddleware = contentLengthMiddleware; +exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; +exports.determineTimestampFormat = determineTimestampFormat; +exports.escapeUri = escapeUri; +exports.escapeUriPath = escapeUriPath; +exports.extendedEncodeURIComponent = extendedEncodeURIComponent; +exports.getContentLengthPlugin = getContentLengthPlugin; +exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; +exports.loadJsonRpcErrorCode = loadJsonRpcErrorCode; +exports.loadRestJsonErrorCode = loadRestJsonErrorCode; +exports.loadSmithyRpcV2JsonErrorCode = loadSmithyRpcV2JsonErrorCode; +exports.parseJsonBody = parseJsonBody; +exports.parseJsonErrorBody = parseJsonErrorBody; +exports.requestBuilder = requestBuilder; +exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; +exports.resolvedPath = resolvedPath; + + +/***/ }), + +/***/ 26266: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { Readable } = __webpack_require__(57075); +const { NoOpLogger, normalizeProvider } = __webpack_require__(20895); +const { HttpResponse, HttpRequest } = __webpack_require__(62049); +const { parseRfc7231DateTime, v4 } = __webpack_require__(34129); +const { hasOwn } = __webpack_require__(30673); + +const isStreamingPayload = (request) => request?.body instanceof Readable || + (typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream); + +const CLOCK_SKEW_ERROR_CODES = [ + "AccessDeniedException", + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch", +]; +const THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException", +]; +const TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; +const NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN"]; + +const isRetryableByTrait = (error) => error?.$retryable !== undefined; +const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name); +const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; +const isBrowserNetworkError = (error) => { + const errorMessages = new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed", + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; + } + return errorMessages.has(error.message); +}; +const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || + THROTTLING_ERROR_CODES.includes(error.name) || + error.$retryable?.throttling == true; +const isTransientError = (error, depth = 0) => error?.name !== "AbortError" && + (isRetryableByTrait(error) || + isClockSkewCorrectedError(error) || + (error.name === "InvalidSignatureException" && error.message?.includes("Signature expired")) || + TRANSIENT_ERROR_CODES.includes(error.name) || + NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || + NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || + TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || + isBrowserNetworkError(error) || + isNodeJsHttp2TransientError(error) || + (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1))); +const isServerError = (error) => { + if (error.$metadata?.httpStatusCode !== undefined) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; + } + return false; + } + return false; +}; +function isNodeJsHttp2TransientError(error) { + return error.code === "ERR_HTTP2_STREAM_ERROR" && error.message.includes("NGHTTP2_REFUSED_STREAM"); +} + +const DEFAULT_RETRY_DELAY_BASE = 100; +const MAXIMUM_RETRY_DELAY = 20 * 1000; +const THROTTLING_RETRY_DELAY_BASE = 500; +const INITIAL_RETRY_TOKENS = 500; +const RETRY_COST = 5; +const TIMEOUT_RETRY_COST = 10; +const NO_RETRY_INCREMENT = 1; +const INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +const REQUEST_HEADER = "amz-sdk-request"; + +function parseRetryAfterHeader(response, logger) { + if (!HttpResponse.isInstance(response)) { + return; + } + for (const header in response.headers) { + if (!hasOwn(response.headers, header)) + continue; + const h = header.toLowerCase(); + if (h === "retry-after") { + const retryAfter = response.headers[header]; + let retryAfterSeconds = NaN; + if (retryAfter.endsWith("GMT")) { + try { + const date = parseRfc7231DateTime(retryAfter); + retryAfterSeconds = (date.getTime() - Date.now()) / 1000; + } + catch (e) { + logger?.trace?.("Failed to parse retry-after header"); + logger?.trace?.(e); + } + } + else if (retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter.match(/ GMT, ([\d.]+)$/)?.[1]); + } + else if (retryAfter.match(/^((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter); + } + else if (Date.parse(retryAfter) >= Date.now()) { + retryAfterSeconds = (Date.parse(retryAfter) - Date.now()) / 1000; + } + if (isNaN(retryAfterSeconds)) { + return; + } + return new Date(Date.now() + retryAfterSeconds * 1000); + } + else if (h === "x-amz-retry-after") { + const v = response.headers[header]; + const backoffMilliseconds = Number(v); + if (isNaN(backoffMilliseconds)) { + logger?.trace?.(`Failed to parse x-amz-retry-after=${v}`); + return; + } + return new Date(Date.now() + backoffMilliseconds); + } + } +} +function getRetryAfterHint(response, logger) { + return parseRetryAfterHeader(response, logger); +} + +const asSdkError = (error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); +}; + +function bindRetryMiddleware(isStreamingPayload) { + return (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken((context["partition_id"] ?? "") + (context.__retryLongPoll ? ":longpoll" : "")); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = HttpRequest.isInstance(request); + if (isRequest) { + request.headers[INVOCATION_ID_HEADER] = v4(); + } + while (true) { + try { + if (isRequest) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } + catch (e) { + const retryErrorInfo = getRetryErrorInfo(e, options.logger); + lastError = asSdkError(e); + if (isRequest && isStreamingPayload(request)) { + (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } + catch (ignoredRefreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += (retryToken?.$retryLog?.acquisitionDelay ?? 0) + delay; + if (delay > 0) { + await cooldown(delay); + } + } + } + } + else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) { + context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; + } + return retryStrategy.retry(next, args); + } + }; +} +const cooldown = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && + typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && + typeof retryStrategy.recordSuccess !== "undefined"; +const getRetryErrorInfo = (error, logger) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error), + }; + const retryAfterHint = parseRetryAfterHeader(error.$response, logger); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; +}; +const getRetryErrorType = (error) => { + if (isThrottlingError(error)) + return "THROTTLING"; + if (isTransientError(error)) + return "TRANSIENT"; + if (isServerError(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}; +const retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true, +}; +function bindGetRetryPlugin(isStreamingPayload) { + const retryMiddleware = bindRetryMiddleware(isStreamingPayload); + return (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + }, + }); +} + +class DefaultRateLimiter { + static setTimeoutFn = (fn, delay) => setTimeout(fn, delay); + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + enabled = false; + availableTokens = 0; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + const retryErrorInfo = response; + const isThrottling = retryErrorInfo?.errorType === "THROTTLING" || isThrottlingError(retryErrorInfo?.error ?? response); + if (isThrottling) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } + else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + getCurrentTimeInSeconds() { + return Date.now() / 1000; + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + while (amount > this.availableTokens) { + const delay = ((amount - this.availableTokens) / this.fillRate) * 1000; + await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay)); + this.refillTokenBucket(); + } + this.availableTokens = this.availableTokens - amount; + } + refillTokenBucket() { + const timestamp = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp; + return; + } + const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; + this.availableTokens = Math.min(this.maxCapacity, this.availableTokens + fillAmount); + this.lastTimestamp = timestamp; + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.availableTokens = Math.min(this.availableTokens, this.maxCapacity); + } + updateMeasuredRate() { + const t = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } +} + +class Retry { + static v2026 = typeof process !== "undefined" && process.env?.SMITHY_NEW_RETRIES_2026 === "true"; + static delay() { + return Retry.v2026 ? 50 : 100; + } + static throttlingDelay() { + return Retry.v2026 ? 1_000 : 500; + } + static cost() { + return Retry.v2026 ? 14 : 5; + } + static throttlingCost() { + return Retry.v2026 ? 5 : 10; + } + static modifiedCostType() { + return Retry.v2026 ? "THROTTLING" : "TRANSIENT"; + } +} + +class DefaultRetryBackoffStrategy { + x = Retry.delay(); + computeNextBackoffDelay(i) { + const b = Math.random(); + const r = 2; + const t_i = b * Math.min(this.x * r ** i, MAXIMUM_RETRY_DELAY); + return Math.floor(t_i); + } + setDelayBase(delay) { + this.x = delay; + } +} + +class DefaultRetryToken { + delay; + count; + cost; + longPoll; + $retryLog = { + acquisitionDelay: 0, + }; + constructor(delay, count, cost, longPoll) { + this.delay = delay; + this.count = count; + this.cost = cost; + this.longPoll = longPoll; + } + getRetryCount() { + return this.count; + } + getRetryDelay() { + return Math.min(MAXIMUM_RETRY_DELAY, this.delay); + } + getRetryCost() { + return this.cost; + } + isLongPoll() { + return this.longPoll; + } +} + +var RETRY_MODES; +(function (RETRY_MODES) { + RETRY_MODES["STANDARD"] = "standard"; + RETRY_MODES["ADAPTIVE"] = "adaptive"; +})(RETRY_MODES || (RETRY_MODES = {})); +const DEFAULT_MAX_ATTEMPTS = 3; +const DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD; + +const refusal = { + incompatible: 1, + attempts: 2, + capacity: 3, +}; +let StandardRetryStrategy$1 = class StandardRetryStrategy { + mode = RETRY_MODES.STANDARD; + retryBackoffStrategy; + capacity = INITIAL_RETRY_TOKENS; + maxAttemptsProvider; + baseDelay; + constructor(arg1) { + if (typeof arg1 === "number") { + this.maxAttemptsProvider = async () => arg1; + } + else if (typeof arg1 === "function") { + this.maxAttemptsProvider = arg1; + } + else if (arg1 && typeof arg1 === "object") { + this.maxAttemptsProvider = async () => arg1.maxAttempts; + this.baseDelay = arg1.baseDelay; + this.retryBackoffStrategy = arg1.backoff; + } + this.maxAttemptsProvider ??= async () => DEFAULT_MAX_ATTEMPTS; + this.baseDelay ??= Retry.delay(); + this.retryBackoffStrategy ??= new DefaultRetryBackoffStrategy(); + } + async acquireInitialRetryToken(retryTokenScope) { + return new DefaultRetryToken(Retry.delay(), 0, undefined, Retry.v2026 && retryTokenScope.includes(":longpoll")); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + const retryCode = this.retryCode(token, errorInfo, maxAttempts); + const shouldRetry = retryCode === 0; + const isLongPoll = token.isLongPoll?.(); + if (shouldRetry || isLongPoll) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? Retry.throttlingDelay() : this.baseDelay); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + let retryDelay = delayFromErrorType; + if (errorInfo.retryAfterHint instanceof Date) { + retryDelay = Math.max(delayFromErrorType, Math.min(errorInfo.retryAfterHint.getTime() - Date.now(), delayFromErrorType + 5_000)); + } + if (!shouldRetry) { + const longPollBackoff = Retry.v2026 && retryCode === refusal.capacity && isLongPoll ? retryDelay : 0; + if (longPollBackoff > 0) { + await new Promise((r) => setTimeout(r, longPollBackoff)); + } + } + else { + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + const nextToken = new DefaultRetryToken(0, token.getRetryCount() + 1, capacityCost, token.isLongPoll?.() ?? false); + await new Promise((r) => setTimeout(r, retryDelay)); + nextToken.$retryLog.acquisitionDelay = retryDelay; + return nextToken; + } + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.min(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async maxAttempts() { + return this.maxAttemptsProvider(); + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } + catch (ignored) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + retryCode(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + const retryableStatus = this.isRetryableError(errorInfo.errorType) ? 0 : refusal.incompatible; + const attemptStatus = attempts < maxAttempts ? 0 : refusal.attempts; + const capacityStatus = this.capacity >= this.getCapacityCost(errorInfo.errorType) ? 0 : refusal.capacity; + return retryableStatus || attemptStatus || capacityStatus; + } + getCapacityCost(errorType) { + return errorType === Retry.modifiedCostType() ? Retry.throttlingCost() : Retry.cost(); + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +}; + +let AdaptiveRetryStrategy$1 = class AdaptiveRetryStrategy { + mode = RETRY_MODES.ADAPTIVE; + rateLimiter; + standardRetryStrategy; + constructor(maxAttemptsProvider, options) { + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = options + ? new StandardRetryStrategy$1({ + maxAttempts: typeof maxAttemptsProvider === "number" ? maxAttemptsProvider : 3, + ...options, + }) + : new StandardRetryStrategy$1(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + const token = await this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + await this.rateLimiter.getSendToken(); + return token; + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + const token = await this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + await this.rateLimiter.getSendToken(); + return token; + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } + async maxAttemptsProvider() { + return this.standardRetryStrategy.maxAttempts(); + } +}; + +class ConfiguredRetryStrategy extends StandardRetryStrategy$1 { + computeNextBackoffDelay; + constructor(maxAttempts, computeNextBackoffDelay = Retry.delay()) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } + else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + this.retryBackoffStrategy.computeNextBackoffDelay = (completedAttempt) => { + const nextAttempt = completedAttempt + 1; + return this.computeNextBackoffDelay(nextAttempt); + }; + } +} + +const getDefaultRetryQuota = (initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = NO_RETRY_INCREMENT; + const retryCost = RETRY_COST; + const timeoutRetryCost = TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); + const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; + const retrieveRetryTokens = (error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); + } + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }; + const releaseRetryTokens = (capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }; + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens, + }); +}; + +const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + +const defaultRetryDecider = (error) => { + if (!error) { + return false; + } + return isRetryableByTrait(error) || isClockSkewError(error) || isThrottlingError(error) || isTransientError(error); +}; + +class StandardRetryStrategy { + maxAttemptsProvider; + retryDecider; + delayDecider; + retryQuota; + mode = RETRY_MODES.STANDARD; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(INITIAL_RETRY_TOKENS); + } + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } + catch (ignored) { + maxAttempts = DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (HttpRequest.isInstance(request)) { + request.headers[INVOCATION_ID_HEADER] = v4(); + } + while (true) { + try { + if (HttpRequest.isInstance(request)) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); + } + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } + catch (e) { + const err = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider(isThrottlingError(err) ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE, attempts); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; + } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } + } + } +} +const getDelayFromRetryAfterHeader = (response) => { + if (!HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return Math.min(retryAfterSeconds * 1000, 20_000); + const retryAfterDate = new Date(retryAfter); + return Math.min(retryAfterDate.getTime() - Date.now(), 20_000); +}; + +class AdaptiveRetryStrategy extends StandardRetryStrategy { + rateLimiter; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.mode = RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + }, + }); + } +} + +const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +const CONFIG_MAX_ATTEMPTS = "max_attempts"; +const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return undefined; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + default: DEFAULT_MAX_ATTEMPTS, +}; +const resolveRetryConfig = (input, defaults) => { + const { retryStrategy, retryMode } = input; + const { defaultMaxAttempts = DEFAULT_MAX_ATTEMPTS, defaultBaseDelay = Retry.delay() } = defaults ?? {}; + const maxAttemptsProvider = normalizeProvider(input.maxAttempts ?? defaultMaxAttempts); + let controller = retryStrategy + ? Promise.resolve(retryStrategy) + : undefined; + const getDefault = async () => { + const maxAttempts = await maxAttemptsProvider(); + const adaptive = (await normalizeProvider(retryMode)()) === RETRY_MODES.ADAPTIVE; + if (adaptive) { + return new AdaptiveRetryStrategy$1(maxAttemptsProvider, { + maxAttempts, + baseDelay: defaultBaseDelay, + }); + } + return new StandardRetryStrategy$1({ + maxAttempts, + baseDelay: defaultBaseDelay, + }); + }; + return Object.assign(input, { + maxAttempts: maxAttemptsProvider, + retryStrategy: () => (controller ??= getDefault()), + }); +}; +const ENV_RETRY_MODE = "AWS_RETRY_MODE"; +const CONFIG_RETRY_MODE = "retry_mode"; +const NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: DEFAULT_RETRY_MODE, +}; + +const omitRetryHeadersMiddleware = () => (next) => async (args) => { + const { request } = args; + if (HttpRequest.isInstance(request)) { + delete request.headers[INVOCATION_ID_HEADER]; + delete request.headers[REQUEST_HEADER]; + } + return next(args); +}; +const omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true, +}; +const getOmitRetryHeadersPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + }, +}); + +const retryMiddleware = bindRetryMiddleware(isStreamingPayload); +const getRetryPlugin = bindGetRetryPlugin(isStreamingPayload); + +exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy$1; +exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; +exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; +exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; +exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; +exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; +exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE; +exports.DefaultRateLimiter = DefaultRateLimiter; +exports.DeprecatedAdaptiveRetryStrategy = AdaptiveRetryStrategy; +exports.DeprecatedStandardRetryStrategy = StandardRetryStrategy; +exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; +exports.ENV_RETRY_MODE = ENV_RETRY_MODE; +exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; +exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; +exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; +exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS; +exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS; +exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; +exports.REQUEST_HEADER = REQUEST_HEADER; +exports.RETRY_COST = RETRY_COST; +exports.RETRY_MODES = RETRY_MODES; +exports.Retry = Retry; +exports.StandardRetryStrategy = StandardRetryStrategy$1; +exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; +exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; +exports.defaultDelayDecider = defaultDelayDecider; +exports.defaultRetryDecider = defaultRetryDecider; +exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; +exports.getRetryAfterHint = getRetryAfterHint; +exports.getRetryPlugin = getRetryPlugin; +exports.isBrowserNetworkError = isBrowserNetworkError; +exports.isClockSkewCorrectedError = isClockSkewCorrectedError; +exports.isClockSkewError = isClockSkewError; +exports.isNodeJsHttp2TransientError = isNodeJsHttp2TransientError; +exports.isRetryableByTrait = isRetryableByTrait; +exports.isServerError = isServerError; +exports.isThrottlingError = isThrottlingError; +exports.isTransientError = isTransientError; +exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; +exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; +exports.resolveRetryConfig = resolveRetryConfig; +exports.retryMiddleware = retryMiddleware; +exports.retryMiddlewareOptions = retryMiddlewareOptions; + + +/***/ }), + +/***/ 39875: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { getSmithyContext, HttpResponse, toEndpointV1 } = __webpack_require__(30673); + +const deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; +}; + +const operation = (namespace, name, traits, input, output) => ({ + name, + namespace, + traits, + input, + output, +}); + +const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + try { + const parsed = await config.protocol.deserializeResponse(operation(ns, n, t, i, o), { + ...config, + ...context, + }, response); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (ignored) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (HttpResponse.isInstance(response)) { + const { headers = {}, statusCode } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (ignored) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = getSmithyContext(context); + const [, ns, n, t, i, o] = operationSchema ?? []; + const endpoint = context.endpointV2 + ? async () => toEndpointV1(context.endpointV2) + : config.endpoint; + const request = await config.protocol.serializeRequest(operation(ns, n, t, i, o), args.input, { + ...config, + ...context, + endpoint, + }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSchemaSerdePlugin(config) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + }, + }; +} + +class Schema { + name; + namespace; + traits; + static assign(instance, values) { + const schema = Object.assign(instance, values); + return schema; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list = lhs; + return list.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } +} + +class ListSchema extends Schema { + static symbol = Symbol.for("@smithy/lis"); + valueSchema; + symbol = ListSchema.symbol; +} +const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema, +}); + +class MapSchema extends Schema { + static symbol = Symbol.for("@smithy/map"); + keySchema; + valueSchema; + symbol = MapSchema.symbol; +} +const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema, +}); + +class OperationSchema extends Schema { + static symbol = Symbol.for("@smithy/ope"); + input; + output; + symbol = OperationSchema.symbol; +} +const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output, +}); + +class StructureSchema extends Schema { + static symbol = Symbol.for("@smithy/str"); + memberNames; + memberList; + symbol = StructureSchema.symbol; +} +const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList, +}); + +class ErrorSchema extends StructureSchema { + static symbol = Symbol.for("@smithy/err"); + ctor; + symbol = ErrorSchema.symbol; +} +const error = (namespace, name, traits, memberNames, memberList, _ctor) => Schema.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor: null, +}); + +const traitsCache = []; +function translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + if (traitsCache[indicator]) { + return traitsCache[indicator]; + } + const traits = {}; + let i = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams", + ]) { + if (((indicator >> i++) & 1) === 1) { + traits[trait] = 1; + } + } + return (traitsCache[indicator] = traits); +} + +const anno = { + it: Symbol.for("@smithy/nor-struct-it"), + ns: Symbol.for("@smithy/ns"), +}; +const simpleSchemaCacheN = []; +const simpleSchemaCacheS = {}; +class NormalizedSchema { + ref; + memberName; + static symbol = Symbol.for("@smithy/nor"); + symbol = NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (isMemberSchema(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, translateTraits(traitSet)); + } + } + else { + this.memberTraits = 0; + } + if (schema instanceof NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema); + this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (isStaticSchema(this.schema)) { + this.name = `${this.schema[1]}#${this.schema[2]}`; + this.traits = this.schema[3]; + } + else { + this.name = this.memberName ?? String(schema); + this.traits = 0; + } + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const ns = lhs; + return ns.symbol === this.symbol; + } + return isPrototype; + } + static of(ref) { + const keyAble = typeof ref === "function" || (typeof ref === "object" && ref !== null); + if (typeof ref === "number") { + if (simpleSchemaCacheN[ref]) { + return simpleSchemaCacheN[ref]; + } + } + else if (typeof ref === "string") { + if (simpleSchemaCacheS[ref]) { + return simpleSchemaCacheS[ref]; + } + } + else if (keyAble) { + if (ref[anno.ns]) { + return ref[anno.ns]; + } + } + const sc = deref(ref); + if (sc instanceof NormalizedSchema) { + return sc; + } + if (isMemberSchema(sc)) { + const [ns, traits] = sc; + if (ns instanceof NormalizedSchema) { + Object.assign(ns.getMergedTraits(), translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + const ns = new NormalizedSchema(sc); + if (keyAble) { + return (ref[anno.ns] = ns); + } + if (typeof sc === "string") { + return (simpleSchemaCacheS[sc] = ns); + } + if (typeof sc === "number") { + return (simpleSchemaCacheN[sc] = ns); + } + return ns; + } + getSchema() { + const sc = this.schema; + if (Array.isArray(sc) && sc[0] === 0) { + return sc[4]; + } + return sc; + } + getName(withNamespace = false) { + const { name } = this; + const short = !withNamespace && name && name.includes("#"); + return short ? name.split("#")[1] : name || undefined; + } + getMemberName() { + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isListSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 64 && sc < 128 + : sc[0] === 1; + } + isMapSchema() { + const sc = this.getSchema(); + return typeof sc === "number" + ? sc >= 128 && sc <= 0b1111_1111 + : sc[0] === 2; + } + isStructSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + const id = sc[0]; + return (id === 3 || + id === -3 || + id === 4); + } + isUnionSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + return sc[0] === 4; + } + isBlobSchema() { + const sc = this.getSchema(); + return sc === 21 || sc === 42; + } + isTimestampSchema() { + const sc = this.getSchema(); + return (typeof sc === "number" && + sc >= 4 && + sc <= 7); + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isDocumentSchema() { + return this.getSchema() === 15; + } + isStringSchema() { + return this.getSchema() === 0; + } + isBooleanSchema() { + return this.getSchema() === 2; + } + isNumericSchema() { + return this.getSchema() === 1; + } + isBigIntegerSchema() { + return this.getSchema() === 17; + } + isBigDecimalSchema() { + return this.getSchema() === 19; + } + isStreaming() { + const { streaming } = this.getMergedTraits(); + return !!streaming || this.getSchema() === 42; + } + isIdempotencyToken() { + return !!this.getMergedTraits().idempotencyToken; + } + getMergedTraits() { + return (this.normalizedTraits ?? + (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits(), + })); + } + getMemberTraits() { + return translateTraits(this.memberTraits); + } + getOwnTraits() { + return translateTraits(this.traits); + } + getKeySchema() { + const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; + if (!isDoc && !isMap) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema = this.getSchema(); + const memberSchema = isDoc + ? 15 + : (schema[4] ?? 0); + return member([memberSchema, 0], "key"); + } + getValueSchema() { + const sc = this.getSchema(); + const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; + const memberSchema = typeof sc === "number" + ? 0b0011_1111 & sc + : sc && typeof sc === "object" && (isMap || isList) + ? sc[3 + sc[0]] + : isDoc + ? 15 + : void 0; + if (memberSchema != null) { + return member([memberSchema, 0], isMap ? "value" : "member"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + getMemberSchema(memberName) { + const struct = this.getSchema(); + if (this.isStructSchema() && struct[4].includes(memberName)) { + const i = struct[4].indexOf(memberName); + const memberSchema = struct[5][i]; + return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); + } + if (this.isDocumentSchema()) { + return member([15, 0], memberName); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`); + } + getMemberSchemas() { + const buffer = {}; + try { + for (const [k, v] of this.structIterator()) { + buffer[k] = v; + } + } + catch (ignored) { } + return buffer; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct = this.getSchema(); + const z = struct[4].length; + let it = struct[anno.it]; + if (it && z === it.length) { + yield* it; + return; + } + it = Array(z); + for (let i = 0; i < z; ++i) { + const k = struct[4][i]; + const v = member([struct[5][i], 0], k); + yield (it[i] = [k, v]); + } + struct[anno.it] = it; + } +} +function member(memberSchema, memberName) { + if (memberSchema instanceof NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true, + }); + } + const internalCtorAccess = NormalizedSchema; + return new internalCtorAccess(memberSchema, memberName); +} +const isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; +const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; + +class SimpleSchema extends Schema { + static symbol = Symbol.for("@smithy/sim"); + schemaRef; + symbol = SimpleSchema.symbol; +} +const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); +const simAdapter = (namespace, name, traits, schemaRef) => Schema.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef, +}); + +const SCHEMA = { + BLOB: 0b0001_0101, + STREAMING_BLOB: 0b0010_1010, + BOOLEAN: 0b0000_0010, + STRING: 0b0000_0000, + NUMERIC: 0b0000_0001, + BIG_INTEGER: 0b0001_0001, + BIG_DECIMAL: 0b0001_0011, + DOCUMENT: 0b0000_1111, + TIMESTAMP_DEFAULT: 0b0000_0100, + TIMESTAMP_DATE_TIME: 0b0000_0101, + TIMESTAMP_HTTP_DATE: 0b0000_0110, + TIMESTAMP_EPOCH_SECONDS: 0b0000_0111, + LIST_MODIFIER: 0b0100_0000, + MAP_MODIFIER: 0b1000_0000, +}; + +class TypeRegistry { + namespace; + schemas; + exceptions; + static registries = new Map(); + constructor(namespace, schemas = new Map(), exceptions = new Map()) { + this.namespace = namespace; + this.schemas = schemas; + this.exceptions = exceptions; + if (!TypeRegistry.registries.has(namespace)) { + TypeRegistry.registries.set(namespace, this); + } + } + static for(namespace) { + return TypeRegistry.registries.get(namespace) ?? new TypeRegistry(namespace); + } + copyFrom(other) { + const { schemas, exceptions } = this; + for (const [k, v] of other.schemas) { + if (!schemas.has(k)) { + schemas.set(k, v); + } + } + for (const [k, v] of other.exceptions) { + if (!exceptions.has(k)) { + exceptions.set(k, v); + } + } + } + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + for (const r of [this, TypeRegistry.for(qualifiedName.split("#")[0])]) { + if (!r.schemas.has(qualifiedName)) { + r.schemas.set(qualifiedName, schema); + } + } + } + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + if (!shapeId.includes("#")) { + const suffix = "#" + shapeId; + const candidates = []; + for (const [shapeId, schema] of this.schemas.entries()) { + if (shapeId.endsWith(suffix)) { + candidates.push(schema); + } + } + if (candidates.length === 1) { + return candidates[0]; + } + } + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + registerError(es, ctor) { + const $error = es; + const ns = $error[1]; + const qualifiedName = ns + "#" + $error[2]; + if (!ctor.hasOwnProperty?.("shapeId")) { + ctor.shapeId = qualifiedName; + } + for (const r of [this, TypeRegistry.for(ns)]) { + if (!r.schemas.has(qualifiedName) && !r.exceptions.has($error)) { + r.schemas.set(qualifiedName, $error); + r.exceptions.set($error, ctor); + } + } + } + getErrorCtor(es) { + const $error = es; + if (this.exceptions.has($error)) { + return this.exceptions.get($error); + } + const registry = TypeRegistry.for($error[1]); + return registry.exceptions.get($error); + } + getBaseException() { + for (const exceptionKey of this.exceptions.keys()) { + if (Array.isArray(exceptionKey)) { + const [, ns, name] = exceptionKey; + const id = ns + "#" + name; + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return exceptionKey; + } + } + } + return undefined; + } + find(predicate) { + for (const schema of this.schemas.values()) { + if (predicate(schema)) { + return schema; + } + } + return undefined; + } + clear() { + this.schemas.clear(); + this.exceptions.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } +} + +exports.ErrorSchema = ErrorSchema; +exports.ListSchema = ListSchema; +exports.MapSchema = MapSchema; +exports.NormalizedSchema = NormalizedSchema; +exports.OperationSchema = OperationSchema; +exports.SCHEMA = SCHEMA; +exports.Schema = Schema; +exports.SimpleSchema = SimpleSchema; +exports.StructureSchema = StructureSchema; +exports.TypeRegistry = TypeRegistry; +exports.deref = deref; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.error = error; +exports.getSchemaSerdePlugin = getSchemaSerdePlugin; +exports.isStaticSchema = isStaticSchema; +exports.list = list; +exports.map = map; +exports.op = op; +exports.operation = operation; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.sim = sim; +exports.simAdapter = simAdapter; +exports.simpleSchemaCacheN = simpleSchemaCacheN; +exports.simpleSchemaCacheS = simpleSchemaCacheS; +exports.struct = struct; +exports.traitsCache = traitsCache; +exports.translateTraits = translateTraits; + + +/***/ }), + +/***/ 34129: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { createHmac, createHash, getRandomValues } = __webpack_require__(77598); +const { hasOwn, HttpResponse } = __webpack_require__(30673); +exports.hasOwn = hasOwn; +const { ReadStream, lstatSync, fstatSync } = __webpack_require__(73024); +const { toEndpointV1 } = __webpack_require__(93846); +const { Readable, Writable, PassThrough } = __webpack_require__(57075); + +const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || + Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + +const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return Buffer.from(input, offset, length); +}; +const fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? Buffer.from(input, encoding) : Buffer.from(input); +}; + +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = fromString(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; + +const fromUtf8$1 = (input) => { + const buf = fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}; + +const toBase64$1 = (_input) => { + let input; + if (typeof _input === "string") { + input = fromUtf8$1(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; + +function bindUint8ArrayBlobAdapter(toUtf8, fromUtf8, toBase64, fromBase64) { + return class Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + if (typeof source === "string") { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate(fromBase64(source)); + } + return Uint8ArrayBlobAdapter.mutate(fromUtf8(source)); + } + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + static mutate(source) { + Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + if (encoding === "base64") { + return toBase64(this); + } + return toUtf8(this); + } + }; +} + +const toUtf8$1 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}; + +const decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bindV4(getRandomValues) { + if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { + return () => crypto.randomUUID(); + } + return () => { + const rnds = new Uint8Array(16); + getRandomValues(rnds); + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + return (decimalToHex[rnds[0]] + + decimalToHex[rnds[1]] + + decimalToHex[rnds[2]] + + decimalToHex[rnds[3]] + + "-" + + decimalToHex[rnds[4]] + + decimalToHex[rnds[5]] + + "-" + + decimalToHex[rnds[6]] + + decimalToHex[rnds[7]] + + "-" + + decimalToHex[rnds[8]] + + decimalToHex[rnds[9]] + + "-" + + decimalToHex[rnds[10]] + + decimalToHex[rnds[11]] + + decimalToHex[rnds[12]] + + decimalToHex[rnds[13]] + + decimalToHex[rnds[14]] + + decimalToHex[rnds[15]]); + }; +} + +const copyDocumentWithTransform = (source, _schemaRef, _transform = (_) => _) => source; + +const parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}; +const expectBoolean = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}; +const expectNumber = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}; +const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +const expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; +}; +const expectLong = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +const expectInt = expectLong; +const expectInt32 = (value) => expectSizedInt(value, 32); +const expectShort = (value) => expectSizedInt(value, 16); +const expectByte = (value) => expectSizedInt(value, 8); +const expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== undefined && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +const castInt = (value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}; +const expectNonNull = (value, location) => { + if (value === null || value === undefined) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; +}; +const expectObject = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}; +const expectString = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +const expectUnion = (value) => { + if (value === null || value === undefined) { + return undefined; + } + const asObject = expectObject(value); + const setKeys = []; + for (const k in asObject) { + if (!hasOwn(asObject, k)) + continue; + if (asObject[k] != null) { + setKeys.push(k); + } + } + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}; +const strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +const strictParseFloat = strictParseDouble; +const strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +const parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}; +const limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +const handleFloat = limitedParseDouble; +const limitedParseFloat = limitedParseDouble; +const limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +const parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}; +const strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +const strictParseInt = strictParseLong; +const strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +const strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +const strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +const stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message) + .split("\n") + .slice(0, 5) + .filter((s) => !s.includes("stackTraceWarning")) + .join("\n"); +}; +const logger = { + warn: console.warn, +}; + +const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +const parseRfc3339DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}; +const RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/); +const parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET$1.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date; +}; +const IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); +const ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); +const parseRfc7231DateTime = (value) => { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + match = RFC_850_DATE$1.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds, + })); + } + match = ASC_TIME$1.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +const parseEpochTimestamp = (value) => { + if (value === null || value === undefined) { + return undefined; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } + else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } + else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } + else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1000)); +}; +const buildDate = (year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); +}; +const parseTwoDigitYear = (value) => { + const thisYear = new Date().getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; +}; +const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; +const adjustRfc850Year = (input) => { + if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); + } + return input; +}; +const parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; +}; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const validateDayOfMonth = (year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; + } + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + } +}; +const isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}; +const parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}; +const parseMilliseconds = (value) => { + if (value === null || value === undefined) { + return 0; + } + return strictParseFloat32("0." + value) * 1000; +}; +const parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } + else if (directionStr == "-") { + direction = -1; + } + else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1000; +}; +const stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; + +const LazyJsonString = function LazyJsonString(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + }, + }); + return str; +}; +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } + else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); +}; +LazyJsonString.fromObject = LazyJsonString.from; + +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} + +const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; +const mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; +const time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; +const date = `(\\d?\\d)`; +const year = `(\\d{4})`; +const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); +const IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`); +const RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`); +const ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`); +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const _parseEpochTimestamp = (value) => { + if (value == null) { + return void 0; + } + let num = NaN; + if (typeof value === "number") { + num = value; + } + else if (typeof value === "string") { + if (!/^-?\d*\.?\d+$/.test(value)) { + throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); + } + num = Number.parseFloat(value); + } + else if (typeof value === "object" && value.tag === 1) { + num = value.value; + } + if (isNaN(num) || Math.abs(num) === Infinity) { + throw new TypeError("Epoch timestamps must be valid finite numbers."); + } + return new Date(Math.round(num * 1000)); +}; +const _parseRfc3339DateTimeWithOffset = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC3339 timestamps must be strings"); + } + const matches = RFC3339_WITH_OFFSET.exec(value); + if (!matches) { + throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); + } + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + range(monthStr, 1, 12); + range(dayStr, 1, 31); + range(hours, 0, 23); + range(minutes, 0, 59); + range(seconds, 0, 60); + const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); + date.setUTCFullYear(Number(yearStr)); + if (offsetStr.toUpperCase() != "Z") { + const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; + const scalar = sign === "-" ? 1 : -1; + date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); + } + return date; +}; +const _parseRfc7231DateTime = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC7231 timestamps must be strings."); + } + let day; + let month; + let year; + let hour; + let minute; + let second; + let fraction; + let matches; + if ((matches = IMF_FIXDATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + } + else if ((matches = RFC_850_DATE.exec(value))) { + [, day, month, year, hour, minute, second, fraction] = matches; + year = (Number(year) + 1900).toString(); + } + else if ((matches = ASC_TIME.exec(value))) { + [, month, day, hour, minute, second, fraction, year] = matches; + } + if (year && second) { + const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); + range(day, 1, 31); + range(hour, 0, 23); + range(minute, 0, 59); + range(second, 0, 60); + const date = new Date(timestamp); + date.setUTCFullYear(Number(year)); + return date; + } + throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); +}; +function range(v, min, max) { + const _v = Number(v); + if (_v < min || _v > max) { + throw new Error(`Value ${_v} out of range [${min}, ${max}]`); + } +} + +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; + } + else { + currentSegment += delimiter + segments[i]; + } + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} + +const splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = undefined; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } + break; + } + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z = v.length; + if (z < 2) { + return v; + } + if (v[0] === `"` && v[z - 1] === `"`) { + v = v.slice(1, z - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +const format = /^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; +class NumericValue { + string; + type; + constructor(string, type) { + this.string = string; + this.type = type; + if (!format.test(string)) { + throw new Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${string}"`); + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; + } + const _nv = object; + return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === "bigDecimal" && format.test(_nv.string)); + } +} +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} + +const SHORT_TO_HEX = {}; +const HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; +} +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } + else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; +} + +const calculateBodyLength = (body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } + else if (typeof body.byteLength === "number") { + return body.byteLength; + } + else if (typeof body.size === "number") { + return body.size; + } + else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } + else if (body instanceof ReadStream) { + if (body.path != null) { + return lstatSync(body.path).size; + } + else if (typeof body.fd === "number") { + return fstatSync(body.fd).size; + } + } + throw new Error(`Body Length computation failed for ${body}`); +}; + +const toUint8Array = (data) => { + if (data instanceof Uint8Array) { + return data; + } + if (typeof data === "string") { + return fromUtf8$1(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); +}; + +function concatBytes(arrays, length) { + if (length === undefined) { + length = 0; + for (const bytes of arrays) { + length += bytes.byteLength; + } + } + const result = new Uint8Array(length); + let offset = 0; + for (const buf of arrays) { + result.set(buf, offset); + offset += buf.byteLength; + } + return result; +} + +const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed, + }; + } + catch (error) { + Object.defineProperty(error, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false, + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } + catch (ignored) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } + else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), + }; + } + } + catch (ignored) { + } + } + throw error; + } +}; +const findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2 + ? async () => toEndpointV1(context.endpointV2) + : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request, + }); +}; + +const deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true, +}; +const serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true, +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + }, + }; +} + +class Hash { + algorithmIdentifier; + secret; + hash; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update(toUint8Array(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret + ? createHmac(this.algorithmIdentifier, castSourceData(this.secret)) + : createHash(this.algorithmIdentifier); + } +} +function castSourceData(toCast, encoding) { + if (Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return fromString(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return fromArrayBuffer(toCast); +} + +let ChecksumStream$1 = class ChecksumStream extends Readable { + expectedChecksum; + checksumSourceLocation; + checksum; + source; + base64Encoder; + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + super(); + if (typeof source.pipe !== "function") { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + this.source = source; + this.base64Encoder = base64Encoder ?? toBase64$1; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.on("data", this.onSourceData); + this.source.on("end", this.onSourceEnd); + this.source.on("error", this.onSourceError); + this.source.on("close", this.onSourceClose); + this.source.pause(); + } + onSourceData = (chunk) => { + if (this.destroyed) { + return; + } + try { + this.checksum.update(chunk); + } + catch (e) { + this.destroy(e); + return; + } + if (!this.push(chunk)) { + this.source.pause(); + } + }; + onSourceEnd = async () => { + if (this.destroyed) { + return; + } + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + return; + } + } + catch (e) { + this.destroy(e); + return; + } + this.push(null); + }; + onSourceError = (error) => { + this.destroy(error); + }; + onSourceClose = () => { + if (!this.destroyed && !this.source.readableEnded) { + this.destroy(new Error("Connection lost or stream closed before all data was received.")); + } + }; + _read(_size) { + this.source.resume(); + } + _destroy(error, callback) { + this.source?.removeListener("data", this.onSourceData); + this.source?.removeListener("end", this.onSourceEnd); + this.source?.removeListener("error", this.onSourceError); + this.source?.removeListener("close", this.onSourceClose); + this.source?.destroy(); + callback(error); + } +}; + +const isReadableStream = (stream) => typeof ReadableStream === "function" && + (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); +const isBlob = (blob) => { + return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); +}; + +const fromUtf8 = (input) => new TextEncoder().encode(input); + +const chars = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`; +Object.entries(chars).reduce((acc, [i, c]) => { + acc[c] = Number(i); + return acc; +}, {}); +const alphabetByValue = chars.split(""); +const bitsPerLetter = 6; +const bitsPerByte = 8; +const maxLetterValue = 0b111111; + +function toBase64(_input) { + let input; + if (typeof _input === "string") { + input = fromUtf8(_input); + } + else { + input = _input; + } + const isArrayLike = typeof input === "object" && typeof input.length === "number"; + const isUint8Array = typeof input === "object" && + typeof input.byteOffset === "number" && + typeof input.byteLength === "number"; + if (!isArrayLike && !isUint8Array) { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + let str = ""; + for (let i = 0; i < input.length; i += 3) { + let bits = 0; + let bitLength = 0; + for (let j = i, limit = Math.min(i + 3, input.length); j < limit; j++) { + bits |= input[j] << ((limit - j - 1) * bitsPerByte); + bitLength += bitsPerByte; + } + const bitClusterCount = Math.ceil(bitLength / bitsPerLetter); + bits <<= bitClusterCount * bitsPerLetter - bitLength; + for (let k = 1; k <= bitClusterCount; k++) { + const offset = (bitClusterCount - k) * bitsPerLetter; + str += alphabetByValue[(bits & (maxLetterValue << offset)) >> offset]; + } + str += "==".slice(0, 4 - bitClusterCount); + } + return str; +} + +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} + +const createChecksumStream$1 = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + if (!isReadableStream(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + const encoder = base64Encoder ?? toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream.prototype); + return readable; +}; + +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && isReadableStream(init.source)) { + return createChecksumStream$1(init); + } + return new ChecksumStream$1(init); +} + +class ByteArrayCollector { + allocByteArray; + byteLength = 0; + byteArrays = []; + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} + +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull, + }); +} +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + return chunk?.byteLength ?? chunk?.length ?? 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} + +function createBufferedReadable(upstream, size, logger) { + if (isReadableStream(upstream)) { + return createBufferedReadableStream(upstream, size, logger); + } + const downstream = new Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = modeOf(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push(flush(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} + +const getAwsChunkedEncodingStream$1 = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + bodyLengthChecker !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + Promise.resolve(digest).catch(() => { + }); + const reader = readableStream.getReader(); + return new ReadableStream({ + async pull(controller) { + const { value, done } = await reader.read(); + if (done) { + controller.enqueue(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + controller.enqueue(`${checksumLocationName}:${checksum}\r\n`); + controller.enqueue(`\r\n`); + } + controller.close(); + } + else { + controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\r\n${value}\r\n`); + } + }, + }); +}; + +function getAwsChunkedEncodingStream(stream, options) { + const readable = stream; + const readableStream = stream; + if (isReadableStream(readableStream)) { + return getAwsChunkedEncodingStream$1(readableStream, options); + } + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readable) : undefined; + Promise.resolve(digest).catch(() => { + }); + const awsChunkedEncodingStream = new Readable({ + read() { + readable.resume(); + }, + }); + readable.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + if (length === 0) { + return; + } + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + if (!awsChunkedEncodingStream.push("\r\n")) { + readable.pause(); + } + }); + readable.on("error", (err) => { + awsChunkedEncodingStream.destroy(err); + }); + readable.pause(); + readable.on("end", async () => { + try { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + } + catch (err) { + awsChunkedEncodingStream.destroy(err); + } + }); + return awsChunkedEncodingStream; +} + +async function headStream$1(stream, bytes) { + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += value?.byteLength ?? 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} + +const headStream = (stream, bytes) => { + if (isReadableStream(stream)) { + return headStream$1(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector$1(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = concatBytes(this.buffers); + resolve(bytes); + }); + }); +}; +let Collector$1 = class Collector extends Writable { + buffers = []; + limit = Infinity; + bytesBuffered = 0; + _write(chunk, encoding, callback) { + this.buffers.push(chunk); + this.bytesBuffered += chunk.byteLength ?? 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +}; + +const toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return new TextDecoder("utf-8").decode(input); +}; + +const streamCollector$1 = async (stream) => { + if (isBlob(stream)) { + return collectBlob(stream); + } + return collectReadableStream(stream); +}; +async function collectBlob(blob) { + return blob.arrayBuffer().then((ab) => new Uint8Array(ab)); +} +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let length = 0; + while (true) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + if (done) { + break; + } + } + return concatBytes(chunks, length); +} + +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1 = "The stream has already been transformed."; +const sdkStreamMixin$1 = (stream) => { + if (!isBlobInstance(stream) && !isReadableStream(stream)) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1); + } + transformed = true; + return await streamCollector$1(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return toBase64(buf); + } + else if (encoding === "hex") { + return toHex(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return toUtf8(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED$1); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if (isReadableStream(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; + +const streamCollector = (stream) => { + if (isBlob(stream)) { + return collectBlob(stream); + } + if (isReadableStream(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + const nodeStream = stream; + nodeStream.pipe(collector); + nodeStream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = concatBytes(this.bufferedBytes); + resolve(bytes); + }); + }); +}; +class Collector extends Writable { + bufferedBytes = []; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } +} + +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + if (!(stream instanceof Readable)) { + try { + return sdkStreamMixin$1(stream); + } + catch (ignored) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await streamCollector(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return Readable.toWeb(stream); + }, + }); +}; + +async function splitStream$1(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} + +async function splitStream(stream) { + if (isReadableStream(stream) || isBlob(stream)) { + return splitStream$1(stream); + } + const stream1 = new PassThrough(); + const stream2 = new PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} + +class Uint8ArrayBlobAdapter extends bindUint8ArrayBlobAdapter(toUtf8$1, fromUtf8$1, toBase64$1, fromBase64) { +} +const _getRandomValues = getRandomValues; +const v4 = bindV4(_getRandomValues); +const generateIdempotencyToken = v4; + +exports.ChecksumStream = ChecksumStream$1; +exports.Hash = Hash; +exports.LazyJsonString = LazyJsonString; +exports.NumericValue = NumericValue; +exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; +exports._parseEpochTimestamp = _parseEpochTimestamp; +exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset; +exports._parseRfc7231DateTime = _parseRfc7231DateTime; +exports.calculateBodyLength = calculateBodyLength; +exports.concatBytes = concatBytes; +exports.copyDocumentWithTransform = copyDocumentWithTransform; +exports.createBufferedReadable = createBufferedReadable; +exports.createChecksumStream = createChecksumStream; +exports.dateToUtcString = dateToUtcString; +exports.deserializerMiddleware = deserializerMiddleware; +exports.deserializerMiddlewareOption = deserializerMiddlewareOption; +exports.expectBoolean = expectBoolean; +exports.expectByte = expectByte; +exports.expectFloat32 = expectFloat32; +exports.expectInt = expectInt; +exports.expectInt32 = expectInt32; +exports.expectLong = expectLong; +exports.expectNonNull = expectNonNull; +exports.expectNumber = expectNumber; +exports.expectObject = expectObject; +exports.expectShort = expectShort; +exports.expectString = expectString; +exports.expectUnion = expectUnion; +exports.fromArrayBuffer = fromArrayBuffer; +exports.fromBase64 = fromBase64; +exports.fromHex = fromHex; +exports.fromString = fromString; +exports.fromUtf8 = fromUtf8$1; +exports.generateIdempotencyToken = generateIdempotencyToken; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +exports.getSerdePlugin = getSerdePlugin; +exports.handleFloat = handleFloat; +exports.headStream = headStream; +exports.isArrayBuffer = isArrayBuffer; +exports.isBlob = isBlob; +exports.isReadableStream = isReadableStream; +exports.limitedParseDouble = limitedParseDouble; +exports.limitedParseFloat = limitedParseFloat; +exports.limitedParseFloat32 = limitedParseFloat32; +exports.logger = logger; +exports.nv = nv; +exports.parseBoolean = parseBoolean; +exports.parseEpochTimestamp = parseEpochTimestamp; +exports.parseRfc3339DateTime = parseRfc3339DateTime; +exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; +exports.parseRfc7231DateTime = parseRfc7231DateTime; +exports.quoteHeader = quoteHeader; +exports.sdkStreamMixin = sdkStreamMixin; +exports.serializerMiddleware = serializerMiddleware; +exports.serializerMiddlewareOption = serializerMiddlewareOption; +exports.splitEvery = splitEvery; +exports.splitHeader = splitHeader; +exports.splitStream = splitStream; +exports.streamCollector = streamCollector; +exports.strictParseByte = strictParseByte; +exports.strictParseDouble = strictParseDouble; +exports.strictParseFloat = strictParseFloat; +exports.strictParseFloat32 = strictParseFloat32; +exports.strictParseInt = strictParseInt; +exports.strictParseInt32 = strictParseInt32; +exports.strictParseLong = strictParseLong; +exports.strictParseShort = strictParseShort; +exports.toBase64 = toBase64$1; +exports.toHex = toHex; +exports.toUint8Array = toUint8Array; +exports.toUtf8 = toUtf8$1; +exports.v4 = v4; + + +/***/ }), + +/***/ 30673: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { SMITHY_CONTEXT_KEY } = __webpack_require__(88867); + +const getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {}); + +function hasOwn(o, k) { + return Object.prototype.hasOwnProperty.call(o, k); +} + +class HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol + ? options.protocol.slice(-1) !== ":" + ? `${options.protocol}:` + : options.protocol + : "https:"; + this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new HttpRequest({ + ...request, + headers: { ...request.headers }, + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return ("method" in req && + "protocol" in req && + "hostname" in req && + "path" in req && + typeof req["query"] === "object" && + typeof req["headers"] === "object"); + } + clone() { + return HttpRequest.clone(this); + } +} +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param, + }; + }, {}); +} + +class HttpResponse { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } +} + +const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +const isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}; + +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9.-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}; + +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } + else if (Array.isArray(query[key])) { + query[key].push(value); + } + else { + query[key] = [query[key], value]; + } + } + } + return query; +} + +const parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = parseQueryString(search); + } + return { + hostname, + port: port ? parseInt(port) : undefined, + protocol, + path: pathname, + query, + }; +}; + +const toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + const v1Endpoint = parseUrl(endpoint.url); + if (endpoint.headers) { + v1Endpoint.headers = {}; + for (const name in endpoint.headers) { + if (!hasOwn(endpoint.headers, name)) + continue; + v1Endpoint.headers[name.toLowerCase()] = endpoint.headers[name].join(", "); + } + } + return v1Endpoint; + } + return endpoint; + } + return parseUrl(endpoint); +}; + +exports.HttpRequest = HttpRequest; +exports.HttpResponse = HttpResponse; +exports.getSmithyContext = getSmithyContext; +exports.hasOwn = hasOwn; +exports.isValidHostLabel = isValidHostLabel; +exports.isValidHostname = isValidHostname; +exports.normalizeProvider = normalizeProvider; +exports.parseQueryString = parseQueryString; +exports.parseUrl = parseUrl; +exports.toEndpointV1 = toEndpointV1; + + +/***/ }), + +/***/ 99236: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { ProviderError, CredentialsProviderError, loadConfig } = __webpack_require__(68702); +const node_http = __webpack_require__(37067); +const { parseUrl } = __webpack_require__(62049); + +const isImdsCredentials = (arg) => Boolean(arg) && + typeof arg === "object" && + typeof arg.AccessKeyId === "string" && + typeof arg.SecretAccessKey === "string" && + typeof arg.Token === "string" && + typeof arg.Expiration === "string"; +const fromImdsCredentials = (creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...(creds.AccountId && { accountId: creds.AccountId }), +}); + +const DEFAULT_TIMEOUT = 1000; +const DEFAULT_MAX_RETRIES = 0; +const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout }); + +function httpRequest(options) { + return new Promise((resolve, reject) => { + const req = node_http.request({ + method: "GET", + ...options, + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1"), + }); + req.on("error", (err) => { + reject(Object.assign(new ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new ProviderError("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || 300 <= statusCode) { + reject(Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve(Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); +} + +const retry = (toRetry, maxRetries) => { + let promise = toRetry(); + for (let i = 0; i < maxRetries; i++) { + promise = promise.catch(toRetry); + } + return promise; +}; + +const ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromContainerMetadata = (init = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); + } + return fromImdsCredentials(credsResponse); + }, maxRetries); +}; +const requestFromEcsImds = async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN], + }; + } + const buffer = await httpRequest({ + ...options, + timeout, + }); + return buffer.toString(); +}; +const CMDS_IP = "169.254.170.2"; +const GREENGRASS_HOSTS = new Set(["localhost", "127.0.0.1"]); +const GREENGRASS_PROTOCOLS = new Set(["http:", "https:"]); +const getCmdsUri = async ({ logger }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI], + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + let parsed; + try { + parsed = new URL(process.env[ENV_CMDS_FULL_URI]); + } + catch { + throw new CredentialsProviderError(`${process.env[ENV_CMDS_FULL_URI]} is not a valid container metadata service URL`, { tryNextLink: false, logger }); + } + if (!parsed.hostname || !GREENGRASS_HOSTS.has(parsed.hostname)) { + throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger, + }); + } + if (!parsed.protocol || !GREENGRASS_PROTOCOLS.has(parsed.protocol)) { + throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger, + }); + } + return { + protocol: parsed.protocol, + hostname: parsed.hostname, + path: parsed.pathname + parsed.search, + port: parsed.port ? parseInt(parsed.port, 10) : undefined, + }; + } + throw new CredentialsProviderError("The container metadata credential provider cannot be used unless" + + ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` + + " variable is set", { + tryNextLink: false, + logger, + }); +}; + +class InstanceMetadataV1FallbackError extends CredentialsProviderError { + tryNextLink; + name = "InstanceMetadataV1FallbackError"; + constructor(message, tryNextLink = true) { + super(message, tryNextLink); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); + } +} + +var Endpoint; +(function (Endpoint) { + Endpoint["IPv4"] = "http://169.254.169.254"; + Endpoint["IPv6"] = "http://[fd00:ec2::254]"; +})(Endpoint || (Endpoint = {})); + +const ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; +const CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; +const ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: undefined, +}; + +var EndpointMode; +(function (EndpointMode) { + EndpointMode["IPv4"] = "IPv4"; + EndpointMode["IPv6"] = "IPv6"; +})(EndpointMode || (EndpointMode = {})); + +const ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; +const CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; +const ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: EndpointMode.IPv4, +}; + +const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig())); +const getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)(); +const getFromEndpointModeConfig = async () => { + const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case EndpointMode.IPv4: + return Endpoint.IPv4; + case EndpointMode.IPv6: + return Endpoint.IPv6; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`); + } +}; + +const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; +const STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; +const STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; +const getExtendedInstanceMetadataCredentials = (credentials, logger) => { + const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); + const newExpiration = new Date(Date.now() + refreshInterval * 1000); + logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + + `credentials will be attempted after ${new Date(newExpiration)}.\nFor more information, please visit: ` + + STATIC_STABILITY_DOC_URL); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...(originalExpiration ? { originalExpiration } : {}), + expiration: newExpiration, + }; +}; + +const staticStabilityProvider = (provider, options = {}) => { + const logger = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger); + } + } + catch (e) { + if (pastCredentials) { + logger.warn("Credential renew failed: ", e); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } + else { + throw e; + } + } + pastCredentials = credentials; + return credentials; + }; +}; + +const IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; +const IMDS_TOKEN_PATH = "/latest/api/token"; +const AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; +const PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; +const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }); +const getInstanceMetadataProvider = (init = {}) => { + let disableFetchToken = false; + const { logger, profile } = init; + const { timeout, maxRetries } = providerConfigFromInit(init); + const getCredentials = async (maxRetries, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await loadConfig({ + environmentVariableSelector: (env) => { + const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === undefined) { + throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger }); + } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile) => { + const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; + return fallbackBlockedFromProfile; + }, + default: false, + }, { + profile, + })(); + if (init.ec2MetadataV1Disabled || configValue) { + const causes = []; + if (init.ec2MetadataV1Disabled) + causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); + if (fallbackBlockedFromProfile) + causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); + if (fallbackBlockedFromProcessEnv) + causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); + throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); + } + } + const imdsProfile = (await retry(async () => { + let profile; + try { + profile = await getProfile(options); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return profile; + }, maxRetries)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init); + } + catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return creds; + }, maxRetries); + }; + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + else { + let token; + try { + token = (await getMetadataToken({ ...endpoint, timeout })).toString(); + } + catch (error) { + if (error?.statusCode === 400) { + throw Object.assign(error, { + message: "EC2 Metadata token request returned error", + }); + } + else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { + disableFetchToken = true; + } + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + return getCredentials(maxRetries, { + ...endpoint, + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token, + }, + timeout, + }); + } + }; +}; +const getMetadataToken = async (options) => httpRequest({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600", + }, +}); +const getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(); +const getCredentialsFromProfile = async (profile, options, init) => { + const credentialsResponse = JSON.parse((await httpRequest({ + ...options, + path: IMDS_PATH + profile, + })).toString()); + if (!isImdsCredentials(credentialsResponse)) { + throw new CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger, + }); + } + return fromImdsCredentials(credentialsResponse); +}; + +exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; +exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; +exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; +exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; +exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; +exports.Endpoint = Endpoint; +exports.fromContainerMetadata = fromContainerMetadata; +exports.fromInstanceMetadata = fromInstanceMetadata; +exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; +exports.httpRequest = httpRequest; +exports.providerConfigFromInit = providerConfigFromInit; + + +/***/ }), + +/***/ 96363: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { buildQueryString, HttpResponse } = __webpack_require__(37015); +const { streamCollector } = __webpack_require__(26591); +exports.streamCollector = streamCollector; + +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} + +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); +} + +const keepAliveSupport = { + supported: undefined, +}; +class FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } + else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === undefined) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = buildAbortError(abortSignal); + return Promise.reject(abortError); + } + let path = request.path; + const queryString = buildQueryString(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? undefined : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method: method, + credentials, + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { }; + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != undefined; + if (!hasReadableStream) { + return response.blob().then((body) => ({ + response: new HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body, + }), + })); + } + return { + response: new HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body, + }), + }; + }), + requestTimeout(requestTimeoutInMs), + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve, reject) => { + const onAbort = () => { + const abortError = buildAbortError(abortSignal); + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } + else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} +function buildAbortError(abortSignal) { + const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal + ? abortSignal.reason + : undefined; + if (reason) { + if (reason instanceof Error) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + abortError.cause = reason; + return abortError; + } + const abortError = new Error(String(reason)); + abortError.name = "AbortError"; + return abortError; + } + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return abortError; +} + +exports.FetchHttpHandler = FetchHttpHandler; +exports.keepAliveSupport = keepAliveSupport; + + +/***/ }), + +/***/ 60517: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { hasOwn } = __webpack_require__(26591); +const { streamCollector } = __webpack_require__(26591); +exports.streamCollector = streamCollector; +const { buildQueryString, HttpResponse } = __webpack_require__(37015); +const node_https = __webpack_require__(44708); +const { Readable } = __webpack_require__(57075); +const http2 = __webpack_require__(32467); + +function buildAbortError(abortSignal) { + const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal + ? abortSignal.reason + : undefined; + if (reason) { + if (reason instanceof Error) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + abortError.cause = reason; + return abortError; + } + const abortError = new Error(String(reason)); + abortError.name = "AbortError"; + return abortError; + } + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return abortError; +} + +const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +const getTransformedHeaders = (headers) => { + const transformedHeaders = {}; + for (const name in headers) { + if (!hasOwn(headers, name)) + continue; + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; +}; + +const timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId), +}; + +const DEFER_EVENT_LISTENER_TIME$2 = 1000; +const setConnectionTimeout = (request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = (offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { + name: "TimeoutError", + })); + }, timeoutInMs - offset); + const doWithSocket = (socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } + else { + timing.clearTimeout(timeoutId); + } + }; + if (request.socket) { + doWithSocket(request.socket); + } + else { + request.on("socket", doWithSocket); + } + }; + if (timeoutInMs < 2000) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); +}; + +const setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => { + if (timeoutInMs) { + return timing.setTimeout(() => { + let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; + if (throwOnRequestTimeout) { + const error = Object.assign(new Error(msg), { + name: "TimeoutError", + code: "ETIMEDOUT", + }); + req.destroy(error); + reject(error); + } + else { + msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; + logger?.warn?.(msg); + } + }, timeoutInMs); + } + return -1; +}; + +const DEFER_EVENT_LISTENER_TIME$1 = 3000; +const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = () => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } + else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }; + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}; + +const DEFER_EVENT_LISTENER_TIME = 3000; +const setSocketTimeout = (request, reject, timeoutInMs = 0) => { + const registerTimeout = (offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = () => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); + }; + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } + else { + request.setTimeout(timeout, onTimeout); + } + }; + if (0 < timeoutInMs && timeoutInMs < 6000) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}; + +const MIN_WAIT_TIME = 6_000; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { + const headers = request.headers; + const expect = headers ? headers.Expect || headers.expect : undefined; + let timeoutId = -1; + let sendBody = true; + if (!externalAgent && expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }), + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +function writeBody(httpRequest, body) { + if (body instanceof Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + const isBuffer = Buffer.isBuffer(body); + const isString = typeof body === "string"; + if (isBuffer || isString) { + if (isBuffer && body.byteLength === 0) { + httpRequest.end(); + } + else { + httpRequest.end(body); + } + return; + } + const uint8 = body; + if (typeof uint8 === "object" && + uint8.buffer && + typeof uint8.byteOffset === "number" && + typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} + +const DEFAULT_REQUEST_TIMEOUT = 0; +let hAgent = undefined; +let hRequest = undefined; +class NodeHttpHandler { + config; + configProvider; + socketWarningTimestamp = 0; + externalAgent = false; + metadata = { handlerProtocol: "http/1.1" }; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttpHandler(instanceOrOptions); + } + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15_000; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + if (!hasOwn(sockets, origin)) + continue; + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }) + .catch(reject); + } + else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const config = this.config; + const logger = config.logger; + const isSSL = request.protocol === "https:"; + if (!isSSL && !this.config.httpAgent) { + this.config.httpAgent = await this.config.httpAgentProvider(); + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = undefined; + let socketWarningTimeoutId = -1; + let connectionTimeoutId = -1; + let requestTimeoutId = -1; + let socketTimeoutId = -1; + let keepAliveTimeoutId = -1; + const clearTimeouts = () => { + timing.clearTimeout(socketWarningTimeoutId); + timing.clearTimeout(connectionTimeoutId); + timing.clearTimeout(requestTimeoutId); + timing.clearTimeout(socketTimeoutId); + timing.clearTimeout(keepAliveTimeoutId); + }; + const resolve = async (arg) => { + await writeRequestBodyPromise; + clearTimeouts(); + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + clearTimeouts(); + _reject(arg); + }; + if (abortSignal?.aborted) { + const abortError = buildAbortError(abortSignal); + reject(abortError); + return; + } + const headers = request.headers; + const expectContinue = headers ? (headers.Expect ?? headers.expect) === "100-continue" : false; + let agent = isSSL ? config.httpsAgent : config.httpAgent; + if (expectContinue && !this.externalAgent) { + agent = new (isSSL ? node_https.Agent : hAgent)({ + keepAlive: false, + maxSockets: Infinity, + }); + } + socketWarningTimeoutId = timing.setTimeout(() => { + this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, logger); + }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000)); + const queryString = request.query ? buildQueryString(request.query) : ""; + let auth = undefined; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } + else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth, + }; + const requestFunc = isSSL ? node_https.request : hRequest; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res, + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } + else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = () => { + req.destroy(); + const abortError = buildAbortError(abortSignal); + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout; + connectionTimeoutId = setConnectionTimeout(req, reject, config.connectionTimeout); + requestTimeoutId = setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, logger ?? console); + socketTimeoutId = setSocketTimeout(req, reject, config.socketTimeout); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + keepAliveTimeoutId = setSocketKeepAlive(req, { + keepAlive: httpAgent.keepAlive, + keepAliveMsecs: httpAgent.keepAliveMsecs, + }); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => { + clearTimeouts(); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + if (key === Symbol.for("logger")) { + return { + ...config, + logger: config.logger ?? value, + }; + } + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger, } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout, + socketTimeout, + socketAcquisitionWarningTimeout, + throwOnRequestTimeout, + httpAgentProvider: async () => { + const node_http = __webpack_require__(37067); + const { Agent, request } = node_http.default ?? node_http; + hRequest = request; + hAgent = Agent; + if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") { + this.externalAgent = true; + return httpAgent; + } + return new hAgent({ keepAlive, maxSockets, ...httpAgent }); + }, + httpsAgent: (() => { + if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === "function") { + this.externalAgent = true; + return httpsAgent; + } + return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger, + }; + } +} + +const ids = new Uint16Array(1); +class ClientHttp2SessionRef { + id = ids[0]++; + total = 0; + max = 0; + session; + refs = 0; + constructor(session) { + session.unref(); + this.session = session; + } + retain() { + if (this.session.destroyed) { + throw new Error("@smithy/node-http-handler - cannot acquire reference to destroyed session."); + } + this.refs += 1; + this.total += 1; + this.max = Math.max(this.refs, this.max); + this.session.ref(); + } + free() { + if (this.session.destroyed) { + return; + } + this.refs -= 1; + if (this.refs === 0) { + this.session.unref(); + } + if (this.refs < 0) { + throw new Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement."); + } + } + deref() { + return this.session; + } + close() { + if (!this.session.closed) { + this.session.close(); + } + } + destroy() { + this.refs = 0; + if (!this.session.destroyed) { + this.session.setTimeout(0); + this.session.destroy(); + } + } + useCount() { + return this.refs; + } +} + +class NodeHttp2ConnectionPool { + sessions = []; + maxConcurrency = 0; + constructor(sessions) { + this.sessions = (sessions ?? []).map((session) => new ClientHttp2SessionRef(session)); + } + poll() { + let cleanup = false; + for (const session of this.sessions) { + if (session.deref().destroyed) { + cleanup = true; + continue; + } + if (!this.maxConcurrency || session.useCount() < this.maxConcurrency) { + return session; + } + } + if (cleanup) { + for (const session of this.sessions) { + if (session.deref().destroyed) { + this.remove(session); + } + } + } + } + offerLast(ref) { + this.sessions.push(ref); + } + remove(ref) { + const ix = this.sessions.indexOf(ref); + if (ix > -1) { + this.sessions.splice(ix, 1); + } + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + setMaxConcurrency(maxConcurrency) { + this.maxConcurrency = maxConcurrency; + } + destroy(ref) { + this.remove(ref); + ref.destroy(); + } +} + +class NodeHttp2ConnectionManager { + config; + connectOptions; + connectionPools = new Map(); + constructor(config) { + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const pool = this.getPool(url); + if (!this.config.disableConcurrency && !connectionConfiguration.isEventStream) { + const available = pool.poll(); + if (available) { + available.retain(); + return available; + } + } + const ref = new ClientHttp2SessionRef(this.connect(url)); + const session = ref.deref(); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error("Fail to set maxConcurrentStreams to " + + this.config.maxConcurrency + + "when creating new session for " + + requestContext.destination.toString()); + } + }); + } + const graceful = () => { + this.removeFromPoolAndClose(url, ref); + }; + const ensureDestroyed = () => { + this.removeFromPoolAndCheckedDestroy(url, ref); + }; + session.on("goaway", graceful); + session.on("error", ensureDestroyed); + session.on("frameError", ensureDestroyed); + session.on("close", ensureDestroyed); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, ensureDestroyed); + } + pool.offerLast(ref); + ref.retain(); + return ref; + } + release(_requestContext, ref) { + ref.free(); + } + createIsolatedSession(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const ref = new ClientHttp2SessionRef(this.connect(url)); + const session = ref.deref(); + session.settings({ maxConcurrentStreams: 1 }); + const ensureDestroyed = () => { + ref.destroy(); + }; + session.on("error", ensureDestroyed); + session.on("frameError", ensureDestroyed); + session.on("close", ensureDestroyed); + const timeout = connectionConfiguration.requestTimeout ?? 300_000; + session.setTimeout(timeout, ensureDestroyed); + ref.retain(); + return ref; + } + destroy() { + for (const [url, connectionPool] of this.connectionPools) { + for (const session of [...connectionPool]) { + session.destroy(); + } + this.connectionPools.delete(url); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + for (const pool of this.connectionPools.values()) { + pool.setMaxConcurrency(maxConcurrentStreams); + } + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions) { + this.connectOptions = nodeHttp2ConnectOptions; + } + debug() { + const pools = {}; + for (const [url, pool] of this.connectionPools) { + const sessions = []; + for (const ref of pool) { + sessions.push({ + id: ref.id, + active: ref.useCount(), + maxConcurrent: ref.max, + totalRequests: ref.total, + }); + } + pools[url] = { sessions }; + } + return pools; + } + removeFromPoolAndClose(authority, ref) { + this.connectionPools.get(authority)?.remove(ref); + ref.close(); + } + removeFromPoolAndCheckedDestroy(authority, ref) { + this.connectionPools.get(authority)?.remove(ref); + ref.destroy(); + } + getPool(url) { + if (!this.connectionPools.has(url)) { + const pool = new NodeHttp2ConnectionPool(); + if (this.config.maxConcurrency) { + pool.setMaxConcurrency(this.config.maxConcurrency); + } + this.connectionPools.set(url, pool); + } + return this.connectionPools.get(url); + } + getUrlString(request) { + return request.destination.toString(); + } + connect(url) { + return this.connectOptions === undefined ? http2.connect(url) : http2.connect(url, this.connectOptions); + } +} + +const { constants } = http2; +class NodeHttp2Handler { + config; + configProvider; + metadata = { handlerProtocol: "h2" }; + connectionManager = new NodeHttp2ConnectionManager({}); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new NodeHttp2Handler(instanceOrOptions); + } + constructor(options) { + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options() + .then((opts) => { + resolve(opts || {}); + }) + .catch(reject); + } + else { + resolve(options || {}); + } + }); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout, isEventStream } = {}) { + if (!this.config) { + this.config = await this.configProvider; + const { disableConcurrentStreams, maxConcurrentStreams, nodeHttp2ConnectOptions } = this.config; + this.connectionManager.setDisableConcurrentStreams(disableConcurrentStreams ?? false); + if (maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(maxConcurrentStreams); + } + if (nodeHttp2ConnectOptions) { + this.connectionManager.setNodeHttp2ConnectOptions(nodeHttp2ConnectOptions); + } + } + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const useIsolatedSession = disableConcurrentStreams || isEventStream; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = undefined; + const resolve = async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }; + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = buildAbortError(abortSignal); + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const connectConfig = { + requestTimeout: this.config?.sessionTimeout, + isEventStream, + }; + const ref = useIsolatedSession + ? this.connectionManager.createIsolatedSession(requestContext, connectConfig) + : this.connectionManager.lease(requestContext, connectConfig); + const session = ref.deref(); + const rejectWithDestroy = (err) => { + if (useIsolatedSession) { + ref.destroy(); + } + fulfilled = true; + reject(err); + }; + const queryString = query ? buildQueryString(query) : ""; + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const clientHttp2Stream = session.request({ + ...request.headers, + [constants.HTTP2_HEADER_PATH]: path, + [constants.HTTP2_HEADER_METHOD]: method, + }); + if (effectiveRequestTimeout) { + clientHttp2Stream.setTimeout(effectiveRequestTimeout, () => { + clientHttp2Stream.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = () => { + clientHttp2Stream.close(); + const abortError = buildAbortError(abortSignal); + rejectWithDestroy(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + clientHttp2Stream.once("close", () => signal.removeEventListener("abort", onAbort)); + } + else { + abortSignal.onabort = onAbort; + } + } + clientHttp2Stream.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + clientHttp2Stream.on("error", rejectWithDestroy); + clientHttp2Stream.on("aborted", () => { + rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${clientHttp2Stream.rstCode}.`)); + }); + clientHttp2Stream.on("response", (headers) => { + const httpResponse = new HttpResponse({ + statusCode: headers[":status"] ?? -1, + headers: getTransformedHeaders(headers), + body: clientHttp2Stream, + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (useIsolatedSession) { + session.close(); + clientHttp2Stream.on("end", () => { + ref.destroy(); + }); + } + }); + clientHttp2Stream.on("close", () => { + if (useIsolatedSession) { + ref.destroy(); + } + else { + this.connectionManager.release(requestContext, ref); + } + if (!fulfilled) { + const error = new Error("Unexpected error: http2 request did not get a response"); + if (session.destroyed) { + error.name = "TimeoutError"; + } + rejectWithDestroy(error); + } + }); + writeRequestBodyPromise = writeRequestBody(clientHttp2Stream, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = undefined; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value, + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +} + +exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; +exports.NodeHttp2Handler = NodeHttp2Handler; +exports.NodeHttpHandler = NodeHttpHandler; + + +/***/ }), + +/***/ 10262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { hasOwn, fromUtf8, fromHex, toHex, toUint8Array, isArrayBuffer } = __webpack_require__(26591); +const { normalizeProvider } = __webpack_require__(40417); +const { escapeUri, HttpRequest } = __webpack_require__(37015); + +class HeaderFormatter { + format(headers) { + const chunks = []; + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + const bytes = fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex(header.value.replace(/-/g, "")), 1); + return uuidBytes; + } + } +} +var HEADER_VALUE_TYPE; +(function (HEADER_VALUE_TYPE) { + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"] = 3] = "short"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"] = 5] = "long"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"] = 7] = "string"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"] = 9] = "uuid"; +})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +const AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +const EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +const SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +const TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +const REGION_SET_PARAM = "X-Amz-Region-Set"; +const AUTH_HEADER = "authorization"; +const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +const DATE_HEADER = "date"; +const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +const SHA256_HEADER = "x-amz-content-sha256"; +const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +const HOST_HEADER = "host"; +const ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true, +}; +const PROXY_HEADER_PATTERN = /^proxy-/; +const SEC_HEADER_PATTERN = /^sec-/; +const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; +const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; +const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +const MAX_CACHE_SIZE = 50; +const KEY_TYPE_IDENTIFIER = "aws4_request"; +const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +const getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key in query) { + if (!hasOwn(query, key)) + continue; + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`; + } + else if (Array.isArray(value)) { + serialized[encodedKey] = value + .slice(0) + .reduce((encoded, value) => encoded.concat([`${encodedKey}=${escapeUri(value)}`]), []) + .sort() + .join("&"); + } + } + return keys + .sort() + .map((key) => serialized[key]) + .filter((serialized) => serialized) + .join("&"); +}; + +const iso8601 = (time) => toDate(time) + .toISOString() + .replace(/\.\d{3}Z$/, "Z"); +const toDate = (time) => { + if (typeof time === "number") { + return new Date(time * 1000); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1000); + } + return new Date(time); + } + return time; +}; + +class SignatureV4Base { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = normalizeProvider(region); + this.credentialProvider = normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update(toUint8Array(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${toHex(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } + else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || + typeof credentials.accessKeyId !== "string" || + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now) { + const longDate = iso8601(now).replace(/[-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8), + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } +} + +const signingKeyCache = {}; +const cacheQueue = []; +const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; +const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return (signingKeyCache[cacheKey] = key); +}; +const clearCredentialCache = () => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}; +const hmac = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(toUint8Array(data)); + return hash.digest(); +}; + +const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == undefined) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || + unsignableHeaders?.has(canonicalHeaderName) || + PROXY_HEADER_PATTERN.test(canonicalHeaderName) || + SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; +}; + +const getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == undefined) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } + else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(toUint8Array(body)); + return toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}; + +const hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}; + +const moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = HttpRequest.clone(request); + for (const name in headers) { + if (!hasOwn(headers, name)) + continue; + const lname = name.toLowerCase(); + if ((lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) || + options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query, + }; +}; + +const prepareRequest = (request) => { + request = HttpRequest.clone(request); + for (const headerName in request.headers) { + if (!hasOwn(request.headers, headerName)) + continue; + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}; + +class SignatureV4 extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath, + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } + else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } + else if (toSign.message) { + return this.signMessage(toSign, options); + } + else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService, eventStreamCredentials, }) { + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = toHex(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload, + ].join("\n"); + return this.signString(stringToSign, { + signingDate, + signingRegion: region, + signingService, + eventStreamCredentials, + }); + } + async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService, eventStreamCredentials }) { + const promise = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body, + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature, + eventStreamCredentials, + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService, eventStreamCredentials, } = {}) { + const credentials = eventStreamCredentials ?? (await this.credentialProvider()); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = + `${ALGORITHM_IDENTIFIER} ` + + `Credential=${credentials.accessKeyId}/${scope}, ` + + `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + + `Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash = new this.sha256(await keyPromise); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } +} + +const signatureV4aContainer = { + SignatureV4a: null, +}; + +exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; +exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; +exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; +exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; +exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; +exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; +exports.AUTH_HEADER = AUTH_HEADER; +exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; +exports.DATE_HEADER = DATE_HEADER; +exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; +exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; +exports.GENERATED_HEADERS = GENERATED_HEADERS; +exports.HOST_HEADER = HOST_HEADER; +exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; +exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; +exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; +exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; +exports.REGION_SET_PARAM = REGION_SET_PARAM; +exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; +exports.SHA256_HEADER = SHA256_HEADER; +exports.SIGNATURE_HEADER = SIGNATURE_HEADER; +exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; +exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; +exports.SignatureV4 = SignatureV4; +exports.SignatureV4Base = SignatureV4Base; +exports.TOKEN_HEADER = TOKEN_HEADER; +exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; +exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; +exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; +exports.clearCredentialCache = clearCredentialCache; +exports.createScope = createScope; +exports.getCanonicalHeaders = getCanonicalHeaders; +exports.getCanonicalQuery = getCanonicalQuery; +exports.getPayloadHash = getPayloadHash; +exports.getSigningKey = getSigningKey; +exports.hasHeader = hasHeader; +exports.moveHeadersToQuery = moveHeadersToQuery; +exports.prepareRequest = prepareRequest; +exports.signatureV4aContainer = signatureV4aContainer; + + +/***/ }), + +/***/ 82961: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +const { hasOwn, fromUtf8, fromHex, toHex, toUint8Array, isArrayBuffer } = __webpack_require__(34129); +const { normalizeProvider } = __webpack_require__(20895); +const { escapeUri, HttpRequest } = __webpack_require__(62049); + +class HeaderFormatter { + format(headers) { + const chunks = []; + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + const bytes = fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex(header.value.replace(/-/g, "")), 1); + return uuidBytes; + } + } +} +var HEADER_VALUE_TYPE; +(function (HEADER_VALUE_TYPE) { + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"] = 3] = "short"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"] = 5] = "long"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"] = 7] = "string"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"] = 9] = "uuid"; +})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); +const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 0b10000000; + if (negative) { + negate(bytes); + } + return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 0xff; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} + +const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +const AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +const EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +const SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +const TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +const REGION_SET_PARAM = "X-Amz-Region-Set"; +const AUTH_HEADER = "authorization"; +const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +const DATE_HEADER = "date"; +const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +const SHA256_HEADER = "x-amz-content-sha256"; +const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +const HOST_HEADER = "host"; +const ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true, +}; +const PROXY_HEADER_PATTERN = /^proxy-/; +const SEC_HEADER_PATTERN = /^sec-/; +const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; +const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; +const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +const MAX_CACHE_SIZE = 50; +const KEY_TYPE_IDENTIFIER = "aws4_request"; +const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +const getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key in query) { + if (!hasOwn(query, key)) + continue; + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`; + } + else if (Array.isArray(value)) { + serialized[encodedKey] = value + .slice(0) + .reduce((encoded, value) => encoded.concat([`${encodedKey}=${escapeUri(value)}`]), []) + .sort() + .join("&"); + } + } + return keys + .sort() + .map((key) => serialized[key]) + .filter((serialized) => serialized) + .join("&"); +}; + +const iso8601 = (time) => toDate(time) + .toISOString() + .replace(/\.\d{3}Z$/, "Z"); +const toDate = (time) => { + if (typeof time === "number") { + return new Date(time * 1000); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1000); + } + return new Date(time); + } + return time; +}; + +class SignatureV4Base { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = normalizeProvider(region); + this.credentialProvider = normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update(toUint8Array(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${toHex(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } + else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || + typeof credentials.accessKeyId !== "string" || + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now) { + const longDate = iso8601(now).replace(/[-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8), + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } +} + +const signingKeyCache = {}; +const cacheQueue = []; +const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; +const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return (signingKeyCache[cacheKey] = key); +}; +const clearCredentialCache = () => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}; +const hmac = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(toUint8Array(data)); + return hash.digest(); +}; + +const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == undefined) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || + unsignableHeaders?.has(canonicalHeaderName) || + PROXY_HEADER_PATTERN.test(canonicalHeaderName) || + SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName] + .replace(/[\r\n]/g, " ") + .replace(/[ \t]+/g, " ") + .replace(/^ | $/g, ""); + } + return canonical; +}; + +const getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == undefined) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } + else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(toUint8Array(body)); + return toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}; + +const hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName in headers) { + if (!hasOwn(headers, headerName)) + continue; + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}; + +const moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = HttpRequest.clone(request); + for (const name in headers) { + if (!hasOwn(headers, name)) + continue; + const lname = name.toLowerCase(); + if ((lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) || + options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query, + }; +}; + +const prepareRequest = (request) => { + request = HttpRequest.clone(request); + for (const headerName in request.headers) { + if (!hasOwn(request.headers, headerName)) + continue; + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}; + +class SignatureV4 extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath, + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } + else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } + else if (toSign.message) { + return this.signMessage(toSign, options); + } + else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService, eventStreamCredentials, }) { + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = toHex(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload, + ].join("\n"); + return this.signString(stringToSign, { + signingDate, + signingRegion: region, + signingService, + eventStreamCredentials, + }); + } + async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService, eventStreamCredentials }) { + const promise = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body, + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature, + eventStreamCredentials, + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService, eventStreamCredentials, } = {}) { + const credentials = eventStreamCredentials ?? (await this.credentialProvider()); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? (await this.regionProvider()); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = + `${ALGORITHM_IDENTIFIER} ` + + `Credential=${credentials.accessKeyId}/${scope}, ` + + `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + + `Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash = new this.sha256(await keyPromise); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } +} + +const signatureV4aContainer = { + SignatureV4a: null, +}; + +exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; +exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; +exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; +exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; +exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; +exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; +exports.AUTH_HEADER = AUTH_HEADER; +exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; +exports.DATE_HEADER = DATE_HEADER; +exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; +exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; +exports.GENERATED_HEADERS = GENERATED_HEADERS; +exports.HOST_HEADER = HOST_HEADER; +exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; +exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; +exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; +exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; +exports.REGION_SET_PARAM = REGION_SET_PARAM; +exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; +exports.SHA256_HEADER = SHA256_HEADER; +exports.SIGNATURE_HEADER = SIGNATURE_HEADER; +exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; +exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; +exports.SignatureV4 = SignatureV4; +exports.SignatureV4Base = SignatureV4Base; +exports.TOKEN_HEADER = TOKEN_HEADER; +exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; +exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; +exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; +exports.clearCredentialCache = clearCredentialCache; +exports.createScope = createScope; +exports.getCanonicalHeaders = getCanonicalHeaders; +exports.getCanonicalQuery = getCanonicalQuery; +exports.getPayloadHash = getPayloadHash; +exports.getSigningKey = getSigningKey; +exports.hasHeader = hasHeader; +exports.moveHeadersToQuery = moveHeadersToQuery; +exports.prepareRequest = prepareRequest; +exports.signatureV4aContainer = signatureV4aContainer; + + +/***/ }), + +/***/ 88867: +/***/ ((__unused_webpack_module, exports) => { + +var HttpAuthLocation; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(HttpAuthLocation || (HttpAuthLocation = {})); + +var HttpApiKeyAuthLocation; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {})); + +var EndpointURLScheme; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(EndpointURLScheme || (EndpointURLScheme = {})); + +var AlgorithmId; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(AlgorithmId || (AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, + }); + } + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +var FieldPosition; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(FieldPosition || (FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +var IniSectionType; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(IniSectionType || (IniSectionType = {})); + +var RequestHandlerProtocol; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(RequestHandlerProtocol || (RequestHandlerProtocol = {})); + +exports.AlgorithmId = AlgorithmId; +exports.EndpointURLScheme = EndpointURLScheme; +exports.FieldPosition = FieldPosition; +exports.HttpApiKeyAuthLocation = HttpApiKeyAuthLocation; +exports.HttpAuthLocation = HttpAuthLocation; +exports.IniSectionType = IniSectionType; +exports.RequestHandlerProtocol = RequestHandlerProtocol; +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; + + +/***/ }), + +/***/ 97458: +/***/ (function(module) { + +!function(e,t){ true?module.exports=t():0}(this,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var i=r(18),n=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));t.push(0);var r=t[0],i=t[1];if(10===r)switch(i){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,i){void 0===i&&(i=!1);var n=e.getVersionPrecision(t),a=e.getVersionPrecision(r),o=Math.max(n,a),s=0,u=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),i=t+new Array(r+1).join(".0");return e.map(i.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(i&&(s=o-Math.min(n,a)),o-=1;o>=s;){if(u[0][o]>u[1][o])return 1;if(u[0][o]===u[1][o]){if(o===s)return 0;o-=1}else if(u[0][o]1?n-1:0),o=1;o0){var o=Object.keys(r),u=s.default.find(o,(function(e){return t.isOS(e)}));if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d}var c=s.default.find(o,(function(e){return t.isPlatform(e)}));if(c){var f=this.satisfies(r[c]);if(void 0!==f)return f}}if(a>0){var l=Object.keys(n),b=s.default.find(l,(function(e){return t.isBrowser(e,!0)}));if(void 0!==b)return this.compareVersion(n[b])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),i=e.toLowerCase(),n=s.default.getBrowserTypeByAlias(i);return t&&n&&(i=n.toLowerCase()),i===r},t.compareVersion=function(e){var t=[0],r=e,i=!1,n=this.getBrowserVersion();if("string"==typeof n)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(i=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(i=!0,r=e.substr(1)),t.indexOf(s.default.compareVersions(n,r,i))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default},92:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var i,n=(i=r(17))&&i.__esModule?i:{default:i};var a=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/gptbot/i],describe:function(e){var t={name:"GPTBot"},r=n.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/chatgpt-user/i],describe:function(e){var t={name:"ChatGPT-User"},r=n.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/oai-searchbot/i],describe:function(e){var t={name:"OAI-SearchBot"},r=n.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(e){var t={name:"ClaudeBot"},r=n.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(e){var t={name:"Omgilibot"},r=n.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/diffbot/i],describe:function(e){var t={name:"Diffbot"},r=n.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/perplexitybot/i],describe:function(e){var t={name:"PerplexityBot"},r=n.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/perplexity-user/i],describe:function(e){var t={name:"Perplexity-User"},r=n.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/youbot/i],describe:function(e){var t={name:"YouBot"},r=n.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/meta-webindexer/i],describe:function(e){var t={name:"Meta-WebIndexer"},r=n.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/meta-externalads/i],describe:function(e){var t={name:"Meta-ExternalAds"},r=n.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/meta-externalagent/i],describe:function(e){var t={name:"Meta-ExternalAgent"},r=n.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/meta-externalfetcher/i],describe:function(e){var t={name:"Meta-ExternalFetcher"},r=n.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=n.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/linespider/i],describe:function(e){var t={name:"Linespider"},r=n.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/amazonbot/i],describe:function(e){var t={name:"AmazonBot"},r=n.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/bingbot/i],describe:function(e){var t={name:"BingCrawler"},r=n.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/baiduspider/i],describe:function(e){var t={name:"BaiduSpider"},r=n.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/duckduckbot/i],describe:function(e){var t={name:"DuckDuckBot"},r=n.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/ia_archiver/i],describe:function(e){var t={name:"InternetArchiveCrawler"},r=n.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(e){var t={name:"SlackBot"},r=n.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=n.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/PaleMoon/i],describe:function(e){var t={name:"Pale Moon"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=n.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=n.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=n.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=n.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=n.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=n.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=n.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=n.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=n.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=n.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=n.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=n.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=n.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=n.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=n.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=n.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=n.default.getFirstMatch(a,e)||n.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=n.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=n.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=n.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/librewolf/i],describe:function(e){var t={name:"LibreWolf"},r=n.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=n.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=n.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(e){var t={name:"Sogou Browser"},r=n.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,e),i=n.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),a=n.default.getFirstMatch(/se ([\d.]+)x/i,e),o=r||i||a;return o&&(t.version=o),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=n.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return!!e.hasBrand("DuckDuckGo")||e.test(/\sDdg\/[\d.]+$/i)},describe:function(e,t){var r={name:"DuckDuckGo"};if(t){var i=t.getBrandVersion("DuckDuckGo");if(i)return r.version=i,r}var a=n.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,e);return a&&(r.version=a),r}},{test:function(e){return e.hasBrand("Brave")},describe:function(e,t){var r={name:"Brave"};if(t){var i=t.getBrandVersion("Brave");if(i)return r.version=i,r}return r}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=n.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=n.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=n.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=n.default.getFirstMatch(a,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:n.default.getFirstMatch(t,e),version:n.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var i,n=(i=r(17))&&i.__esModule?i:{default:i},a=r(18);var o=[{test:[/Roku\/DVP/],describe:function(e){var t=n.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:a.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=n.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=n.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=n.default.getWindowsVersionName(t);return{name:a.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:a.OS_MAP.iOS},r=n.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=n.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=n.default.getMacOSVersionName(t),i={name:a.OS_MAP.MacOS,version:t};return r&&(i.versionName=r),i}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=n.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:a.OS_MAP.iOS,version:t}}},{test:[/OpenHarmony/i],describe:function(e){var t=n.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.HarmonyOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=n.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=n.default.getAndroidVersionName(t),i={name:a.OS_MAP.Android,version:t};return r&&(i.versionName=r),i}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=n.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:a.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=n.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||n.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||n.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:a.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=n.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=n.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:a.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:a.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=n.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var i,n=(i=r(17))&&i.__esModule?i:{default:i},a=r(18);var o=[{test:[/googlebot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:a.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(e){var t=n.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:a.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=n.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:a.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(e){var t=n.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,e),r={type:a.PLATFORMS_MAP.mobile,vendor:"Nokia"};return t&&(r.model=t),r}},{test:[/[^-]mobi/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var i,n=(i=r(17))&&i.__esModule?i:{default:i},a=r(18);var o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:a.ENGINE_MAP.Blink};var t=n.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:a.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:a.ENGINE_MAP.Trident},r=n.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:a.ENGINE_MAP.Presto},r=n.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:a.ENGINE_MAP.Gecko},r=n.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:a.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:a.ENGINE_MAP.WebKit},r=n.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}})})); + +/***/ }), + +/***/ 29758: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + bedrockProviderModule: () => (/* binding */ bedrockProviderModule) +}); + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@aws-sdk+client-bedrock-runtime@3.1127.0/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js +var dist_cjs = __webpack_require__(99527); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@smithy+node-http-handler@4.12.1/node_modules/@smithy/node-http-handler/dist-cjs/index.js +var node_http_handler_dist_cjs = __webpack_require__(60517); +// EXTERNAL MODULE: external "net" +var external_net_ = __webpack_require__(69278); +// EXTERNAL MODULE: external "tls" +var external_tls_ = __webpack_require__(64756); +// EXTERNAL MODULE: ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js +var src = __webpack_require__(26675); +// EXTERNAL MODULE: external "events" +var external_events_ = __webpack_require__(24434); +// EXTERNAL MODULE: external "http" +var external_http_ = __webpack_require__(58611); +// EXTERNAL MODULE: external "https" +var external_https_ = __webpack_require__(65692); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/agent-base@9.0.0/node_modules/agent-base/dist/helpers.js + + +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString('utf8'); + try { + return JSON.parse(str); + } + catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } +} +function req(url, opts = {}) { + const href = typeof url === 'string' ? url : url.href; + const req = (href.startsWith('https:') ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req + .once('response', resolve) + .once('error', reject) + .end(); + }); + req.then = promise.then.bind(promise); + return req; +} +//# sourceMappingURL=helpers.js.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/agent-base@9.0.0/node_modules/agent-base/dist/index.js + + + + +const INTERNAL = Symbol('AgentBaseInternalState'); +class Agent extends external_http_.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof options.secureEndpoint === 'boolean') { + return options.secureEndpoint; + } + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } + } + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack + .split('\n') + .some((l) => l.indexOf('(https.js:') !== -1 || + l.indexOf('node:https:') !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no + // need to create a fake socket because Node.js native connection pooling + // will never be invoked. + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + // All instances of `sockets` are expected TypeScript errors. The + // alternative is to add it as a private property of this class but that + // will break TypeScript subclassing. + if (!this.sockets[name]) { + // @ts-expect-error `sockets` is readonly in `@types/node` + this.sockets[name] = []; + } + const fakeSocket = new external_net_.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount--; + if (sockets.length === 0) { + // @ts-expect-error `sockets` is readonly in `@types/node` + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + return external_https_.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then((socket) => { + this.decrementSockets(name, fakeSocket); + if (typeof socket + .addRequest === 'function') { + try { + return socket.addRequest(req, connectOpts); + } + catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } + get defaultPort() { + return (this[INTERNAL].defaultPort ?? + (this.protocol === 'https:' ? 443 : 80)); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return (this[INTERNAL].protocol ?? + (this.isSecureEndpoint() ? 'https:' : 'http:')); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } +} +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: external "url" +var external_url_ = __webpack_require__(87016); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/proxy-agent-negotiate@1.1.0/node_modules/proxy-agent-negotiate/dist/index.js +function createNegotiateAuth() { + return async ({ response, scheme }) => { + if (scheme.toLowerCase() !== 'negotiate') { + throw new Error(`Expected Negotiate scheme but got "${scheme}"`); + } + let kerberos; + try { + kerberos = await __webpack_require__.e(/* import() */ 730).then(__webpack_require__.t.bind(__webpack_require__, 10730, 19)); + } + catch { + throw new Error('The "kerberos" package is required for Negotiate proxy authentication. ' + + 'Install it with: npm install kerberos'); + } + const proxyAuthenticate = response.headers['proxy-authenticate'] || ''; + const challengeHeader = Array.isArray(proxyAuthenticate) + ? proxyAuthenticate[0] + : proxyAuthenticate; + const serverToken = typeof challengeHeader === 'string' && challengeHeader.includes(' ') + ? challengeHeader.split(' ').slice(1).join(' ') + : undefined; + const client = await kerberos.initializeClient('HTTP@proxy', { + mechOID: kerberos.GSS_MECH_OID_SPNEGO, + }); + const token = await client.step(serverToken || ''); + if (!token) { + throw new Error('Kerberos client.step() returned no token'); + } + return { + headers: { + 'Proxy-Authorization': `Negotiate ${token}`, + }, + }; + }; +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/http-proxy-agent@9.1.0/node_modules/http-proxy-agent/dist/index.js + + + + + + + +const debug = src('http-proxy-agent'); +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + */ +class HttpProxyAgent extends Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === 'string' ? new external_url_.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); + if (opts?.negotiate) { + this.onProxyAuth = createNegotiateAuth(); + } + else if (opts?.onProxyAuth) { + this.onProxyAuth = opts.onProxyAuth; + } + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + ...(opts + ? omit(opts, 'headers', 'onProxyAuth', 'negotiate') + : null), + host, + port, + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? 'https:' : 'http:'; + const hostname = req.getHeader('host') || 'localhost'; + const base = `${protocol}//${hostname}`; + const url = new external_url_.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + // Change the `http.ClientRequest` instance's "path" field + // to the absolute path of the URL that will be requested. + req.path = String(url); + // Inject the `Proxy-Authorization` header if necessary. + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes('://')) { + this.setRequestProps(req, opts); + } + // At this point, the http ClientRequest's internal `_header` field + // might have already been set. If this is the case then we'll need + // to re-generate the string since we just changed the `req.path`. + let first; + let endOfHeaders; + debug('Regenerating stored HTTP header string for request'); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug('Patching connection write() output buffer with updated header'); + first = req.outputData[0].data; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.outputData[0].data = + req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.outputData[0].data); + } + // Create a socket connection to the proxy server. + let socket; + if (this.proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = external_tls_.connect(this.connectOpts); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = external_net_.connect(this.connectOpts); + } + // Wait for the socket's `connect` event, so that this `callback()` + // function throws instead of the `http` request machinery. This is + // important for i.e. `PacProxyAgent` which determines a failed proxy + // connection via the `callback()` function throwing. + await (0,external_events_.once)(socket, 'connect'); + // Emit the 'proxyConnect' event for parity with https-proxy-agent + const connect = { socket }; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + req.emit('proxy', { proxy: this.proxy.href, socket }); + return socket; + } +} +HttpProxyAgent.protocols = ['http', 'https']; +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: external "assert" +var external_assert_ = __webpack_require__(42613); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/https-proxy-agent@9.1.0/node_modules/https-proxy-agent/dist/parse-proxy-response.js + +const parse_proxy_response_debug = src('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + parse_proxy_response_debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + parse_proxy_response_debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + parse_proxy_response_debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + parse_proxy_response_debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +//# sourceMappingURL=parse-proxy-response.js.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/https-proxy-agent@9.1.0/node_modules/https-proxy-agent/dist/index.js + + + + + + + + +const dist_debug = src('https-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !external_net_.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; + } + return options; +}; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new external_url_.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + dist_debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + if (opts?.negotiate) { + this.onProxyAuth = createNegotiateAuth(); + } + else if (opts?.onProxyAuth) { + this.onProxyAuth = opts.onProxyAuth; + } + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts + ? dist_omit(opts, 'headers', 'onProxyAuth', 'negotiate') + : null), + host, + port, + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + dist_debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = external_tls_.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + dist_debug('Creating `net.Socket`: %o', this.connectOpts); + socket = external_net_.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = external_net_.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parseProxyResponse(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + req.emit('proxy', { proxy: this.proxy.href, socket }); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + dist_debug('Upgrading socket connection to TLS'); + return external_tls_.connect({ + ...dist_omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // Handle 407 Proxy Authentication Required + if (connect.statusCode === 407 && this.onProxyAuth) { + dist_debug('Got 407 response, invoking onProxyAuth callback'); + socket.destroy(); + const proxyAuthenticate = connect.headers['proxy-authenticate'] || ''; + const scheme = Array.isArray(proxyAuthenticate) + ? proxyAuthenticate[0].split(/\s/)[0] + : proxyAuthenticate.split(/\s/)[0]; + const authResponse = await this.onProxyAuth({ + response: connect, + scheme, + }); + // Retry with the auth headers + return this._connectWithAuth(req, opts, authResponse.headers); + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new external_net_.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + dist_debug('Replaying proxy buffer for failed request'); + external_assert_(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + /** + * Retry a CONNECT request with additional auth headers. + */ + async _connectWithAuth(req, opts, authHeaders) { + const { proxy } = this; + let socket; + if (proxy.protocol === 'https:') { + socket = external_tls_.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + socket = external_net_.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = external_net_.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + // Merge auth headers (overrides existing) + Object.assign(headers, authHeaders); + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parseProxyResponse(socket); + socket.write(`${payload}\r\n`); + const { connect } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + dist_debug('Upgrading socket connection to TLS'); + return external_tls_.connect({ + ...dist_omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // If still not 200, throw + socket.destroy(); + throw new Error(`Proxy authentication failed with status ${connect.statusCode} after retry`); + } +} +HttpsProxyAgent.protocols = ['http', 'https']; +function resume(socket) { + // Defer the resume so that all 'socket' event handlers have a chance + // to attach their listeners (e.g. the HTTP client's 'data' handler) + // before data starts flowing. Without this, buffered proxy-response + // data can be emitted synchronously before listeners are ready. + // See: https://github.com/nicolo-ribaudo/tc39-proposal-await-dictionary/issues/7 + setImmediate(() => { + socket.resume(); + }); +} +function dist_omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/models.js +var models = __webpack_require__(25941); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js +var diagnostics = __webpack_require__(64921); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js +var error_body = __webpack_require__(20372); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js +var event_stream = __webpack_require__(45174); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/headers.js +var headers = __webpack_require__(82003); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js +var json_parse = __webpack_require__(84781); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/node-http-proxy.js +var node_http_proxy = __webpack_require__(78191); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js +var provider_env = __webpack_require__(67982); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/sanitize-unicode.js +var sanitize_unicode = __webpack_require__(43780); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/text.js +var utils_text = __webpack_require__(65678); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js +var transcript = __webpack_require__(19883); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js +var constrained_sampling = __webpack_require__(37776); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js + 1 modules +var simple_options = __webpack_require__(18296); +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js +var transform_messages = __webpack_require__(48809); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js + + + + + + + + + + + + + + + + + + +const EMPTY_TEXT_PLACEHOLDER = ""; +/** Matches the placeholder the Anthropic API path uses for redacted thinking. */ +const REDACTED_THINKING_PLACEHOLDER = "[Reasoning redacted]"; +const stream = (model, context, options = {}) => { + const stream = new event_stream/* AssistantMessageEventStream */.Q2(); + // Bedrock has no mid-conversation system messages; fold them into the leading prompt. + const normalizedContext = (0,transcript/* collapseSystemMessages */.zI)(context); + (async () => { + const output = { + role: "assistant", + content: [], + api: "bedrock-converse-stream", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + const blocks = output.content; + // A profile explicitly configured through pi's auth flow (the `profile` + // option or scoped `AWS_PROFILE` on the stored credential's env) must win + // over ambient AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY. The SDK default + // chain already prefers a configured profile over env keys, but only when + // `credentials` is not set on the client config. See #6957. + const optionsProfile = options.profile || options.env?.AWS_PROFILE; + const config = { + profile: optionsProfile || (0,provider_env/* getProviderEnvValue */.Y)("AWS_PROFILE", options.env), + }; + const configuredRegion = getConfiguredBedrockRegion(options); + const hasAmbientConfiguredProfile = Boolean((0,provider_env/* getProviderEnvValue */.Y)("AWS_PROFILE")); + const endpointRegion = getStandardBedrockEndpointRegion(model.baseUrl); + const useExplicitEndpoint = shouldUseExplicitBedrockEndpoint(model.baseUrl, configuredRegion, hasAmbientConfiguredProfile); + // Only pin standard AWS Bedrock runtime endpoints when no region or ambient AWS_PROFILE is configured. + // This preserves custom endpoints (VPC/proxy) from #3402 without forcing built-in + // catalog defaults such as us-east-1 to override AWS_REGION/AWS_PROFILE. + if (useExplicitEndpoint) { + config.endpoint = model.baseUrl; + } + // Resolve bearer token for Bedrock API key auth. + const skipAuth = (0,provider_env/* getProviderEnvValue */.Y)("AWS_BEDROCK_SKIP_AUTH", options.env) === "1"; + const bearerToken = options.bearerToken || + options.apiKey || + (0,provider_env/* getProviderEnvValue */.Y)("AWS_BEARER_TOKEN_BEDROCK", options.env) || + undefined; + const useBearerToken = bearerToken !== undefined && !skipAuth; + // in Node.js/Bun environment only + if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) { + // Region resolution: ARN-embedded > explicit option > env vars > SDK default chain. + // When the model ID is an inference profile ARN, extract the region from it. + // This avoids conflicts with AWS_REGION set for other services. + const arnRegionMatch = model.id.match(/^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/); + if (arnRegionMatch) { + config.region = arnRegionMatch[1]; + } + else if (configuredRegion) { + config.region = configuredRegion; + } + else if (endpointRegion && useExplicitEndpoint) { + config.region = endpointRegion; + } + else if (!hasAmbientConfiguredProfile) { + config.region = "us-east-1"; + } + // Support proxies that don't need authentication + if (skipAuth) { + config.credentials = { + accessKeyId: "dummy-access-key", + secretAccessKey: "dummy-secret-key", + }; + } + const credentials = getConfiguredBedrockCredentials(options.env); + if (!skipAuth && credentials && !optionsProfile) { + config.credentials = credentials; + } + const proxyUrl = (0,node_http_proxy/* resolveHttpProxyUrlForTarget */.Q)(model.baseUrl, options.env); + if (proxyUrl) { + // Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based + // on `http2` module and has no support for http agent. + // Use NodeHttpHandler to support HTTP(S) proxy agents. + config.requestHandler = new node_http_handler_dist_cjs.NodeHttpHandler({ + httpAgent: new HttpProxyAgent(proxyUrl), + httpsAgent: new HttpsProxyAgent(proxyUrl), + }); + } + else if ((0,provider_env/* getProviderEnvValue */.Y)("AWS_BEDROCK_FORCE_HTTP1", options.env) === "1") { + // Some custom endpoints require HTTP/1.1 instead of HTTP/2 + config.requestHandler = new node_http_handler_dist_cjs.NodeHttpHandler(); + } + } + else { + // Non-Node environment (browser): fall back to us-east-1 since + // there's no config file resolution available. + config.region = + configuredRegion || (endpointRegion && useExplicitEndpoint ? endpointRegion : undefined) || "us-east-1"; + } + if (useBearerToken) { + config.token = { token: bearerToken }; + config.authSchemePreference = ["httpBearerAuth"]; + } + // Kept outside the try so the catch can still correlate a mid-stream failure: + // exceptions delivered as stream events carry no HTTP metadata of their own. + let responseRequestId; + try { + const supportsStrictMode = model.compat?.supportsStrictMode ?? false; + const client = new dist_cjs/* BedrockRuntimeClient */.mam(config); + let observedRawResponse = false; + if (options.onResponse) { + addResponseHeadersMiddleware(client, options.onResponse, model, () => { + observedRawResponse = true; + }); + } + const customHeaders = (0,headers/* providerHeadersToRecord */.m)(options.headers); + if (customHeaders) { + addCustomHeadersMiddleware(client, customHeaders); + } + const cacheRetention = resolveCacheRetention(options.cacheRetention, options.env); + const inferenceMaxTokens = options.maxTokens ?? (isAnthropicClaudeModel(model) ? model.maxTokens : undefined); + const initialSystemMessage = (0,transcript/* getInitialSystemMessage */.xF)(normalizedContext.messages); + const initialSystemPrompt = initialSystemMessage ? (0,utils_text/* getSystemMessageText */.Y8)(initialSystemMessage) : undefined; + let commandInput = { + modelId: model.id, + messages: convertMessages(normalizedContext, model, cacheRetention, options.env), + system: buildSystemPrompt(initialSystemPrompt, model, cacheRetention, options.env), + inferenceConfig: { + ...(inferenceMaxTokens !== undefined && { maxTokens: inferenceMaxTokens }), + ...(options.temperature !== undefined && { temperature: options.temperature }), + }, + toolConfig: convertToolConfig((0,transcript/* getCurrentTools */.Fh)(normalizedContext.messages), options.toolChoice, supportsStrictMode), + additionalModelRequestFields: buildAdditionalModelRequestFields(model, options), + ...(options.requestMetadata !== undefined && { requestMetadata: options.requestMetadata }), + }; + const nextCommandInput = await options?.onPayload?.(commandInput, model); + if (nextCommandInput !== undefined) { + commandInput = nextCommandInput; + } + const command = new dist_cjs/* ConverseStreamCommand */.vDc(commandInput); + const response = await client.send(command, { abortSignal: options.signal }); + responseRequestId = normalizeDiagnosticValue(response.$metadata.requestId); + if (!observedRawResponse && response.$metadata.httpStatusCode !== undefined) { + const responseHeaders = {}; + if (response.$metadata.requestId) { + responseHeaders["x-amzn-requestid"] = response.$metadata.requestId; + } + await options?.onResponse?.({ status: response.$metadata.httpStatusCode, headers: responseHeaders }, model); + } + for await (const item of response.stream) { + if (item.messageStart) { + if (item.messageStart.role !== dist_cjs/* ConversationRole */.sCr.ASSISTANT) { + throw new Error("Unexpected assistant message start but got user message start instead"); + } + stream.push({ type: "start", partial: output }); + } + else if (item.contentBlockStart) { + handleContentBlockStart(item.contentBlockStart, blocks, output, stream); + } + else if (item.contentBlockDelta) { + handleContentBlockDelta(item.contentBlockDelta, blocks, output, stream); + } + else if (item.contentBlockStop) { + handleContentBlockStop(item.contentBlockStop, blocks, output, stream); + } + else if (item.messageStop) { + output.rawStopReason = item.messageStop.stopReason; + const { stopReason, errorMessage } = mapStopReason(item.messageStop.stopReason); + output.stopReason = stopReason; + if (errorMessage) { + output.errorMessage = errorMessage; + } + } + else if (item.metadata) { + handleMetadata(item.metadata, model, output); + } + else if (item.internalServerException) { + throw item.internalServerException; + } + else if (item.modelStreamErrorException) { + throw item.modelStreamErrorException; + } + else if (item.validationException) { + throw item.validationException; + } + else if (item.throttlingException) { + throw item.throttlingException; + } + else if (item.serviceUnavailableException) { + throw item.serviceUnavailableException; + } + } + if (options.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "pending") { + throw new Error("Bedrock stream ended without a stop reason"); + } + if (output.stopReason === "error" || output.stopReason === "aborted") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + // A stream can settle without stopping every block, so finalize here too. + for (const block of output.content) + finalizeStreamingBlock(block); + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + for (const block of output.content) { + finalizeStreamingBlock(block); + } + output.stopReason = options.signal?.aborted ? "aborted" : "error"; + output.errorMessage = formatBedrockError(error); + if (output.stopReason === "error") { + appendBedrockFailureDiagnostic(output, error, responseRequestId); + } + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +/** + * Human-readable prefixes for Bedrock SDK exception names. + * The downstream retry logic in agent-session matches patterns like + * `server.?error` and `service.?unavailable`, so we preserve the legacy + * prefix format rather than using the raw SDK exception name. + */ +const BEDROCK_ERROR_PREFIXES = { + InternalServerException: "Internal server error", + ModelStreamErrorException: "Model stream error", + ValidationException: "Validation error", + ThrottlingException: "Throttling error", + ServiceUnavailableException: "Service unavailable", +}; +/** + * Some models reject the account/profile's configured Bedrock data retention mode + * (e.g. "data retention mode 'default' is not available for this model"). Point + * users at the AWS docs explaining how to configure a supported mode. + */ +const BEDROCK_DATA_RETENTION_DOCS_URL = "https://docs.aws.amazon.com/bedrock/latest/userguide/data-retention.html"; +/** + * Format a Bedrock error with a human-readable prefix. + * AWS SDK exceptions (both from `client.send()` and from stream event items) + * extend BedrockRuntimeServiceException. We map the `.name` to a stable + * human-readable prefix so downstream consumers (retry logic, context-overflow + * detection) can distinguish error categories via simple string matching. + */ +function formatBedrockError(error) { + const norm = (0,error_body/* normalizeProviderError */.Jo)(error); + // Surface the raw HTTP body (with status) when the SDK did not fold it into + // the message; otherwise fall back to the message. This is what stops a + // gateway 403 from collapsing to `Unknown: UnknownError`. + const core = !norm.messageCarriesBody && norm.status !== undefined && norm.body !== undefined + ? `${norm.status}: ${norm.body}` + : norm.message; + const dataRetentionHint = /data retention mode/i.test(core) + ? ` See ${BEDROCK_DATA_RETENTION_DOCS_URL} for supported data retention modes.` + : ""; + if (error instanceof dist_cjs/* BedrockRuntimeServiceException */.bY6) { + const prefix = BEDROCK_ERROR_PREFIXES[error.name] ?? error.name; + return `${prefix}: ${core}${dataRetentionHint}`; + } + return `${core}${dataRetentionHint}`; +} +/** Over-long header values are dropped rather than truncated: a truncated request id is not a request id. */ +const MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS = 200; +function normalizeDiagnosticValue(value) { + if (typeof value !== "string") + return undefined; + const trimmed = value.trim(); + if (trimmed.length === 0 || trimmed.length > MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS) + return undefined; + return trimmed; +} +/** + * The SDK puts the modeled code on `error.name` for service exceptions and unmodeled stream errors alike, so + * do not narrow to `BedrockRuntimeServiceException`. Modeled Bedrock errors all end in `Exception`, unlike + * transport names such as `TimeoutError`. + */ +function extractBedrockErrorCode(error) { + if (!(error instanceof Error) || !error.name.endsWith("Exception")) + return undefined; + return normalizeDiagnosticValue(error.name); +} +/** + * Structured metadata alongside `errorMessage`, which stays byte-identical because `isRetryableAssistantError` + * matches against it. Unknown fields are omitted, never guessed: a modeled mid-stream exception reaches us as + * a bare object literal, leaving only `fallbackRequestId`. `details` only, as the throw is not always `Error`. + */ +function appendBedrockFailureDiagnostic(output, error, fallbackRequestId) { + const metadata = error?.$metadata; + const details = {}; + if (typeof metadata?.httpStatusCode === "number") + details.status = metadata.httpStatusCode; + const errorCode = extractBedrockErrorCode(error); + if (errorCode !== undefined) + details.errorCode = errorCode; + const requestId = normalizeDiagnosticValue(metadata?.requestId) ?? fallbackRequestId; + if (requestId !== undefined) + details.requestId = requestId; + if (Object.keys(details).length === 0) + return; + (0,diagnostics/* appendAssistantMessageDiagnostic */.vF)(output, { type: "bedrock_response_failure", timestamp: Date.now(), details }); +} +/** + * Header keys that must never be overwritten by caller-supplied headers. + * `host` and `x-amz-*` participate in the SigV4 canonical request; `authorization` + * is owned by SigV4 or the bearer-token path (config.token + authSchemePreference). + * Compared case-insensitively (caller key is lower-cased before lookup). + */ +const RESERVED_HEADER_EXACT = new Set(["authorization", "host"]); +function isReservedHeader(key) { + const lower = key.toLowerCase(); + return lower.startsWith("x-amz-") || RESERVED_HEADER_EXACT.has(lower); +} +/** + * Attach caller-supplied headers to the outgoing Bedrock request via a Smithy + * `build`-step middleware. The `build` step runs after request serialisation but + * before SigV4 signing, so injected headers are covered by the signature. Reserved + * SigV4 / auth headers (`x-amz-*`, `authorization`, `host`) are silently skipped; + * all other caller headers override any existing same-named header on the request. + */ +function addCustomHeadersMiddleware(client, headers) { + const middleware = (next) => async (args) => { + const request = args.request; + if (request && typeof request === "object" && "headers" in request) { + const requestHeaders = request.headers; + for (const [key, value] of Object.entries(headers)) { + if (!isReservedHeader(key)) { + requestHeaders[key] = value; + } + } + } + return next(args); + }; + client.middlewareStack.add(middleware, { step: "build", name: "pi-ai-custom-headers", priority: "low" }); +} +function isSmithyHttpResponse(response) { + if (!response || typeof response !== "object") + return false; + const candidate = response; + return typeof candidate.statusCode === "number" && !!candidate.headers && typeof candidate.headers === "object"; +} +function toProviderResponse(response) { + if (!isSmithyHttpResponse(response)) + return undefined; + return { status: response.statusCode, headers: { ...response.headers } }; +} +/** + * Bedrock's modeled `$metadata` only preserves selected HTTP metadata (for example + * requestId), so custom gateway headers are otherwise lost before callers see + * `onResponse`. Capture the raw Smithy HTTP response at the deserialize step, + * after the SDK receives the response but before the event stream is consumed. + */ +function addResponseHeadersMiddleware(client, onResponse, model, onObserved) { + const middleware = (next) => async (args) => { + const result = await next(args); + const providerResponse = toProviderResponse(result.response); + if (providerResponse) { + onObserved(); + await onResponse(providerResponse, model); + } + return result; + }; + client.middlewareStack.add(middleware, { step: "deserialize", name: "pi-ai-response-headers" }); +} +const streamSimple = (model, context, options) => { + const base = { + ...(0,simple_options/* buildBaseOptions */.QP)(model, context, options, undefined), + toolChoice: options?.toolChoice, + }; + if (!options?.reasoning) { + return stream(model, context, { ...base, reasoning: undefined }); + } + if (isAnthropicClaudeModel(model)) { + if (supportsAdaptiveThinking(model.id, model.name)) { + return stream(model, context, { + ...base, + reasoning: options.reasoning, + thinkingBudgets: options.thinkingBudgets, + }); + } + // Undefined means the caller did not request an output cap; let the helper use the model cap. + // Do not coerce to 0 here, or the thinking budget would become the entire maxTokens value. + const adjusted = (0,simple_options/* adjustMaxTokensForThinking */.xw)(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets); + const maxTokens = (0,simple_options/* clampMaxTokensToContext */.Yx)(model, context, adjusted.maxTokens); + return stream(model, context, { + ...base, + maxTokens, + reasoning: options.reasoning, + thinkingBudgets: { + ...(options.thinkingBudgets || {}), + [(0,simple_options/* clampReasoning */.M7)(options.reasoning)]: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)), + }, + }); + } + return stream(model, context, { + ...base, + reasoning: options.reasoning, + thinkingBudgets: options.thinkingBudgets, + }); +}; +function handleContentBlockStart(event, blocks, output, stream) { + const index = event.contentBlockIndex; + const start = event.start; + if (start?.toolUse) { + const block = { + type: "toolCall", + id: start.toolUse.toolUseId || "", + name: start.toolUse.name || "", + arguments: {}, + partialJson: "", + index, + }; + output.content.push(block); + stream.push({ type: "toolcall_start", contentIndex: blocks.length - 1, partial: output }); + } +} +function handleContentBlockDelta(event, blocks, output, stream) { + const contentBlockIndex = event.contentBlockIndex; + const delta = event.delta; + let index = blocks.findIndex((b) => b.index === contentBlockIndex); + let block = blocks[index]; + if (delta?.text !== undefined) { + // If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks + if (!block) { + const newBlock = { type: "text", text: "", index: contentBlockIndex }; + output.content.push(newBlock); + index = blocks.length - 1; + block = blocks[index]; + stream.push({ type: "text_start", contentIndex: index, partial: output }); + } + if (block.type === "text") { + block.text += delta.text; + stream.push({ type: "text_delta", contentIndex: index, delta: delta.text, partial: output }); + } + } + else if (delta?.toolUse && block?.type === "toolCall") { + block.partialJson = (block.partialJson || "") + (delta.toolUse.input || ""); + block.arguments = (0,json_parse/* parseStreamingJson */.o2)(block.partialJson); + stream.push({ type: "toolcall_delta", contentIndex: index, delta: delta.toolUse.input || "", partial: output }); + } + else if (delta?.reasoningContent) { + let thinkingBlock = block; + let thinkingIndex = index; + if (!thinkingBlock) { + const newBlock = { type: "thinking", thinking: "", thinkingSignature: "", index: contentBlockIndex }; + output.content.push(newBlock); + thinkingIndex = blocks.length - 1; + thinkingBlock = blocks[thinkingIndex]; + stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output }); + } + if (thinkingBlock?.type === "thinking") { + if (delta.reasoningContent.text) { + thinkingBlock.thinking += delta.reasoningContent.text; + stream.push({ + type: "thinking_delta", + contentIndex: thinkingIndex, + delta: delta.reasoningContent.text, + partial: output, + }); + } + // `thinkingSignature` holds either an Anthropic signature or an opaque redacted + // payload, never both: mixing them would corrupt whichever arrived first. + if (delta.reasoningContent.signature && !thinkingBlock.redacted) { + thinkingBlock.thinkingSignature = + (thinkingBlock.thinkingSignature || "") + delta.reasoningContent.signature; + } + if (delta.reasoningContent.redactedContent?.length) { + // Encrypted reasoning from non-Anthropic models on Bedrock (e.g. OpenAI GPT-5.6). + // The payload is opaque, so keep it verbatim in `thinkingSignature` the way the + // Anthropic path stores redacted thinking, and replay it on the next turn. + if (!thinkingBlock.redacted) { + thinkingBlock.redacted = true; + thinkingBlock.thinkingSignature = ""; + thinkingBlock.thinking += REDACTED_THINKING_PLACEHOLDER; + stream.push({ + type: "thinking_delta", + contentIndex: thinkingIndex, + delta: REDACTED_THINKING_PLACEHOLDER, + partial: output, + }); + } + thinkingBlock.redactedChunks ??= []; + thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent); + } + } + } +} +/** + * Encodes buffered encrypted reasoning into `thinkingSignature` and drops the scratch + * buffer, which must never reach a persisted message: `Uint8Array` serializes to an + * index-keyed object roughly ten times the size of the base64 payload. + */ +function flushRedactedContent(block) { + if (block.type !== "thinking" || !block.redactedChunks) + return; + block.thinkingSignature = bytesToBase64(block.redactedChunks); + delete block.redactedChunks; +} +/** + * Strips every streaming scratch field. Runs from the terminal paths as well as + * `contentBlockStop`, because a stream can settle without stopping each block. + */ +function finalizeStreamingBlock(block) { + delete block.index; + // partialJson is only a streaming scratch buffer; never persist it. + delete block.partialJson; + flushRedactedContent(block); +} +function handleMetadata(event, model, output) { + if (event.usage) { + output.usage.input = event.usage.inputTokens || 0; + output.usage.output = event.usage.outputTokens || 0; + output.usage.cacheRead = event.usage.cacheReadInputTokens || 0; + output.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0; + output.usage.cacheWrite1h = event.usage.cacheDetails?.reduce((total, detail) => total + (detail.ttl === dist_cjs/* CacheTTL */.xN0.ONE_HOUR ? (detail.inputTokens ?? 0) : 0), 0); + output.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output; + (0,models/* calculateCost */.yN)(model, output.usage); + } +} +function handleContentBlockStop(event, blocks, output, stream) { + const index = blocks.findIndex((b) => b.index === event.contentBlockIndex); + const block = blocks[index]; + if (!block) + return; + delete block.index; + switch (block.type) { + case "text": + stream.push({ type: "text_end", contentIndex: index, content: block.text, partial: output }); + break; + case "thinking": + flushRedactedContent(block); + stream.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: output }); + break; + case "toolCall": + block.arguments = (0,json_parse/* parseStreamingJson */.o2)(block.partialJson); + // Finalize in-place and strip the scratch buffer so replay only + // carries parsed arguments. + delete block.partialJson; + stream.push({ type: "toolcall_end", contentIndex: index, toolCall: block, partial: output }); + break; + } +} +/** + * Check if the model supports adaptive thinking (Opus 4.6+, Sonnet 4.6). + * Checks both model ID and model name to support application inference profiles + * whose ARNs don't contain the model name. + */ +function getModelMatchCandidates(modelId, modelName) { + const values = modelName ? [modelId, modelName] : [modelId]; + return values.flatMap((value) => { + const lower = value.toLowerCase(); + return [lower, lower.replace(/[\s_.:]+/g, "-")]; + }); +} +function supportsAdaptiveThinking(modelId, modelName) { + const candidates = getModelMatchCandidates(modelId, modelName); + return candidates.some((s) => s.includes("opus-4-6") || + s.includes("opus-4-7") || + s.includes("opus-4-8") || + s.includes("opus-5") || + s.includes("sonnet-4-6") || + s.includes("sonnet-5") || + s.includes("fable-5")); +} +function supportsNativeXhighEffort(model) { + const candidates = getModelMatchCandidates(model.id, model.name); + return candidates.some((s) => s.includes("opus-4-7") || + s.includes("opus-4-8") || + s.includes("opus-5") || + s.includes("sonnet-5") || + s.includes("fable-5")); +} +function mapThinkingLevelToEffort(model, level) { + if (level === "xhigh" && supportsNativeXhighEffort(model)) + return "xhigh"; + const mapped = level ? model.thinkingLevelMap?.[level] : undefined; + if (typeof mapped === "string") + return mapped; + switch (level) { + case "minimal": + case "low": + return "low"; + case "medium": + return "medium"; + case "high": + return "high"; + default: + return "high"; + } +} +/** + * Resolve cache retention preference. + * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility. + */ +function resolveCacheRetention(cacheRetention, env) { + if (cacheRetention) { + return cacheRetention; + } + if ((0,provider_env/* getProviderEnvValue */.Y)("PI_CACHE_RETENTION", env) === "long") { + return "long"; + } + return "short"; +} +/** + * Check if the model is an Anthropic Claude model on Bedrock. + * Checks both model ID and model name to support application inference profiles + * whose ARNs don't contain the model name. + */ +function isAnthropicClaudeModel(model) { + const id = model.id.toLowerCase(); + const name = model.name?.toLowerCase() ?? ""; + return (id.includes("anthropic.claude") || + id.includes("anthropic/claude") || + name.includes("anthropic.claude") || + name.includes("anthropic/claude") || + name.includes("claude")); +} +/** + * Check if the model supports prompt caching. + * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models, Claude 5 models + * + * For base models and system-defined inference profiles the model ID / ARN + * contains the model name, so we can decide locally. + * + * For application inference profiles (whose ARNs don't contain the model name), + * also checks model.name which is user-controlled via models.json or registerProvider. + * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points. + * Amazon Nova models have automatic caching and don't need explicit cache points. + */ +function supportsPromptCaching(model, env) { + const candidates = getModelMatchCandidates(model.id, model.name); + const hasClaudeRef = candidates.some((s) => s.includes("claude")); + if (!hasClaudeRef) { + // Application inference profiles don't contain the model name in the ARN. + // Allow users to force cache points via environment variable. + if ((0,provider_env/* getProviderEnvValue */.Y)("AWS_BEDROCK_FORCE_CACHE", env) === "1") + return true; + return false; + } + // Claude 5 models (fable-5, opus-5, sonnet-5) + if (candidates.some((s) => s.includes("fable-5") || s.includes("opus-5") || s.includes("sonnet-5"))) + return true; + // Claude 4.x models (opus-4, sonnet-4, haiku-4) + if (candidates.some((s) => s.includes("-4-"))) + return true; + // Claude 3.7 Sonnet + if (candidates.some((s) => s.includes("claude-3-7-sonnet"))) + return true; + // Claude 3.5 Haiku + if (candidates.some((s) => s.includes("claude-3-5-haiku"))) + return true; + return false; +} +/** + * Check if the model supports thinking signatures in reasoningContent. + * Only Anthropic Claude models support the signature field. + * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with: + * "This model doesn't support the reasoningContent.reasoningText.signature field" + * + * Checks both model ID and model name to support application inference profiles. + */ +function supportsThinkingSignature(model) { + return isAnthropicClaudeModel(model); +} +function buildSystemPrompt(systemPrompt, model, cacheRetention, env) { + if (!systemPrompt) + return undefined; + const blocks = [{ text: (0,sanitize_unicode/* sanitizeSurrogates */.J)(systemPrompt) }]; + // Add cache point for supported Claude models when caching is enabled + if (cacheRetention !== "none" && supportsPromptCaching(model, env)) { + blocks.push({ + cachePoint: { type: dist_cjs/* CachePointType */.zRl.DEFAULT, ...(cacheRetention === "long" ? { ttl: dist_cjs/* CacheTTL */.xN0.ONE_HOUR } : {}) }, + }); + } + return blocks; +} +function normalizeToolCallId(id) { + const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, "_"); + return sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized; +} +function createNonBlankTextBlock(text) { + const sanitized = (0,sanitize_unicode/* sanitizeSurrogates */.J)(text); + return sanitized.trim().length === 0 ? undefined : { text: sanitized }; +} +function createRequiredTextBlock(text) { + return createNonBlankTextBlock(text) ?? { text: EMPTY_TEXT_PLACEHOLDER }; +} +function sanitizeBedrockDocument(value) { + if (Array.isArray(value)) { + return value.map(sanitizeBedrockDocument); + } + if (value !== null && typeof value === "object") { + return Object.fromEntries(Object.entries(value) + .filter(([key]) => key.length > 0) + .map(([key, nestedValue]) => [key, sanitizeBedrockDocument(nestedValue)])); + } + return value; +} +function convertToolResultContent(content) { + const result = []; + for (const c of content) { + if (c.type === "image") { + result.push({ image: createImageBlock(c.mimeType, c.data) }); + } + else { + const textBlock = createNonBlankTextBlock(c.text); + if (textBlock) + result.push(textBlock); + } + } + if (result.length === 0) + result.push({ text: EMPTY_TEXT_PLACEHOLDER }); + return result; +} +function convertMessages(context, model, cacheRetention, env) { + const result = []; + const transformedMessages = (0,transform_messages/* transformMessages */.b)((0,transcript/* withoutInitialSystemMessage */.rg)(context.messages), model, normalizeToolCallId); + for (let i = 0; i < transformedMessages.length; i++) { + const m = transformedMessages[i]; + switch (m.role) { + case "user": { + const content = []; + if (typeof m.content === "string") { + content.push(createRequiredTextBlock(m.content)); + } + else { + for (const c of m.content) { + switch (c.type) { + case "text": { + const textBlock = createNonBlankTextBlock(c.text); + if (textBlock) + content.push(textBlock); + break; + } + case "image": + content.push({ image: createImageBlock(c.mimeType, c.data) }); + break; + default: + continue; + } + } + if (content.length === 0) + content.push({ text: EMPTY_TEXT_PLACEHOLDER }); + } + result.push({ role: dist_cjs/* ConversationRole */.sCr.USER, content }); + break; + } + case "assistant": { + // Skip assistant messages with empty content (e.g., from aborted requests) + // Bedrock rejects messages with empty content arrays + if (m.content.length === 0) { + continue; + } + const contentBlocks = []; + for (const c of m.content) { + switch (c.type) { + case "text": { + // Skip empty text blocks + const textBlock = createNonBlankTextBlock(c.text); + if (!textBlock) + continue; + contentBlocks.push(textBlock); + break; + } + case "toolCall": + contentBlocks.push({ + toolUse: { toolUseId: c.id, name: c.name, input: sanitizeBedrockDocument(c.arguments) }, + }); + break; + case "thinking": { + // Encrypted reasoning is opaque: replay the stored payload as the + // `redactedContent` member instead of lowering it to reasoning text. + if (c.redacted) { + const redactedContent = decodeRedactedContent(c.thinkingSignature); + if (redactedContent?.length) { + contentBlocks.push({ reasoningContent: { redactedContent } }); + } + continue; + } + // Skip empty thinking blocks + const thinking = (0,sanitize_unicode/* sanitizeSurrogates */.J)(c.thinking); + if (thinking.trim().length === 0) + continue; + // Only Anthropic models support the signature field in reasoningText. + // For other models, we omit the signature to avoid errors like: + // "This model doesn't support the reasoningContent.reasoningText.signature field" + if (supportsThinkingSignature(model)) { + // Signatures arrive after thinking deltas. If a partial or externally + // persisted message lacks a signature, Bedrock rejects the replayed + // reasoning block. Fall back to plain text, matching Anthropic. + if (!c.thinkingSignature || c.thinkingSignature.trim().length === 0) { + contentBlocks.push({ text: thinking }); + } + else { + contentBlocks.push({ + reasoningContent: { + reasoningText: { + text: thinking, + signature: c.thinkingSignature, + }, + }, + }); + } + } + else { + contentBlocks.push({ + reasoningContent: { + reasoningText: { text: thinking }, + }, + }); + } + break; + } + default: + continue; + } + } + // Skip if all content blocks were filtered out + if (contentBlocks.length === 0) { + continue; + } + result.push({ + role: dist_cjs/* ConversationRole */.sCr.ASSISTANT, + content: contentBlocks, + }); + break; + } + case "toolResult": { + // Collect all consecutive toolResult messages into a single user message + // Bedrock requires all tool results to be in one message + const toolResults = []; + // Add current tool result with all content blocks combined + toolResults.push({ + toolResult: { + toolUseId: m.toolCallId, + content: convertToolResultContent(m.content), + status: m.isError ? dist_cjs/* ToolResultStatus */.kz_.ERROR : dist_cjs/* ToolResultStatus */.kz_.SUCCESS, + }, + }); + // Look ahead for consecutive toolResult messages + let j = i + 1; + while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") { + const nextMsg = transformedMessages[j]; + toolResults.push({ + toolResult: { + toolUseId: nextMsg.toolCallId, + content: convertToolResultContent(nextMsg.content), + status: nextMsg.isError ? dist_cjs/* ToolResultStatus */.kz_.ERROR : dist_cjs/* ToolResultStatus */.kz_.SUCCESS, + }, + }); + j++; + } + // Skip the messages we've already processed + i = j - 1; + result.push({ role: dist_cjs/* ConversationRole */.sCr.USER, content: toolResults }); + break; + } + default: + continue; + } + } + // Add cache point to the last user message for supported Claude models when caching is enabled + if (cacheRetention !== "none" && supportsPromptCaching(model, env) && result.length > 0) { + const lastMessage = result[result.length - 1]; + if (lastMessage.role === dist_cjs/* ConversationRole */.sCr.USER && lastMessage.content) { + lastMessage.content.push({ + cachePoint: { + type: dist_cjs/* CachePointType */.zRl.DEFAULT, + ...(cacheRetention === "long" ? { ttl: dist_cjs/* CacheTTL */.xN0.ONE_HOUR } : {}), + }, + }); + } + } + return result; +} +function convertToolConfig(tools, toolChoice, supportsStrictMode) { + if (!tools?.length) + return undefined; + if (toolChoice === "none") + return undefined; + const bedrockTools = tools.map((tool) => { + const strict = (0,constrained_sampling/* resolveJsonSchemaStrictSampling */._F)(tool, supportsStrictMode); + return { + toolSpec: { + name: tool.name, + description: tool.description, + inputSchema: { json: (0,constrained_sampling/* getJsonSchemaToolParameters */.Km)(tool, strict) }, + ...(strict === true ? { strict: true } : {}), + }, + }; + }); + let bedrockToolChoice; + switch (toolChoice) { + case "auto": + bedrockToolChoice = { auto: {} }; + break; + case "any": + bedrockToolChoice = { any: {} }; + break; + default: + if (toolChoice?.type === "tool") { + bedrockToolChoice = { tool: { name: toolChoice.name } }; + } + } + return { tools: bedrockTools, toolChoice: bedrockToolChoice }; +} +function mapStopReason(reason) { + switch (reason) { + case dist_cjs/* StopReason */.TnC.END_TURN: + case dist_cjs/* StopReason */.TnC.STOP_SEQUENCE: + return { stopReason: "stop" }; + case dist_cjs/* StopReason */.TnC.MAX_TOKENS: + case dist_cjs/* StopReason */.TnC.MODEL_CONTEXT_WINDOW_EXCEEDED: + return { stopReason: "length" }; + case dist_cjs/* StopReason */.TnC.TOOL_USE: + return { stopReason: "toolUse" }; + default: + return reason + ? { stopReason: "error", errorMessage: `Provider stopped with: ${reason}` } + : { stopReason: "error" }; + } +} +function getConfiguredBedrockRegion(options) { + return (options.region || + (0,provider_env/* getProviderEnvValue */.Y)("AWS_REGION", options.env) || + (0,provider_env/* getProviderEnvValue */.Y)("AWS_DEFAULT_REGION", options.env) || + undefined); +} +function getConfiguredBedrockCredentials(env) { + const accessKeyId = (0,provider_env/* getProviderEnvValue */.Y)("AWS_ACCESS_KEY_ID", env); + const secretAccessKey = (0,provider_env/* getProviderEnvValue */.Y)("AWS_SECRET_ACCESS_KEY", env); + if (!accessKeyId || !secretAccessKey) { + return undefined; + } + const sessionToken = (0,provider_env/* getProviderEnvValue */.Y)("AWS_SESSION_TOKEN", env); + return { + accessKeyId, + secretAccessKey, + ...(sessionToken ? { sessionToken } : {}), + }; +} +function getStandardBedrockEndpointRegion(baseUrl) { + if (!baseUrl) { + return undefined; + } + try { + const { hostname } = new URL(baseUrl); + const match = hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/); + return match?.[1]; + } + catch { + return undefined; + } +} +function shouldUseExplicitBedrockEndpoint(baseUrl, configuredRegion, hasAmbientConfiguredProfile) { + const endpointRegion = getStandardBedrockEndpointRegion(baseUrl); + if (!endpointRegion) { + return true; + } + return !configuredRegion && !hasAmbientConfiguredProfile; +} +function isGovCloudBedrockTarget(model, options) { + const region = getConfiguredBedrockRegion(options); + if (region?.toLowerCase().startsWith("us-gov-")) { + return true; + } + const modelId = model.id.toLowerCase(); + return modelId.startsWith("us-gov.") || modelId.startsWith("arn:aws-us-gov:"); +} +function buildAdditionalModelRequestFields(model, options) { + if (!options.reasoning || !model.reasoning) { + return undefined; + } + if (isAnthropicClaudeModel(model)) { + // GovCloud Bedrock currently rejects the Claude thinking.display field. + // Omit it there until the GovCloud Converse schema catches up. + const display = isGovCloudBedrockTarget(model, options) ? undefined : (options.thinkingDisplay ?? "summarized"); + const result = supportsAdaptiveThinking(model.id, model.name) + ? { + thinking: { type: "adaptive", ...(display !== undefined ? { display } : {}) }, + output_config: { effort: mapThinkingLevelToEffort(model, options.reasoning) }, + } + : (() => { + const defaultBudgets = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384, + xhigh: 16384, // Budget-based Claude clamps extended levels to high + max: 16384, + }; + // Custom budgets only cover token-based levels through high. + const level = options.reasoning === "xhigh" || options.reasoning === "max" ? "high" : options.reasoning; + const budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning]; + return { + thinking: { + type: "enabled", + budget_tokens: budget, + ...(display !== undefined ? { display } : {}), + }, + }; + })(); + if (!supportsAdaptiveThinking(model.id, model.name) && (options.interleavedThinking ?? true)) { + result.anthropic_beta = ["interleaved-thinking-2025-05-14"]; + } + return result; + } + return undefined; +} +function createImageBlock(mimeType, data) { + let format; + switch (mimeType) { + case "image/jpeg": + case "image/jpg": + format = dist_cjs/* ImageFormat */.f5W.JPEG; + break; + case "image/png": + format = dist_cjs/* ImageFormat */.f5W.PNG; + break; + case "image/gif": + format = dist_cjs/* ImageFormat */.f5W.GIF; + break; + case "image/webp": + format = dist_cjs/* ImageFormat */.f5W.WEBP; + break; + default: + throw new Error(`Unknown image type: ${mimeType}`); + } + return { source: { bytes: base64ToBytes(data) }, format }; +} +function base64ToBytes(data) { + const binaryString = atob(data); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +/** + * Decodes a stored redacted payload. The AWS SDK hands the blob over as bytes, but a + * persisted session carries it as base64. A hand-edited or externally produced session + * can hold a signature that is not base64; drop that block instead of failing the + * whole request. + */ +function decodeRedactedContent(signature) { + if (!signature) + return undefined; + try { + return base64ToBytes(signature); + } + catch { + return undefined; + } +} +function bytesToBase64(chunks) { + // Encrypted reasoning runs to tens of KB, so build the binary string in slices + // rather than one concatenation per byte. The window stays under the engine's + // argument-count limit for spread calls. + const WINDOW = 0x8000; + let binary = ""; + for (const chunk of chunks) { + for (let i = 0; i < chunk.length; i += WINDOW) { + binary += String.fromCharCode(...chunk.subarray(i, i + WINDOW)); + } + } + return btoa(binary); +} +//# sourceMappingURL=bedrock-converse-stream.js.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/bedrock-provider.js + +const bedrockProviderModule = { + stream: stream, + streamSimple: streamSimple, +}; +//# sourceMappingURL=bedrock-provider.js.map + +/***/ }), + +/***/ 20372: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Jo: () => (/* binding */ normalizeProviderError), +/* harmony export */ lR: () => (/* binding */ formatProviderError) +/* harmony export */ }); +/* unused harmony exports MAX_PROVIDER_ERROR_BODY_CHARS, truncateErrorText, safeJsonStringify */ +// Shared normalization for provider HTTP error objects. +// +// Endpoints behind a proxy / gateway may return a non-2xx response whose body +// the provider SDK cannot fold into `error.message`. The SDK error object still +// carries the HTTP status and the raw/parsed body, but under SDK-specific field +// names. Provider catch blocks that read only `error.message` therefore drop +// the body and surface opaque messages like `"403 status code (no body)"` or +// collapse to `"Unknown: UnknownError"`. +// +// `normalizeProviderError` probes the known SDK field shapes (Mistral, +// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider +// composes into its display string. The `messageCarriesBody` flag captures the +// Anthropic / `@google/genai` happy path where the SDK already folded the body +// into the message, so providers can preserve it without double-printing. +const MAX_PROVIDER_ERROR_BODY_CHARS = 4000; +function normalizeProviderError(error) { + if (!(error instanceof Error)) { + return { message: safeJsonStringify(error), messageCarriesBody: false }; + } + const sdkError = error; + const status = extractStatus(sdkError); + const body = extractBody(sdkError); + const messageCarriesBody = body === undefined || error.message.includes(body); + return { + status, + body, + message: error.message, + messageCarriesBody, + }; +} +/** + * Probe the HTTP status, first numeric hit wins, in SDK-field order: + * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) → + * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock). + */ +function extractStatus(error) { + if (typeof error.statusCode === "number") + return error.statusCode; + if (typeof error.status === "number") + return error.status; + if (typeof error.$metadata?.httpStatusCode === "number") + return error.$metadata.httpStatusCode; + if (typeof error.$response?.statusCode === "number") + return error.$response.statusCode; + return undefined; +} +/** + * Probe the raw body reason, first usable hit wins, in SDK-field order: + * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's + * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response + * streams are treated as no body so they do not surface as `"{}"` or serialized + * stream internals. The chosen body is truncated to the cap. + */ +function extractBody(error) { + const bodyText = pickBodyText(error); + if (bodyText === undefined) + return undefined; + const trimmed = bodyText.trim(); + if (trimmed.length === 0) + return undefined; + return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS); +} +function pickBodyText(error) { + if (typeof error.body === "string") + return error.body; + if (isPlainNonEmptyObject(error.error)) + return safeJsonStringify(error.error); + const responseBody = error.$response?.body; + if (typeof responseBody === "string") + return responseBody; + if (isReadableStreamLike(responseBody)) + return undefined; + if (isPlainNonEmptyObject(responseBody)) + return safeJsonStringify(responseBody); + return undefined; +} +function isReadableStreamLike(value) { + return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function"; +} +/** + * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class + * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an + * HTTP stream/response wrapper object, and stringifying one produced garbage + * like `{"_events":...}` as the "body", which then REPLACED `error.message` + * in the composed display string. `error.message` is where the SDK puts the + * real deserialized exception text ("Input is too long...", schema validation + * details, ...), so the one useful string was discarded for noise. A class + * instance yields no body, `messageCarriesBody` stays true, and the real + * message survives. Complements the `pipe` sniffing above: web + * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper + * classes fail the prototype check, while parsed JSON bodies (plain objects + * by construction) still pass. + */ +function isPlainNonEmptyObject(value) { + if (typeof value !== "object" || value === null) + return false; + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + return false; + return Object.keys(value).length > 0; +} +/** + * Compose a display string from a normalized error. When the message already + * carries the body (Anthropic / `@google/genai` happy path) or no body/status + * was extracted, the message is returned unchanged. Otherwise the status and + * body are surfaced, with an optional provider prefix. + * + * - no prefix: `": "` + * - prefix: `" (): "` + */ +function formatProviderError(norm, prefix) { + if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) { + return prefix !== undefined && norm.status !== undefined + ? `${prefix} (${norm.status}): ${norm.message}` + : norm.message; + } + return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`; +} +function truncateErrorText(text, maxChars) { + if (text.length <= maxChars) + return text; + return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`; +} +function safeJsonStringify(value) { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? String(value) : serialized; + } + catch { + return String(value); + } +} +//# sourceMappingURL=error-body.js.map + +/***/ }), + +/***/ 78191: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Q: () => (/* binding */ resolveHttpProxyUrlForTarget) +/* harmony export */ }); +/* unused harmony export UNSUPPORTED_PROXY_PROTOCOL_MESSAGE */ +/* harmony import */ var _provider_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67982); + +const DEFAULT_PROXY_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; +function getProxyEnv(key, env) { + const lowercaseKey = key.toLowerCase(); + const uppercaseKey = key.toUpperCase(); + return (env?.[lowercaseKey] || + env?.[uppercaseKey] || + (0,_provider_env_js__WEBPACK_IMPORTED_MODULE_0__/* .getProviderEnvValue */ .Y)(lowercaseKey) || + (0,_provider_env_js__WEBPACK_IMPORTED_MODULE_0__/* .getProviderEnvValue */ .Y)(uppercaseKey) || + ""); +} +function parseProxyTargetUrl(targetUrl) { + if (targetUrl instanceof URL) { + return targetUrl; + } + try { + return new URL(targetUrl); + } + catch { + return undefined; + } +} +function stripBrackets(host) { + return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; +} +function parseNoProxyEntry(entry) { + const trimmed = entry.trim().toLowerCase(); + if (!trimmed) + return undefined; + if (trimmed.startsWith("[")) { + const closingBracket = trimmed.indexOf("]"); + if (closingBracket !== -1) { + const host = trimmed.slice(1, closingBracket); + const rest = trimmed.slice(closingBracket + 1); + if (rest.startsWith(":")) { + const port = Number.parseInt(rest.slice(1), 10); + return { host, port: Number.isNaN(port) ? 0 : port }; + } + return { host, port: 0 }; + } + } + if (trimmed.includes(":") && trimmed.split(":").length > 2) { + return { host: trimmed, port: 0 }; + } + const colonIndex = trimmed.lastIndexOf(":"); + if (colonIndex !== -1 && colonIndex === trimmed.indexOf(":")) { + const host = trimmed.slice(0, colonIndex); + const port = Number.parseInt(trimmed.slice(colonIndex + 1), 10); + if (!Number.isNaN(port)) { + return { host, port }; + } + } + return { host: trimmed, port: 0 }; +} +function shouldProxyHostname(hostname, port, env) { + const noProxy = getProxyEnv("no_proxy", env).toLowerCase(); + if (!noProxy) { + return true; + } + if (noProxy === "*") { + return false; + } + const normalizedTargetHost = stripBrackets(hostname.toLowerCase()); + return noProxy.split(/[,\s]/).every((entry) => { + const parsed = parseNoProxyEntry(entry); + if (!parsed) { + return true; + } + if (parsed.port && parsed.port !== port) { + return true; + } + let domain = stripBrackets(parsed.host); + if (domain.startsWith("*.")) { + domain = domain.slice(2); + } + else if (domain.startsWith(".") || domain.startsWith("*")) { + domain = domain.slice(1); + } + if (!domain) { + return true; + } + if (normalizedTargetHost === domain) { + return false; + } + if (normalizedTargetHost.endsWith(`.${domain}`)) { + return false; + } + return true; + }); +} +function getProxyForUrl(targetUrl, env) { + const parsedUrl = parseProxyTargetUrl(targetUrl); + if (!parsedUrl?.protocol || !parsedUrl.host) { + return ""; + } + const protocol = parsedUrl.protocol.split(":", 1)[0]; + const hostname = stripBrackets(parsedUrl.hostname || parsedUrl.host.replace(/:\d*$/, "")); + const port = Number.parseInt(parsedUrl.port, 10) || DEFAULT_PROXY_PORTS[protocol] || 0; + if (!shouldProxyHostname(hostname, port, env)) { + return ""; + } + let proxy = getProxyEnv(`${protocol}_proxy`, env) || getProxyEnv("all_proxy", env); + if (proxy && !proxy.includes("://")) { + proxy = `${protocol}://${proxy}`; + } + return proxy; +} +const UNSUPPORTED_PROXY_PROTOCOL_MESSAGE = "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL."; +function resolveHttpProxyUrlForTarget(targetUrl, env) { + const proxy = getProxyForUrl(targetUrl, env); + if (!proxy) { + return undefined; + } + let proxyUrl; + try { + proxyUrl = new URL(proxy); + } + catch (error) { + throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error ? error.message : String(error)}`); + } + if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") { + throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`); + } + return proxyUrl; +} +//# sourceMappingURL=node-http-proxy.js.map + +/***/ }) + +}; diff --git a/dist/action/786.index.js b/dist/action/786.index.js new file mode 100644 index 000000000..4de82a2e1 --- /dev/null +++ b/dist/action/786.index.js @@ -0,0 +1,1478 @@ +export const id = 786; +export const ids = [786]; +export const modules = { + +/***/ 26103: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ G0: () => (/* binding */ buildCopilotDynamicHeaders), +/* harmony export */ d1: () => (/* binding */ hasCopilotVisionInput) +/* harmony export */ }); +/* unused harmony export inferCopilotInitiator */ +// Copilot expects X-Initiator to indicate whether the request is user-initiated +// or agent-initiated (e.g. follow-up after assistant/tool messages). +function inferCopilotInitiator(messages) { + const last = messages[messages.length - 1]; + return last && last.role !== "user" ? "agent" : "user"; +} +// Copilot requires Copilot-Vision-Request header when sending images +function hasCopilotVisionInput(messages) { + return messages.some((msg) => { + if (msg.role === "user" && Array.isArray(msg.content)) { + return msg.content.some((c) => c.type === "image"); + } + if (msg.role === "toolResult" && Array.isArray(msg.content)) { + return msg.content.some((c) => c.type === "image"); + } + return false; + }); +} +function buildCopilotDynamicHeaders(params) { + const headers = { + "X-Initiator": inferCopilotInitiator(params.messages), + "Openai-Intent": "conversation-edits", + }; + if (params.hasImages) { + headers["Copilot-Vision-Request"] = "true"; + } + return headers; +} +//# sourceMappingURL=github-copilot-headers.js.map + +/***/ }), + +/***/ 55786: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ convertMessages: () => (/* binding */ convertMessages), +/* harmony export */ stream: () => (/* binding */ stream), +/* harmony export */ streamSimple: () => (/* binding */ streamSimple) +/* harmony export */ }); +/* harmony import */ var openai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3840); +/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(25941); +/* harmony import */ var _utils_error_body_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(20372); +/* harmony import */ var _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(45174); +/* harmony import */ var _utils_hash_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1901); +/* harmony import */ var _utils_headers_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(82003); +/* harmony import */ var _utils_json_parse_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(84781); +/* harmony import */ var _utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(55278); +/* harmony import */ var _utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67982); +/* harmony import */ var _utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(46863); +/* harmony import */ var _utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(43780); +/* harmony import */ var _utils_text_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(65678); +/* harmony import */ var _utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19883); +/* harmony import */ var _constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(37776); +/* harmony import */ var _github_copilot_headers_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(26103); +/* harmony import */ var _openai_prompt_cache_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(95304); +/* harmony import */ var _simple_options_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(18296); +/* harmony import */ var _transform_messages_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(48809); + + + + + + + + + + + + + + + + + + +/** + * Check if conversation messages contain tool calls or tool results. + * This is needed because Anthropic (via proxy) requires the tools param + * to be present when messages include tool_calls or tool role messages. + */ +function hasHeader(headers, name) { + if (!headers) + return false; + const expected = name.toLowerCase(); + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === expected && value !== null && value.trim().length > 0) + return true; + } + return false; +} +function getClientApiKey(provider, apiKey, headers) { + if (apiKey) + return apiKey; + if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization")) + return "unused"; + throw new Error(`No API key for provider: ${provider}`); +} +function hasToolHistory(messages) { + for (const msg of messages) { + if (msg.role === "toolResult") { + return true; + } + if (msg.role === "assistant") { + if (msg.content.some((block) => block.type === "toolCall")) { + return true; + } + } + } + return false; +} +function isTextContentBlock(block) { + return block.type === "text"; +} +function isThinkingContentBlock(block) { + return block.type === "thinking"; +} +function isToolCallBlock(block) { + return block.type === "toolCall"; +} +function isImageContentBlock(block) { + return block.type === "image"; +} +function isReasoningDetailObject(detail) { + return typeof detail === "object" && detail !== null && !Array.isArray(detail); +} +function hasValidCommonReasoningDetailFields(candidate) { + return ((candidate.id === undefined || candidate.id === null || typeof candidate.id === "string") && + (candidate.format === undefined || typeof candidate.format === "string") && + (candidate.index === undefined || typeof candidate.index === "number")); +} +function isOpenAIReasoningDetail(detail) { + if (!isReasoningDetailObject(detail) || !hasValidCommonReasoningDetailFields(detail)) { + return false; + } + switch (detail.type) { + case "reasoning.summary": + return typeof detail.summary === "string"; + case "reasoning.encrypted": + return typeof detail.data === "string"; + case "reasoning.text": + return (typeof detail.text === "string" && + (detail.signature === undefined || detail.signature === null || typeof detail.signature === "string")); + default: + return false; + } +} +function parseOpenAIReasoningDetails(signature) { + if (!signature) + return undefined; + try { + const parsed = JSON.parse(signature); + return Array.isArray(parsed) && parsed.length > 0 && parsed.every(isOpenAIReasoningDetail) ? parsed : undefined; + } + catch { + return undefined; + } +} +function parseLegacyEncryptedReasoningDetail(signature) { + if (!signature) + return undefined; + try { + const parsed = JSON.parse(signature); + return isOpenAIReasoningDetail(parsed) && + parsed.type === "reasoning.encrypted" && + typeof parsed.id === "string" && + parsed.id.length > 0 && + parsed.data.length > 0 + ? parsed + : undefined; + } + catch { + return undefined; + } +} +function fillMissingCommonReasoningDetailFields(target, source) { + target.id ??= source.id; + target.format ||= source.format; + target.index ??= source.index; +} +function appendOpenAIReasoningDetail(details, detail) { + const lastDetail = details[details.length - 1]; + if (detail.type === "reasoning.text" && lastDetail?.type === "reasoning.text") { + lastDetail.text += detail.text; + lastDetail.signature ||= detail.signature; + fillMissingCommonReasoningDetailFields(lastDetail, detail); + return; + } + if (detail.type === "reasoning.summary" && lastDetail?.type === "reasoning.summary") { + lastDetail.summary += detail.summary; + fillMissingCommonReasoningDetailFields(lastDetail, detail); + return; + } + details.push({ ...detail }); +} +const OPENAI_COMPLETIONS_REASONING_FIELDS = ["reasoning", "reasoning_content", "reasoning_text"]; +function isOpenAICompletionsReasoningField(field) { + return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field); +} +function resolveCacheRetention(cacheRetention, env) { + if (cacheRetention) { + return cacheRetention; + } + if ((0,_utils_provider_env_js__WEBPACK_IMPORTED_MODULE_1__/* .getProviderEnvValue */ .Y)("PI_CACHE_RETENTION", env) === "long") { + return "long"; + } + return "short"; +} +const stream = (model, context, options) => { + const stream = new _utils_event_stream_js__WEBPACK_IMPORTED_MODULE_2__/* .AssistantMessageEventStream */ .Q2(); + const normalizedContext = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveTranscript */ .lw)(context, getCompat(model).supportsMidConvoSystemMessages); + (async () => { + const output = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + // `reasoning_details` are replay metadata, not user-visible stream deltas. + // Keep them in memory during streaming and serialize once when the block is finalized. + let streamedReasoningDetails; + const applyStreamedReasoningDetails = (block) => { + if (streamedReasoningDetails !== undefined) { + block.thinkingSignature = JSON.stringify(streamedReasoningDetails); + } + }; + try { + const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers); + const compat = getCompat(model); + const grammarToolInputProperties = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .createGrammarToolInputProperties */ .PJ)((0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .getDeclaredTools */ .Wg)(normalizedContext.messages), compat.supportsOpenAIGrammarTools); + const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env); + const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId; + const client = createClient(model, normalizedContext, apiKey, options?.headers, options?.fetch, cacheSessionId, compat); + let params = buildParams(model, normalizedContext, options, compat, cacheRetention, grammarToolInputProperties); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== undefined) { + params = nextParams; + } + const requestOptions = { + ...(options?.signal ? { signal: options.signal } : {}), + ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), + maxRetries: 0, + }; + const { data: openaiStream, response } = await (0,_utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_5__/* .retryProviderRequest */ .T)(() => client.chat.completions.create(params, requestOptions).withResponse(), { + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + signal: options?.signal, + }); + await options?.onResponse?.({ status: response.status, headers: (0,_utils_headers_js__WEBPACK_IMPORTED_MODULE_6__/* .headersToRecord */ .j)(response.headers) }, model); + stream.push({ type: "start", partial: output }); + let textBlock = null; + let thinkingBlock = null; + let hasFinishReason = false; + const toolCallBlocksByIndex = new Map(); + const toolCallBlocksById = new Map(); + const blocks = output.content; + const getContentIndex = (block) => blocks.indexOf(block); + const getCustomToolCallInput = (block) => { + const property = block.customInput?.property; + if (property === undefined) + return ""; + const value = block.arguments[property]; + return typeof value === "string" ? value : ""; + }; + const appendCustomToolCallInput = (block, nextInput, close) => { + const customInput = block.customInput; + if (!customInput) + return undefined; + const delta = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .appendGrammarToolInputJsonDelta */ .eW)(customInput.jsonBuffer, customInput.property, nextInput, close); + block.arguments = { [customInput.property]: nextInput }; + return delta; + }; + const finishBlock = (block) => { + const contentIndex = getContentIndex(block); + if (contentIndex === -1) { + return; + } + if (block.type === "text") { + stream.push({ + type: "text_end", + contentIndex, + content: block.text, + partial: output, + }); + } + else if (block.type === "thinking") { + applyStreamedReasoningDetails(block); + stream.push({ + type: "thinking_end", + contentIndex, + content: block.thinking, + partial: output, + }); + } + else if (block.type === "toolCall") { + if (block.customInput) { + const delta = appendCustomToolCallInput(block, getCustomToolCallInput(block), true); + if (delta !== undefined) { + stream.push({ + type: "toolcall_delta", + contentIndex, + delta, + partial: output, + }); + } + } + else { + block.arguments = (0,_utils_json_parse_js__WEBPACK_IMPORTED_MODULE_7__/* .parseStreamingJson */ .o2)(block.partialArgs); + } + // Finalize in-place and strip the scratch buffers so replay only + // carries parsed arguments. + delete block.partialArgs; + delete block.customInput; + delete block.streamIndex; + stream.push({ + type: "toolcall_end", + contentIndex, + toolCall: block, + partial: output, + }); + } + }; + const ensureTextBlock = () => { + if (!textBlock) { + textBlock = { type: "text", text: "" }; + blocks.push(textBlock); + stream.push({ type: "text_start", contentIndex: getContentIndex(textBlock), partial: output }); + } + return textBlock; + }; + const ensureThinkingBlock = (thinkingSignature) => { + if (!thinkingBlock) { + thinkingBlock = { + type: "thinking", + thinking: "", + thinkingSignature, + }; + blocks.push(thinkingBlock); + stream.push({ type: "thinking_start", contentIndex: getContentIndex(thinkingBlock), partial: output }); + } + return thinkingBlock; + }; + const ensureToolCallBlock = (toolCall) => { + const streamIndex = typeof toolCall.index === "number" ? toolCall.index : undefined; + const name = toolCall.function?.name ?? toolCall.custom?.name ?? ""; + let block = streamIndex !== undefined ? toolCallBlocksByIndex.get(streamIndex) : undefined; + if (!block && toolCall.id) { + block = toolCallBlocksById.get(toolCall.id); + } + if (!block) { + // Note: the "input" fallback here should/must not be taken. in case the LLM makes up + // a tool we don't knwo about, we at least have a place to stash our stuff. + const customInputProperty = toolCall.custom && !toolCall.function ? (grammarToolInputProperties.get(name) ?? "input") : undefined; + const hasCustomInput = customInputProperty !== undefined; + block = { + type: "toolCall", + id: toolCall.id || "", + name, + arguments: hasCustomInput ? { [customInputProperty]: "" } : {}, + partialArgs: hasCustomInput ? undefined : "", + customInput: hasCustomInput + ? { property: customInputProperty, jsonBuffer: { input: "", started: false, closed: false } } + : undefined, + streamIndex, + }; + if (streamIndex !== undefined) { + toolCallBlocksByIndex.set(streamIndex, block); + } + if (toolCall.id) { + toolCallBlocksById.set(toolCall.id, block); + } + blocks.push(block); + stream.push({ + type: "toolcall_start", + contentIndex: getContentIndex(block), + partial: output, + }); + } + if (streamIndex !== undefined && block.streamIndex === undefined) { + block.streamIndex = streamIndex; + toolCallBlocksByIndex.set(streamIndex, block); + } + if (toolCall.id) { + toolCallBlocksById.set(toolCall.id, block); + } + if (!block.name && name) { + block.name = name; + } + if (toolCall.custom && !toolCall.function && !block.customInput) { + const customInputProperty = grammarToolInputProperties.get(block.name) ?? "input"; + block.arguments = { [customInputProperty]: "" }; + block.customInput = { + property: customInputProperty, + jsonBuffer: { input: "", started: false, closed: false }, + }; + delete block.partialArgs; + } + return block; + }; + for await (const chunk of openaiStream) { + if (!chunk || typeof chunk !== "object") + continue; + // OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier, + // and each chunk in a streamed completion carries the same id. + output.responseId ||= chunk.id; + if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) { + output.responseModel ||= chunk.model; + } + if (chunk.usage) { + output.usage = parseChunkUsage(chunk.usage, model); + } + const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined; + if (!choice) + continue; + // Fallback: some providers (e.g., Moonshot) return usage + // in choice.usage instead of the standard chunk.usage + if (!chunk.usage && choice.usage) { + output.usage = parseChunkUsage(choice.usage, model); + } + if (choice.finish_reason) { + output.rawStopReason = choice.finish_reason; + const finishReasonResult = mapStopReason(choice.finish_reason); + output.stopReason = finishReasonResult.stopReason; + if (finishReasonResult.errorMessage) { + output.errorMessage = finishReasonResult.errorMessage; + } + hasFinishReason = true; + } + if (choice.delta) { + if (choice.delta.content !== null && + choice.delta.content !== undefined && + choice.delta.content.length > 0) { + const block = ensureTextBlock(); + block.text += choice.delta.content; + stream.push({ + type: "text_delta", + contentIndex: getContentIndex(block), + delta: choice.delta.content, + partial: output, + }); + } + // Some endpoints return reasoning in reasoning_content (llama.cpp), + // or reasoning (other openai compatible endpoints) + // Use the first non-empty reasoning field to avoid duplication + // (e.g., chutes.ai returns both reasoning_content and reasoning with same content) + const reasoningFields = ["reasoning_content", "reasoning", "reasoning_text"]; + const deltaFields = choice.delta; + let foundReasoningField = null; + for (const field of reasoningFields) { + const value = deltaFields[field]; + if (typeof value === "string" && value.length > 0) { + foundReasoningField = field; + break; + } + } + if (foundReasoningField) { + const delta = deltaFields[foundReasoningField]; + if (typeof delta === "string" && delta.length > 0) { + const thinkingSignature = model.provider === "opencode-go" && foundReasoningField === "reasoning" + ? "reasoning_content" + : foundReasoningField; + const block = ensureThinkingBlock(thinkingSignature); + block.thinking += delta; + stream.push({ + type: "thinking_delta", + contentIndex: getContentIndex(block), + delta, + partial: output, + }); + } + } + if (choice?.delta?.tool_calls) { + for (const toolCall of choice.delta.tool_calls) { + const block = ensureToolCallBlock(toolCall); + if (!block.id && toolCall.id) { + block.id = toolCall.id; + toolCallBlocksById.set(toolCall.id, block); + } + const name = toolCall.function?.name ?? toolCall.custom?.name; + if (!block.name && name) { + block.name = name; + } + let delta = ""; + if (toolCall.function?.arguments) { + delta = toolCall.function.arguments; + block.partialArgs = (block.partialArgs ?? "") + toolCall.function.arguments; + block.arguments = (0,_utils_json_parse_js__WEBPACK_IMPORTED_MODULE_7__/* .parseStreamingJson */ .o2)(block.partialArgs); + } + else if (toolCall.custom?.input) { + const nextInput = getCustomToolCallInput(block) + toolCall.custom.input; + delta = appendCustomToolCallInput(block, nextInput, false) ?? ""; + } + stream.push({ + type: "toolcall_delta", + contentIndex: getContentIndex(block), + delta, + partial: output, + }); + } + } + const reasoningDetails = choice.delta.reasoning_details; + if (Array.isArray(reasoningDetails)) { + for (const detail of reasoningDetails) { + if (!isOpenAIReasoningDetail(detail)) + continue; + ensureThinkingBlock(""); + streamedReasoningDetails ??= []; + // Keep provider replay data in the existing signature slot. OpenRouter streams + // reasoning_details as deltas: consecutive text/summary deltas are merged into + // logical entries, while encrypted entries remain opaque and discrete. + appendOpenAIReasoningDetail(streamedReasoningDetails, detail); + } + } + } + } + for (const block of blocks) { + finishBlock(block); + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted") { + throw new Error("Request was aborted"); + } + if (!hasFinishReason && !compat.supportsFinishReason) { + output.stopReason = output.content.some((block) => block.type === "toolCall") ? "toolUse" : "stop"; + } + if (output.stopReason === "error") { + throw new Error(output.errorMessage || "Provider returned an error stop reason"); + } + if ((compat.supportsFinishReason && !hasFinishReason) || output.stopReason === "pending") { + throw new Error("Stream ended without finish_reason"); + } + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } + catch (error) { + for (const block of output.content) { + if (block.type === "thinking") { + applyStreamedReasoningDetails(block); + } + delete block.index; + // Streaming scratch buffers are only used during parsing; never persist them. + delete block.partialArgs; + delete block.customInput; + delete block.streamIndex; + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = (0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_8__/* .formatProviderError */ .lR)((0,_utils_error_body_js__WEBPACK_IMPORTED_MODULE_8__/* .normalizeProviderError */ .Jo)(error)); + // Some providers via OpenRouter give additional information in this field. + // normalizeProviderError already stringifies the parsed body (error.error) + // into errorMessage, so only append the raw metadata when it is not already + // present to avoid double-printing it. + const rawMetadata = error?.error?.metadata?.raw; + if (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) { + output.errorMessage += `\n${rawMetadata}`; + } + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + return stream; +}; +const streamSimple = (model, context, options) => { + getClientApiKey(model.provider, options?.apiKey, options?.headers); + const base = { + ...(0,_simple_options_js__WEBPACK_IMPORTED_MODULE_9__/* .buildBaseOptions */ .QP)(model, context, options, options?.apiKey), + toolChoice: options?.toolChoice, + }; + const clampedReasoning = options?.reasoning ? (0,_models_js__WEBPACK_IMPORTED_MODULE_10__/* .clampThinkingLevel */ .Kt)(model, options.reasoning) : undefined; + const reasoningEffort = clampedReasoning === "off" ? undefined : clampedReasoning; + return stream(model, context, { + ...base, + reasoningEffort, + thinkingBudgets: options?.thinkingBudgets, + }); +}; +function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId, compat = getCompat(model)) { + const headers = { "User-Agent": (0,_utils_pi_user_agent_js__WEBPACK_IMPORTED_MODULE_11__/* .getPiUserAgent */ .w)(), ...model.headers }; + if (model.provider === "github-copilot") { + const hasImages = (0,_github_copilot_headers_js__WEBPACK_IMPORTED_MODULE_12__/* .hasCopilotVisionInput */ .d1)(context.messages); + const copilotHeaders = (0,_github_copilot_headers_js__WEBPACK_IMPORTED_MODULE_12__/* .buildCopilotDynamicHeaders */ .G0)({ + messages: context.messages, + hasImages, + }); + Object.assign(headers, copilotHeaders); + } + if (sessionId && compat.sendSessionAffinityHeaders) { + if (compat.sessionAffinityFormat === "openrouter") { + headers["x-session-id"] = sessionId; + } + else { + if (compat.sessionAffinityFormat === "openai") { + headers.session_id = sessionId; + } + headers["x-client-request-id"] = sessionId; + headers["x-session-affinity"] = sessionId; + } + } + // Merge options headers last so they can override defaults + if (optionsHeaders) { + Object.assign(headers, optionsHeaders); + } + return new openai__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + fetch, + defaultHeaders: headers, + }); +} +function buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env), grammarToolInputProperties = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .createGrammarToolInputProperties */ .PJ)((0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .getDeclaredTools */ .Wg)(context.messages), compat.supportsOpenAIGrammarTools)) { + const transcriptTools = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveTranscriptTools */ .eW)(context.messages, compat.supportsMidConvoSystemMessages === true && compat.supportsMidConvoToolAdditions === true); + const messages = convertMessages(model, context, compat, { + grammarToolInputProperties, + }); + const cacheControl = getCompatCacheControl(compat, cacheRetention); + const params = { + model: model.id, + messages, + stream: true, + prompt_cache_key: (model.baseUrl.includes("api.openai.com") && cacheRetention !== "none") || + (cacheRetention === "long" && compat.supportsLongCacheRetention) + ? (0,_openai_prompt_cache_js__WEBPACK_IMPORTED_MODULE_13__/* .clampOpenAIPromptCacheKey */ .l)(options?.sessionId) + : undefined, + prompt_cache_retention: cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : undefined, + }; + if (compat.supportsUsageInStreaming !== false) { + params.stream_options = { include_usage: true }; + } + if (compat.supportsStore) { + params.store = false; + } + if (options?.maxTokens) { + if (compat.maxTokensField === "max_tokens") { + params.max_tokens = options.maxTokens; + } + else { + params.max_completion_tokens = options.maxTokens; + } + } + if (options?.temperature !== undefined) { + params.temperature = options.temperature; + } + if (transcriptTools.requestTools.length > 0) { + params.tools = convertTools(transcriptTools.requestTools, compat); + if (compat.zaiToolStream) { + params.tool_stream = true; + } + } + else if (hasToolHistory(context.messages)) { + // Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results + params.tools = []; + } + if (cacheControl) { + applyAnthropicCacheControl(messages, params.tools, cacheControl); + } + if (options?.toolChoice) { + params.tool_choice = options.toolChoice; + } + if (compat.vllmPriority !== undefined) { + params.priority = compat.vllmPriority; + } + const thinkingTokenBudgetField = resolveThinkingTokenBudgetField(compat); + const thinkingBudget = resolveClampedThinkingBudget(model, options, params); + if (compat.thinkingFormat === "zai" && model.reasoning) { + const zaiParams = params; + zaiParams.thinking = options?.reasoningEffort ? { type: "enabled", clear_thinking: false } : { type: "disabled" }; + if (options?.reasoningEffort && compat.supportsReasoningEffort) { + const mappedEffort = model.thinkingLevelMap?.[options.reasoningEffort]; + const effort = mappedEffort === undefined ? options.reasoningEffort : mappedEffort; + if (typeof effort === "string") { + zaiParams.reasoning_effort = effort; + } + } + } + else if (compat.thinkingFormat === "qwen" && model.reasoning) { + params.enable_thinking = !!options?.reasoningEffort; + if (options?.reasoningEffort && compat.supportsReasoningEffort) { + const effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + if (typeof effort === "string") { + params.reasoning_effort = effort; + } + } + } + else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) { + params.chat_template_kwargs = { + enable_thinking: !!options?.reasoningEffort, + preserve_thinking: true, + }; + } + else if (compat.thinkingFormat === "chat-template" && model.reasoning) { + const chatTemplateKwargs = buildChatTemplateValues(model, options, compat.chatTemplateKwargs, thinkingBudget); + if (chatTemplateKwargs) { + params.chat_template_kwargs = chatTemplateKwargs; + } + } + else if (compat.thinkingFormat === "baseten" && model.reasoning) { + const basetenParams = params; + const chatTemplateArgs = buildChatTemplateValues(model, options, compat.chatTemplateArgs, thinkingBudget); + if (chatTemplateArgs) { + basetenParams.chat_template_args = chatTemplateArgs; + } + if (compat.supportsReasoningEffort) { + const requestedEffort = options?.reasoningEffort; + const mappedEffort = requestedEffort ? model.thinkingLevelMap?.[requestedEffort] : model.thinkingLevelMap?.off; + const effort = mappedEffort === undefined ? requestedEffort : mappedEffort; + if (typeof effort === "string") { + basetenParams.reasoning_effort = effort; + } + } + } + else if (compat.thinkingFormat === "deepseek" && model.reasoning) { + if (options?.reasoningEffort) { + params.thinking = { type: "enabled" }; + } + else if (model.thinkingLevelMap?.off !== null) { + params.thinking = { type: "disabled" }; + } + if (options?.reasoningEffort && compat.supportsReasoningEffort) { + params.reasoning_effort = + model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + } + } + else if (compat.thinkingFormat === "openrouter" && model.reasoning) { + // OpenRouter normalizes reasoning across providers via a nested reasoning object. + const openRouterParams = params; + if (options?.reasoningEffort) { + openRouterParams.reasoning = { + effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort, + }; + } + else if (model.thinkingLevelMap?.off !== null) { + openRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? "none" }; + } + } + else if (compat.thinkingFormat === "ant-ling" && model.reasoning && options?.reasoningEffort) { + const effort = model.thinkingLevelMap?.[options.reasoningEffort]; + if (typeof effort === "string") { + params.reasoning = { effort }; + } + } + else if (compat.thinkingFormat === "together" && model.reasoning) { + const togetherParams = params; + togetherParams.reasoning = { enabled: !!options?.reasoningEffort }; + if (options?.reasoningEffort && compat.supportsReasoningEffort) { + togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + } + } + else if (compat.thinkingFormat === "string-thinking" && model.reasoning) { + const stringThinkingParams = params; + if (options?.reasoningEffort) { + stringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + } + else if (model.thinkingLevelMap?.off !== null) { + stringThinkingParams.thinking = model.thinkingLevelMap?.off ?? "none"; + } + } + else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) { + // OpenAI-style reasoning_effort + params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + } + else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) { + const offValue = model.thinkingLevelMap?.off; + if (typeof offValue === "string") { + params.reasoning_effort = offValue; + } + } + // Cap reasoning with a top-level budget field. Independent of thinkingFormat: the + // same server can serve zai, qwen or chat-template models. Reasoning and the answer + // share max_tokens here, so an uncapped reasoning phase can consume the whole + // response and leave no answer and no tool call. + if (thinkingTokenBudgetField && thinkingBudget !== undefined) { + Object.assign(params, { [thinkingTokenBudgetField]: thinkingBudget }); + } + // OpenRouter provider routing preferences + if (model.compat?.openRouterRouting) { + params.provider = model.compat.openRouterRouting; + } + // Vercel AI Gateway provider routing preferences + if (model.compat?.vercelGatewayRouting) { + const routing = model.compat.vercelGatewayRouting; + if (routing.only || routing.order) { + const gatewayOptions = {}; + if (routing.only) + gatewayOptions.only = routing.only; + if (routing.order) + gatewayOptions.order = routing.order; + params.providerOptions = { gateway: gatewayOptions }; + } + } + // Last so custom keys override the named request fields. + if (options?.samplingParams) { + Object.assign(params, options.samplingParams); + } + return params; +} +function resolveThinkingTokenBudgetField(compat) { + if (compat.thinkingTokenBudgetField) + return compat.thinkingTokenBudgetField; + if (compat.supportsThinkingTokenBudget) + return "thinking_token_budget"; + return undefined; +} +function resolveClampedThinkingBudget(model, options, params) { + if (!options?.reasoningEffort || !model.reasoning) + return undefined; + const ceiling = params.max_tokens ?? params.max_completion_tokens ?? model.maxTokens; + const budget = (0,_simple_options_js__WEBPACK_IMPORTED_MODULE_9__/* .clampThinkingBudgetToAnswerRoom */ .z9)((0,_simple_options_js__WEBPACK_IMPORTED_MODULE_9__/* .thinkingBudgetForLevel */ .pT)(options.reasoningEffort, options.thinkingBudgets), ceiling); + return budget > 0 ? budget : undefined; +} +function buildChatTemplateValues(model, options, values, thinkingBudget) { + const resolvedValues = {}; + for (const [key, value] of Object.entries(values)) { + const resolved = resolveChatTemplateKwargValue(model, options, value, thinkingBudget); + if (resolved !== undefined) { + resolvedValues[key] = resolved; + } + } + return Object.keys(resolvedValues).length > 0 ? resolvedValues : undefined; +} +function resolveChatTemplateKwargValue(model, options, value, thinkingBudget) { + if (typeof value !== "object" || value === null) { + return value; + } + const reasoningEffort = options?.reasoningEffort; + if (!reasoningEffort && value.omitWhenOff) { + return undefined; + } + if (value.$var === "thinking.enabled") { + return !!reasoningEffort; + } + if (value.$var === "thinking.budget") { + return thinkingBudget; + } + const mappedValue = reasoningEffort ? model.thinkingLevelMap?.[reasoningEffort] : model.thinkingLevelMap?.off; + return mappedValue === undefined ? reasoningEffort : typeof mappedValue === "string" ? mappedValue : undefined; +} +function getCompatCacheControl(compat, cacheRetention) { + if (compat.cacheControlFormat !== "anthropic" || cacheRetention === "none") { + return undefined; + } + const ttl = cacheRetention === "long" && compat.supportsLongCacheRetention ? "1h" : undefined; + return { type: "ephemeral", ...(ttl ? { ttl } : {}) }; +} +function applyAnthropicCacheControl(messages, tools, cacheControl) { + addCacheControlToSystemPrompt(messages, cacheControl); + addCacheControlToLastTool(tools, cacheControl); + addCacheControlToLastConversationMessage(messages, cacheControl); +} +function addCacheControlToSystemPrompt(messages, cacheControl) { + for (const message of messages) { + if (message.role === "system" || message.role === "developer") { + addCacheControlToInstructionMessage(message, cacheControl); + return; + } + } +} +function addCacheControlToLastConversationMessage(messages, cacheControl) { + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.role === "user" || message.role === "assistant" || message.role === "tool") { + if (addCacheControlToMessage(message, cacheControl)) { + return; + } + } + } +} +function addCacheControlToLastTool(tools, cacheControl) { + if (!tools || tools.length === 0) { + return; + } + const lastTool = tools[tools.length - 1]; + lastTool.cache_control = cacheControl; +} +function addCacheControlToInstructionMessage(message, cacheControl) { + return addCacheControlToTextContent(message, cacheControl); +} +function addCacheControlToMessage(message, cacheControl) { + if (message.role === "user" || message.role === "assistant" || message.role === "tool") { + return addCacheControlToTextContent(message, cacheControl); + } + return false; +} +function addCacheControlToTextContent(message, cacheControl) { + const content = message.content; + if (typeof content === "string") { + if (content.length === 0) { + return false; + } + message.content = [ + { + type: "text", + text: content, + cache_control: cacheControl, + }, + ]; + return true; + } + if (!Array.isArray(content)) { + return false; + } + for (let i = content.length - 1; i >= 0; i--) { + const part = content[i]; + if (part?.type === "text") { + const textPart = part; + textPart.cache_control = cacheControl; + return true; + } + } + return false; +} +function convertMessages(model, context, compat, options) { + const normalizedContext = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveTranscript */ .lw)(context, compat.supportsMidConvoSystemMessages); + const params = []; + const normalizeToolCallId = (id) => { + // Handle pipe-separated IDs from OpenAI Responses API + // Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =) + // These come from providers like github-copilot, openai-codex, opencode + // Extract just the call_id part and normalize it + // Multiple tool calls in the same turn can share call_id but differ by item_id. + // Preserve item-level uniqueness when replaying into Chat Completions, which + // requires distinct tool call ids. + if (id.includes("|")) { + // Sanitize to allowed chars and truncate to 40 chars (OpenAI limit) + const separatorIndex = id.indexOf("|"); + const callId = id.slice(0, separatorIndex).replace(/[^a-zA-Z0-9_-]/g, "_"); + const itemId = id.slice(separatorIndex + 1).replace(/[^a-zA-Z0-9_-]/g, "_"); + const combinedId = itemId.length > 0 ? `${callId}_${itemId}` : callId; + if (combinedId.length <= 40) { + return combinedId; + } + const hash = (0,_utils_hash_js__WEBPACK_IMPORTED_MODULE_14__/* .shortHash */ .B)(id).slice(0, 8); + const prefix = callId.slice(0, Math.max(1, 40 - hash.length - 1)); + return `${prefix}_${hash}`; + } + if (model.provider === "openai") + return id.length > 40 ? id.slice(0, 40) : id; + return id; + }; + const transformedMessages = (0,_transform_messages_js__WEBPACK_IMPORTED_MODULE_15__/* .transformMessages */ .b)(normalizedContext.messages, model, (id) => normalizeToolCallId(id)); + const transcriptTools = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_3__/* .resolveTranscriptTools */ .eW)(normalizedContext.messages, compat.supportsMidConvoSystemMessages === true && compat.supportsMidConvoToolAdditions === true); + const instructionRole = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system"; + let lastRole = null; + for (let i = 0; i < transformedMessages.length; i++) { + const msg = transformedMessages[i]; + // Some providers don't allow user messages directly after tool results + // Insert a synthetic assistant message to bridge the gap + if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") { + params.push({ + role: "assistant", + content: "I have processed the tool results.", + }); + } + if (msg.role === "system") { + const addedTools = i > 0 && transcriptTools.anchorsAdditions ? (msg.toolsAdded ?? []) : []; + if (addedTools.length > 0) { + const kimiToolMessage = { + role: "system", + tools: convertTools(addedTools, compat), + }; + params.push(kimiToolMessage); + } + const text = i === 0 ? (0,_utils_text_js__WEBPACK_IMPORTED_MODULE_16__/* .getSystemMessageText */ .Y8)(msg) : (0,_utils_text_js__WEBPACK_IMPORTED_MODULE_16__/* .renderSystemMessageUpdate */ .m$)(msg); + if (text.length > 0) { + params.push({ role: instructionRole, content: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(text) }); + } + } + else if (msg.role === "user") { + if (typeof msg.content === "string") { + params.push({ + role: "user", + content: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(msg.content), + }); + } + else { + const content = msg.content.map((item) => { + if (item.type === "text") { + return { + type: "text", + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(item.text), + }; + } + else { + return { + type: "image_url", + image_url: { + url: `data:${item.mimeType};base64,${item.data}`, + }, + }; + } + }); + if (content.length === 0) + continue; + params.push({ + role: "user", + content, + }); + } + } + else if (msg.role === "assistant") { + // Some providers don't accept null content, use empty string instead + const assistantMsg = { + role: "assistant", + content: compat.requiresAssistantAfterToolResult ? "" : null, + }; + const assistantTextParts = msg.content + .filter(isTextContentBlock) + .filter((block) => block.text.trim().length > 0) + .map((block) => ({ + type: "text", + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(block.text), + })); + const assistantText = assistantTextParts.map((part) => part.text).join(""); + const thinkingBlocks = msg.content.filter(isThinkingContentBlock); + const toolCalls = msg.content.filter(isToolCallBlock); + const signedReasoningDetails = thinkingBlocks + .map((block) => parseOpenAIReasoningDetails(block.thinkingSignature)) + .find((details) => details !== undefined); + const legacyReasoningDetails = toolCalls + .map((toolCall) => parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)) + .filter((detail) => detail !== undefined); + const preservedReasoningDetails = signedReasoningDetails ?? (legacyReasoningDetails.length > 0 ? legacyReasoningDetails : undefined); + const nonEmptyThinkingBlocks = thinkingBlocks.filter((block) => block.thinking.trim().length > 0); + if (nonEmptyThinkingBlocks.length > 0) { + if (compat.requiresThinkingAsText) { + // Convert thinking blocks to plain text (no tags to avoid model mimicking them) + const thinkingText = nonEmptyThinkingBlocks + .map((block) => (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(block.thinking)) + .join("\n\n"); + assistantMsg.content = [{ type: "text", text: thinkingText }, ...assistantTextParts]; + } + else { + // Always send assistant content as a plain string (OpenAI Chat Completions + // API standard format). Sending as an array of {type:"text", text:"..."} + // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via + // NVIDIA NIM) to mirror the content-block structure literally in their + // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}]. + if (assistantText.length > 0) { + assistantMsg.content = assistantText; + } + // reasoning_details is the structured alternative to a raw reasoning field. + if (!preservedReasoningDetails) { + // Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss) + let signature = nonEmptyThinkingBlocks[0].thinkingSignature; + if (model.provider === "opencode-go" && signature === "reasoning") { + signature = "reasoning_content"; + } + if (signature && isOpenAICompletionsReasoningField(signature)) { + assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n"); + } + } + } + } + else if (assistantText.length > 0) { + // Always send assistant content as a plain string (OpenAI Chat Completions + // API standard format). Sending as an array of {type:"text", text:"..."} + // objects is non-standard and causes some models (e.g. DeepSeek V3.2 via + // NVIDIA NIM) to mirror the content-block structure literally in their + // output, producing recursive nesting like [{'type':'text','text':'[{...}]'}]. + assistantMsg.content = assistantText; + } + if (toolCalls.length > 0) { + assistantMsg.tool_calls = toolCalls.map((tc) => { + const customInputProperty = options?.grammarToolInputProperties?.get(tc.name); + if (customInputProperty !== undefined) { + return { + id: tc.id, + type: "custom", + custom: { + name: tc.name, + input: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)((0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .getGrammarToolInput */ .gY)(tc.name, tc.arguments, customInputProperty)), + }, + }; + } + return { + id: tc.id, + type: "function", + function: { + name: tc.name, + arguments: JSON.stringify(tc.arguments), + }, + }; + }); + } + if (preservedReasoningDetails) { + assistantMsg.reasoning_details = preservedReasoningDetails; + } + if (compat.requiresReasoningContentOnAssistantMessages && + model.reasoning && + assistantMsg.reasoning_content === undefined) { + assistantMsg.reasoning_content = ""; + } + // Skip assistant messages that have no content and no tool calls. + // Some providers require "either content or tool_calls, but not none". + // Other providers also don't accept empty assistant messages. + // This handles aborted assistant responses that got no content. + const content = assistantMsg.content; + const hasContent = content !== null && + content !== undefined && + (typeof content === "string" ? content.length > 0 : content.length > 0); + if (!hasContent && !assistantMsg.tool_calls) { + continue; + } + params.push(assistantMsg); + } + else if (msg.role === "toolResult") { + const imageBlocks = []; + let j = i; + for (; j < transformedMessages.length && transformedMessages[j].role === "toolResult"; j++) { + const toolMsg = transformedMessages[j]; + // Extract text and image content + const textResult = toolMsg.content + .filter(isTextContentBlock) + .map((block) => block.text) + .join("\n"); + const hasImages = toolMsg.content.some((c) => c.type === "image"); + // Always send tool result with text (or placeholder if only images) + const hasText = textResult.length > 0; + const toolResultText = hasText ? textResult : hasImages ? "(see attached image)" : "(no tool output)"; + // Some providers require the 'name' field in tool results + const toolResultMsg = { + role: "tool", + content: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_17__/* .sanitizeSurrogates */ .J)(toolResultText), + tool_call_id: toolMsg.toolCallId, + }; + if (compat.requiresToolResultName && toolMsg.toolName) { + toolResultMsg.name = toolMsg.toolName; + } + params.push(toolResultMsg); + if (hasImages && model.input.includes("image")) { + for (const block of toolMsg.content) { + if (isImageContentBlock(block)) { + imageBlocks.push({ + type: "image_url", + image_url: { + url: `data:${block.mimeType};base64,${block.data}`, + }, + }); + } + } + } + } + i = j - 1; + if (imageBlocks.length > 0) { + if (compat.requiresAssistantAfterToolResult) { + params.push({ + role: "assistant", + content: "I have processed the tool results.", + }); + } + params.push({ + role: "user", + content: [ + { + type: "text", + text: "Attached image(s) from tool result:", + }, + ...imageBlocks, + ], + }); + lastRole = "user"; + } + else { + lastRole = "toolResult"; + } + continue; + } + lastRole = msg.role; + } + return params; +} +function convertTools(tools, compat) { + return tools.map((tool) => { + const grammar = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .resolveGrammarConstrainedSampling */ .TH)(tool, compat.supportsOpenAIGrammarTools); + if (grammar) { + return { + type: "custom", + custom: { + name: tool.name, + description: tool.description, + format: { + type: "grammar", + grammar: { + syntax: grammar.format, + definition: grammar.definition, + }, + }, + }, + }; + } + const strict = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .resolveJsonSchemaStrictSampling */ ._F)(tool, compat.supportsStrictMode !== false); + return { + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_4__/* .getJsonSchemaToolParameters */ .Km)(tool, strict), + // Only include strict if provider supports it. Some reject unknown fields. + ...(compat.supportsStrictMode !== false && { strict: strict ?? false }), + }, + }; + }); +} +function parseChunkUsage(rawUsage, model) { + const promptTokens = rawUsage.prompt_tokens || 0; + const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? rawUsage.cached_tokens ?? 0; + const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0; + // Follow documented OpenAI/OpenRouter semantics: cached_tokens is cache-read + // tokens (hits). Providers disagree on placement: OpenAI/OpenRouter use + // prompt_tokens_details.cached_tokens, DeepSeek uses prompt_cache_hit_tokens, + // and Kimi documents top-level usage.cached_tokens on the final usage chunk. + // OpenAI does not document or emit cache_write_tokens, but + // OpenRouter-compatible providers can include it as a separate write count. + // OpenRouter's own provider/tests affirm the separate mapping: + // https://github.com/OpenRouterTeam/ai-sdk-provider/pull/409 + // Do not subtract writes from cached_tokens, otherwise spec-compliant + // providers are under-reported. DS4 mirrors this contract too: + // https://github.com/antirez/ds4/pull/29 + const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens); + // OpenAI completion_tokens already includes reasoning_tokens. + const outputTokens = rawUsage.completion_tokens || 0; + const usage = { + input, + output: outputTokens, + cacheRead: cacheReadTokens, + cacheWrite: cacheWriteTokens, + reasoning: rawUsage.completion_tokens_details?.reasoning_tokens || 0, + totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; + (0,_models_js__WEBPACK_IMPORTED_MODULE_10__/* .calculateCost */ .yN)(model, usage); + return usage; +} +function mapStopReason(reason) { + if (reason === null) + return { stopReason: "stop" }; + switch (reason) { + case "stop": + case "end": + return { stopReason: "stop" }; + case "length": + return { stopReason: "length" }; + case "function_call": + case "tool_calls": + return { stopReason: "toolUse" }; + case "content_filter": + return { stopReason: "error", errorMessage: "Provider finish_reason: content_filter" }; + case "network_error": + return { stopReason: "error", errorMessage: "Provider finish_reason: network_error" }; + default: + return { + stopReason: "error", + errorMessage: `Provider finish_reason: ${reason}`, + }; + } +} +/** + * Auto-detect compatibility settings from provider name and baseUrl. + * Used as the base when model.compat is not set; explicit model.compat + * entries override these detected values. + */ +function detectCompat(model) { + const provider = model.provider; + const baseUrl = model.baseUrl; + const isZai = provider === "zai" || + provider === "zai-coding-cn" || + baseUrl.includes("api.z.ai") || + baseUrl.includes("open.bigmodel.cn"); + const isTogether = provider === "together" || baseUrl.includes("api.together.ai") || baseUrl.includes("api.together.xyz"); + const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot."); + const isOpenRouter = provider === "openrouter" || baseUrl.includes("openrouter.ai"); + const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com"); + const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com"); + const isNvidia = provider === "nvidia" || baseUrl.includes("integrate.api.nvidia.com"); + const isAntLing = provider === "ant-ling" || baseUrl.includes("api.ant-ling.com"); + const isCerebras = provider === "cerebras" || baseUrl.includes("cerebras.ai"); + const isDeepSeek = provider === "deepseek" || baseUrl.toLowerCase().includes("deepseek.com"); + const isNonStandard = isNvidia || + isCerebras || + provider === "xai" || + baseUrl.includes("api.x.ai") || + isTogether || + baseUrl.includes("chutes.ai") || + isDeepSeek || + isZai || + isMoonshot || + provider === "opencode" || + baseUrl.includes("opencode.ai") || + isCloudflareWorkersAI || + isCloudflareAiGateway || + isAntLing; + const useMaxTokens = baseUrl.includes("chutes.ai") || + isDeepSeek || + isMoonshot || + isCloudflareAiGateway || + isTogether || + isNvidia || + isAntLing || + isZai; + const isGrok = provider === "xai" || baseUrl.includes("api.x.ai"); + const isOpenRouterDeveloperRoleModel = isOpenRouter && (model.id.startsWith("anthropic/") || model.id.startsWith("openai/")); + const cacheControlFormat = provider === "openrouter" && model.id.startsWith("anthropic/") ? "anthropic" : undefined; + return { + supportsStore: !isNonStandard, + supportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter), + supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing, + supportsUsageInStreaming: true, + supportsFinishReason: true, + maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens", + requiresToolResultName: false, + requiresAssistantAfterToolResult: false, + requiresThinkingAsText: false, + requiresReasoningContentOnAssistantMessages: isDeepSeek, + thinkingFormat: isDeepSeek + ? "deepseek" + : isZai + ? "zai" + : isTogether + ? "together" + : isAntLing + ? "ant-ling" + : isOpenRouter + ? "openrouter" + : "openai", + openRouterRouting: {}, + vercelGatewayRouting: {}, + chatTemplateKwargs: {}, + chatTemplateArgs: {}, + zaiToolStream: false, + supportsThinkingTokenBudget: false, + thinkingTokenBudgetField: undefined, + supportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isCerebras, + supportsOpenAIGrammarTools: false, + supportsMidConvoSystemMessages: false, + supportsMidConvoToolAdditions: false, + cacheControlFormat, + sendSessionAffinityHeaders: isOpenRouter, + sessionAffinityFormat: isOpenRouter ? "openrouter" : "openai", + supportsLongCacheRetention: !(isTogether || + isCloudflareWorkersAI || + isCloudflareAiGateway || + isNvidia || + isAntLing), + }; +} +/** + * Get resolved compatibility settings for a model. + * Auto-detects from provider/URL then overrides with explicit model.compat. + */ +function getCompat(model) { + const detected = detectCompat(model); + if (!model.compat) + return detected; + return { + supportsStore: model.compat.supportsStore ?? detected.supportsStore, + supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole, + supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort, + supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming, + supportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason, + maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField, + requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName, + requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult, + requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText, + requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ?? + detected.requiresReasoningContentOnAssistantMessages, + thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat, + openRouterRouting: model.compat.openRouterRouting ?? {}, + vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting, + chatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs, + chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs, + zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream, + supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget, + thinkingTokenBudgetField: model.compat.thinkingTokenBudgetField ?? detected.thinkingTokenBudgetField, + supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode, + supportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools, + supportsMidConvoSystemMessages: model.compat.supportsMidConvoSystemMessages ?? detected.supportsMidConvoSystemMessages, + supportsMidConvoToolAdditions: model.compat.supportsMidConvoToolAdditions ?? detected.supportsMidConvoToolAdditions, + cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat, + sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders, + sessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat, + supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention, + vllmPriority: model.compat.vllmPriority, + }; +} +//# sourceMappingURL=openai-completions.js.map + +/***/ }), + +/***/ 95304: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ l: () => (/* binding */ clampOpenAIPromptCacheKey) +/* harmony export */ }); +/* unused harmony export OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH */ +const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64; +function clampOpenAIPromptCacheKey(key) { + if (key === undefined) + return undefined; + const chars = Array.from(key); + if (chars.length <= OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH) + return key; + return chars.slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).join(""); +} +//# sourceMappingURL=openai-prompt-cache.js.map + +/***/ }), + +/***/ 1901: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ B: () => (/* binding */ shortHash) +/* harmony export */ }); +/** Fast deterministic hash to shorten long strings */ +function shortHash(str) { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < str.length; i++) { + const ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36); +} +//# sourceMappingURL=hash.js.map + +/***/ }), + +/***/ 55278: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ w: () => (/* binding */ getPiUserAgent) +/* harmony export */ }); +function loadNodeOs() { + if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) { + return null; + } + return process.getBuiltinModule?.("node:os") ?? null; +} +// Keep runtime OS loading browser-safe. A top-level runtime import of node:os breaks browser/Vite builds. +const nodeOs = loadNodeOs(); +function getPiUserAgent() { + return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)"; +} +//# sourceMappingURL=pi-user-agent.js.map + +/***/ }) + +}; diff --git a/dist/action/804.index.js b/dist/action/804.index.js new file mode 100644 index 000000000..753e15c83 --- /dev/null +++ b/dist/action/804.index.js @@ -0,0 +1,699 @@ +export const id = 804; +export const ids = [804]; +export const modules = { + +/***/ 37776: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Km: () => (/* binding */ getJsonSchemaToolParameters), +/* harmony export */ PJ: () => (/* binding */ createGrammarToolInputProperties), +/* harmony export */ TH: () => (/* binding */ resolveGrammarConstrainedSampling), +/* harmony export */ _F: () => (/* binding */ resolveJsonSchemaStrictSampling), +/* harmony export */ eW: () => (/* binding */ appendGrammarToolInputJsonDelta), +/* harmony export */ gY: () => (/* binding */ getGrammarToolInput) +/* harmony export */ }); +/* unused harmony export makeStrictJsonSchema */ +class UnsupportedStrictJsonSchemaError extends Error { +} +const UNSUPPORTED_STRICT_SCHEMA_KEYS = [ + "$ref", + "$defs", + "definitions", + "allOf", + "oneOf", + "patternProperties", + "dependentSchemas", + "dependencies", + "unevaluatedProperties", + "propertyNames", + "contains", + "prefixItems", + "not", + "if", + "then", + "else", +]; +function isJsonSchemaObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function isStructuredSchema(schema) { + if (!isJsonSchemaObject(schema)) + return false; + const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : []; + return (types.includes("object") || + types.includes("array") || + schema.properties !== undefined || + schema.items !== undefined); +} +function schemaAllowsNull(schema) { + if (!isJsonSchemaObject(schema)) + return false; + if (schema.type === "null" || (Array.isArray(schema.type) && schema.type.includes("null"))) + return true; + if (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null))) + return true; + return Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant)); +} +function makeJsonSchemaNodeStrict(schema) { + if (!isJsonSchemaObject(schema)) { + throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported"); + } + for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) { + if (schema[key] !== undefined) { + throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`); + } + } + if (schema.anyOf !== undefined) { + if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) { + throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema"); + } + for (const variant of schema.anyOf) { + if (isStructuredSchema(variant)) { + throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported"); + } + makeJsonSchemaNodeStrict(variant); + } + } + if (schema.items !== undefined) { + if (Array.isArray(schema.items)) { + throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported"); + } + makeJsonSchemaNodeStrict(schema.items); + } + const isObjectSchema = schema.type === "object"; + if (schema.properties !== undefined && !isObjectSchema) { + throw new UnsupportedStrictJsonSchemaError("properties require type object"); + } + if (!isObjectSchema) + return; + if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) { + throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported"); + } + if (schema.properties !== undefined && !isJsonSchemaObject(schema.properties)) { + throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map"); + } + if (schema.required !== undefined && + (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) { + throw new UnsupportedStrictJsonSchemaError("object required must be a string array"); + } + const properties = schema.properties ?? {}; + const propertyNames = Object.keys(properties); + const required = new Set(Array.isArray(schema.required) ? schema.required : []); + if ([...required].some((key) => !propertyNames.includes(key))) { + throw new UnsupportedStrictJsonSchemaError("required contains an unknown property"); + } + for (const [key, property] of Object.entries(properties)) { + makeJsonSchemaNodeStrict(property); + if (!required.has(key) && !schemaAllowsNull(property)) { + properties[key] = { anyOf: [property, { type: "null" }] }; + } + } + schema.required = propertyNames; + schema.additionalProperties = false; +} +/** Convert a tool schema to the strict subset expected by provider constrained sampling. */ +function makeStrictJsonSchema(schema) { + const cloned = structuredClone(schema); + if (!isJsonSchemaObject(cloned)) { + throw new UnsupportedStrictJsonSchemaError("root schema must have type object"); + } + makeJsonSchemaNodeStrict(cloned); + if (cloned.type !== "object") { + throw new UnsupportedStrictJsonSchemaError("root schema must have type object"); + } + return cloned; +} +function getJsonSchemaToolParameters(tool, strict) { + return (strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters); +} +function getGrammarToolInput(toolName, arguments_, inputProperty) { + const input = arguments_[inputProperty]; + if (typeof input !== "string") { + throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`); + } + return input; +} +function appendGrammarToolInputJsonDelta(buffer, inputProperty, nextInput, close) { + if (buffer.closed) { + if (close && nextInput === buffer.input) + return undefined; + throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`); + } + if (!nextInput.startsWith(buffer.input)) { + throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`); + } + const inputDelta = nextInput.slice(buffer.input.length); + if (!close && inputDelta.length === 0) + return undefined; + let delta = ""; + if (!buffer.started) { + delta += `{${JSON.stringify(inputProperty)}:"`; + buffer.started = true; + } + delta += JSON.stringify(inputDelta).slice(1, -1); + buffer.input = nextInput; + if (close) { + delta += '"}'; + buffer.closed = true; + } + return delta; +} +function inferGrammarInputProperty(tool) { + const schema = tool.parameters; + if (schema.type !== "object") { + throw new Error("grammar constrained sampling requires an object parameter schema"); + } + if (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== "string") { + throw new Error("grammar constrained sampling requires exactly one required string property"); + } + const inputProperty = schema.required[0]; + if (!schema.properties?.[inputProperty]) { + throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`); + } + if (schema.properties[inputProperty]?.type !== "string") { + throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`); + } + return inputProperty; +} +function resolveJsonSchemaStrictSampling(tool, supportsStrictMode) { + const config = tool.constrainedSampling; + if (!config || config.type !== "json_schema") + return undefined; + if (supportsStrictMode) { + try { + makeStrictJsonSchema(tool.parameters); + return true; + } + catch (error) { + if (!(error instanceof UnsupportedStrictJsonSchemaError)) + throw error; + if (config.strict !== "require") + return undefined; + throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`); + } + } + if (config.strict === "require") { + throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`); + } + return undefined; +} +function resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools) { + const config = tool.constrainedSampling; + if (!config || config.type !== "grammar") { + return undefined; + } + if (!supportsOpenAIGrammarTools) { + return undefined; + } + const larkDefinition = config.variants.openai_lark; + const regexDefinition = config.variants.openai_regex; + const hasLarkDefinition = typeof larkDefinition === "string" && larkDefinition.trim().length > 0; + const hasRegexDefinition = typeof regexDefinition === "string" && regexDefinition.trim().length > 0; + if (!hasLarkDefinition && !hasRegexDefinition) { + throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`); + } + try { + return { + format: hasLarkDefinition ? "lark" : "regex", + definition: hasLarkDefinition ? larkDefinition : regexDefinition, + inputProperty: inferGrammarInputProperty(tool), + }; + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`); + } +} +function createGrammarToolInputProperties(tools, supportsOpenAIGrammarTools) { + const properties = new Map(); + for (const tool of tools ?? []) { + const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools); + if (grammar) { + properties.set(tool.name, grammar.inputProperty); + } + } + return properties; +} +//# sourceMappingURL=constrained-sampling.js.map + +/***/ }), + +/***/ 18296: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + xw: () => (/* binding */ adjustMaxTokensForThinking), + QP: () => (/* binding */ buildBaseOptions), + Yx: () => (/* binding */ clampMaxTokensToContext), + M7: () => (/* binding */ clampReasoning), + z9: () => (/* binding */ clampThinkingBudgetToAnswerRoom), + pT: () => (/* binding */ thinkingBudgetForLevel) +}); + +// UNUSED EXPORTS: DEFAULT_THINKING_BUDGETS, MIN_ANSWER_TOKENS + +// EXTERNAL MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/text.js +var utils_text = __webpack_require__(65678); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js + +const CHARS_PER_TOKEN = 4; +const ESTIMATED_IMAGE_CHARS = 4800; +function calculateContextTokens(usage) { + return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite; +} +function safeJsonStringify(value) { + try { + return JSON.stringify(value) ?? "undefined"; + } + catch { + return "[unserializable]"; + } +} +function estimateTextAndImageContentChars(content) { + if (typeof content === "string") + return content.length; + let chars = 0; + for (const block of content) + chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS; + return chars; +} +function estimateTextTokens(text) { + return Math.ceil(text.length / CHARS_PER_TOKEN); +} +function estimateTextAndImageContentTokens(content) { + return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN); +} +function estimateMessageTokens(message) { + let chars = 0; + if (message.role === "system") { + return (estimateTextTokens((0,utils_text/* getSystemMessageText */.Y8)(message)) + + estimateToolsTokens(message.toolsAdded) + + estimateToolsTokens(message.toolsRemoved)); + } + if (message.role === "user") + return estimateTextAndImageContentTokens(message.content); + if (message.role === "toolResult") + return estimateTextAndImageContentTokens(message.content); + for (const block of message.content) { + if (block.type === "text") { + chars += block.text.length; + } + else if (block.type === "thinking") { + chars += block.thinking.length; + } + else { + chars += block.name.length + safeJsonStringify(block.arguments).length; + } + } + return Math.ceil(chars / CHARS_PER_TOKEN); +} +function getLastAssistantUsageInfo(messages) { + let latestPrefixTimestamp = Number.NEGATIVE_INFINITY; + let usageInfo; + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + if (message.role === "assistant") { + const assistant = message; + // A newer prefix message was inserted after this response (for example, a + // compaction summary), so its usage cannot describe the current prefix. + const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp; + if (usageAppliesToPrefix && + assistant.stopReason !== "aborted" && + assistant.stopReason !== "error" && + calculateContextTokens(assistant.usage) > 0) { + usageInfo = { usage: assistant.usage, index: i }; + } + } + latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp); + } + return usageInfo; +} +function estimateContextTokens(context) { + const messages = "messages" in context ? context.messages : context; + const usageInfo = getLastAssistantUsageInfo(messages); + if (usageInfo) { + const usageTokens = calculateContextTokens(usageInfo.usage); + let trailingTokens = 0; + for (let i = usageInfo.index + 1; i < messages.length; i++) { + trailingTokens += estimateMessageTokens(messages[i]); + } + return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index }; + } + let tokens = 0; + for (const message of messages) + tokens += estimateMessageTokens(message); + return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null }; +} +function estimateToolsTokens(tools) { + if (!tools || tools.length === 0) + return 0; + return estimateTextTokens(safeJsonStringify(tools)); +} +//# sourceMappingURL=estimate.js.map +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@earendil-works+pi-ai@0.86.1_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7__ws@8.22.0_zod@4.6.7/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js + +const CONTEXT_SAFETY_TOKENS = 4096; +const MIN_MAX_TOKENS = 1; +function clampMaxTokensToContext(model, context, maxTokens) { + if (model.contextWindow <= 0) + return Math.max(MIN_MAX_TOKENS, maxTokens); + const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS; + return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available)); +} +function buildBaseOptions(model, context, options, apiKey) { + const samplingParams = model.samplingParams || options?.samplingParams + ? { ...model.samplingParams, ...options?.samplingParams } + : undefined; + return { + temperature: options?.temperature, + samplingParams, + maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens), + signal: options?.signal, + telemetryContext: options?.telemetryContext, + apiKey: apiKey || options?.apiKey, + fetch: options?.fetch, + transport: options?.transport, + cacheRetention: options?.cacheRetention, + sessionId: options?.sessionId, + headers: options?.headers, + onPayload: options?.onPayload, + onResponse: options?.onResponse, + timeoutMs: options?.timeoutMs, + websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs, + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + metadata: options?.metadata, + env: options?.env, + }; +} +/** Tokens always left for the answer when a thinking budget shares the response ceiling. */ +const MIN_ANSWER_TOKENS = 1024; +const DEFAULT_THINKING_BUDGETS = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384, +}; +function clampReasoning(effort) { + return effort === "xhigh" || effort === "max" ? "high" : effort; +} +function thinkingBudgetForLevel(reasoningLevel, customBudgets) { + const budgets = { ...DEFAULT_THINKING_BUDGETS, ...customBudgets }; + const level = clampReasoning(reasoningLevel); + return budgets[level]; +} +/** Cap a thinking budget so at least MIN_ANSWER_TOKENS remain under a shared response ceiling. */ +function clampThinkingBudgetToAnswerRoom(thinkingBudget, ceiling) { + return Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS)); +} +function adjustMaxTokensForThinking( +// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it. +baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) { + let thinkingBudget = thinkingBudgetForLevel(reasoningLevel, customBudgets); + const maxTokens = baseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens); + if (maxTokens <= thinkingBudget) { + thinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens); + } + return { maxTokens, thinkingBudget }; +} +//# sourceMappingURL=simple-options.js.map + +/***/ }), + +/***/ 48809: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ b: () => (/* binding */ transformMessages) +/* harmony export */ }); +const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)"; +const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)"; +function replaceImagesWithPlaceholder(content, placeholder) { + const result = []; + let previousWasPlaceholder = false; + for (const block of content) { + if (block.type === "image") { + if (!previousWasPlaceholder) { + result.push({ type: "text", text: placeholder }); + } + previousWasPlaceholder = true; + continue; + } + result.push(block); + previousWasPlaceholder = block.text === placeholder; + } + return result; +} +function downgradeUnsupportedImages(messages, model) { + if (model.input.includes("image")) { + return messages; + } + return messages.map((msg) => { + if (msg.role === "user" && Array.isArray(msg.content)) { + return { + ...msg, + content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER), + }; + } + if (msg.role === "toolResult") { + return { + ...msg, + content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER), + }; + } + return msg; + }); +} +/** + * Normalize tool call ID for cross-provider compatibility. + * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`. + * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars). + */ +function transformMessages(messages, model, normalizeToolCallId) { + // Build a map of original tool call IDs to normalized IDs + const toolCallIdMap = new Map(); + // Normalize null/undefined content from untyped callers (custom tools, hand-built + // histories, old session files) so downstream code can rely on the type contract. + const normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg)); + const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model); + // First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization) + const transformed = imageAwareMessages.map((msg) => { + // System and user messages pass through unchanged + if (msg.role === "system" || msg.role === "user") { + return msg; + } + // Handle toolResult messages - normalize toolCallId if we have a mapping + if (msg.role === "toolResult") { + const normalizedId = toolCallIdMap.get(msg.toolCallId); + if (normalizedId && normalizedId !== msg.toolCallId) { + return { ...msg, toolCallId: normalizedId }; + } + return msg; + } + // Assistant messages need transformation check + if (msg.role === "assistant") { + const assistantMsg = msg; + const isSameModel = assistantMsg.provider === model.provider && + assistantMsg.api === model.api && + assistantMsg.model === model.id; + const transformedContent = assistantMsg.content.flatMap((block) => { + if (block.type === "thinking") { + // Redacted thinking is opaque encrypted content, only valid for the same model. + // Drop it for cross-model to avoid API errors. + if (block.redacted) { + return isSameModel ? block : []; + } + // For same model: keep thinking blocks with signatures (needed for replay) + // even if the thinking text is empty (OpenAI encrypted reasoning) + if (isSameModel && block.thinkingSignature) + return block; + // Skip empty thinking blocks, convert others to plain text + if (!block.thinking || block.thinking.trim() === "") + return []; + if (isSameModel) + return block; + return { + type: "text", + text: block.thinking, + }; + } + if (block.type === "text") { + if (isSameModel) + return block; + return { + type: "text", + text: block.text, + }; + } + if (block.type === "toolCall") { + const toolCall = block; + let normalizedToolCall = toolCall; + if (!isSameModel && toolCall.thoughtSignature) { + normalizedToolCall = { ...toolCall }; + delete normalizedToolCall.thoughtSignature; + } + if (!isSameModel && normalizeToolCallId) { + const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg); + if (normalizedId !== toolCall.id) { + toolCallIdMap.set(toolCall.id, normalizedId); + normalizedToolCall = { ...normalizedToolCall, id: normalizedId }; + } + } + return normalizedToolCall; + } + return block; + }); + return { + ...assistantMsg, + content: transformedContent, + }; + } + return msg; + }); + // Second pass: insert synthetic empty tool results for orphaned tool calls + // This preserves thinking signatures and satisfies API requirements + const result = []; + let pendingToolCalls = []; + let existingToolResultIds = new Set(); + // System messages are transparent to tool-call accounting: one that lands between a tool + // call and its results is held back and emitted after the results (synthetic ones + // included), so it never causes a duplicate result for a call that is answered later. + const heldSystemMessages = []; + const closePendingToolCalls = () => { + if (pendingToolCalls.length > 0) { + for (const tc of pendingToolCalls) { + if (!existingToolResultIds.has(tc.id)) { + result.push({ + role: "toolResult", + toolCallId: tc.id, + toolName: tc.name, + content: [{ type: "text", text: "No result provided" }], + isError: true, + timestamp: Date.now(), + }); + } + } + pendingToolCalls = []; + existingToolResultIds = new Set(); + } + result.push(...heldSystemMessages); + heldSystemMessages.length = 0; + }; + for (let i = 0; i < transformed.length; i++) { + const msg = transformed[i]; + if (msg.role === "assistant") { + // If we have pending orphaned tool calls from a previous assistant, insert synthetic results now + closePendingToolCalls(); + // Skip errored/aborted assistant messages entirely. + // These are incomplete turns that shouldn't be replayed: + // - May have partial content (reasoning without message, incomplete tool calls) + // - Replaying them can cause API errors (e.g., OpenAI "reasoning without following item") + // - The model should retry from the last valid state + const assistantMsg = msg; + if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") { + continue; + } + // Track tool calls from this assistant message + const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall"); + if (toolCalls.length > 0) { + pendingToolCalls = toolCalls; + existingToolResultIds = new Set(); + } + result.push(msg); + } + else if (msg.role === "toolResult") { + existingToolResultIds.add(msg.toolCallId); + result.push(msg); + } + else if (msg.role === "system") { + if (pendingToolCalls.length > 0) { + heldSystemMessages.push(msg); + } + else { + result.push(msg); + } + } + else if (msg.role === "user") { + // A new user turn interrupts tool flow - insert synthetic results for orphaned calls + closePendingToolCalls(); + result.push(msg); + } + else { + result.push(msg); + } + } + // If the conversation ends with unresolved tool calls, synthesize results now. + closePendingToolCalls(); + return result; +} +//# sourceMappingURL=transform-messages.js.map + +/***/ }), + +/***/ 82003: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ headersToRecord), +/* harmony export */ m: () => (/* binding */ providerHeadersToRecord) +/* harmony export */ }); +function headersToRecord(headers) { + const result = {}; + for (const [key, value] of headers.entries()) { + result[key] = value; + } + return result; +} +function providerHeadersToRecord(headers) { + if (!headers) + return undefined; + const result = {}; + for (const [key, value] of Object.entries(headers)) { + if (value !== null) + result[key] = value; + } + return Object.keys(result).length > 0 ? result : undefined; +} +//# sourceMappingURL=headers.js.map + +/***/ }), + +/***/ 43780: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ J: () => (/* binding */ sanitizeSurrogates) +/* harmony export */ }); +/** + * Removes unpaired Unicode surrogate characters from a string. + * + * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF, + * or vice versa) cause JSON serialization errors in many API providers. + * + * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired + * surrogates and will NOT be affected by this function. + * + * @param text - The text to sanitize + * @returns The sanitized text with unpaired surrogates removed + * + * @example + * // Valid emoji (properly paired surrogates) are preserved + * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World" + * + * // Unpaired high surrogate is removed + * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low + * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here" + */ +function sanitizeSurrogates(text) { + // Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate) + // Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate) + return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 49017: +/***/ (function(module) { + +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.3.1 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2025 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // The index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne + (id === 2 && e > ne); + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if ( true && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); + + +/***/ }), + +/***/ 53775: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*jshint node:true */ + +var Buffer = (__webpack_require__(20181).Buffer); // browserify +var SlowBuffer = (__webpack_require__(20181).SlowBuffer); + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; + + +/***/ }), + +/***/ 58210: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +var Buffer = (__webpack_require__(5725).Buffer); + +var getParamBytesForAlg = __webpack_require__(24335); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; + + +/***/ }), + +/***/ 24335: +/***/ ((module) => { + + + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; + + +/***/ }), + +/***/ 29936: +/***/ ((module) => { + + + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; + + +/***/ }), + +/***/ 7706: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0; +exports.defaultErrorRedactor = defaultErrorRedactor; +const extend_1 = __importDefault(__webpack_require__(29936)); +const util_cjs_1 = __importDefault(__webpack_require__(39122)); +const pkg = util_cjs_1.default.pkg; +/** + * Support `instanceof` operator for `GaxiosError`s in different versions of this library. + * + * @see {@link GaxiosError[Symbol.hasInstance]} + */ +exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`); +class GaxiosError extends Error { + config; + response; + /** + * An error code. + * Can be a system error code, DOMException error name, or any error's 'code' property where it is a `string`. + * + * It is only a `number` when the cause is sourced from an API-level error (AIP-193). + * + * @see {@link https://nodejs.org/api/errors.html#errorcode error.code} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names DOMException#error_names} + * @see {@link https://google.aip.dev/193#http11json-representation AIP-193} + * + * @example + * 'ECONNRESET' + * + * @example + * 'TimeoutError' + * + * @example + * 500 + */ + code; + /** + * An HTTP Status code. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response#status} + * + * @example + * 500 + */ + status; + /** + * @deprecated use {@link GaxiosError.cause} instead. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause Error#cause} + * + * @privateRemarks + * + * We will want to remove this property later as the modern `cause` property is better suited + * for displaying and relaying nested errors. Keeping this here makes the resulting + * error log larger than it needs to be. + * + */ + error; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[Symbol.hasInstance]} + * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} + * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} + */ + [exports.GAXIOS_ERROR_SYMBOL] = pkg.version; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} + */ + static [Symbol.hasInstance](instance) { + if (instance && + typeof instance === 'object' && + exports.GAXIOS_ERROR_SYMBOL in instance && + instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) { + return true; + } + // fallback to native + return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); + } + constructor(message, config, response, cause) { + super(message, { cause }); + this.config = config; + this.response = response; + this.error = cause instanceof Error ? cause : undefined; + // deep-copy config as we do not want to mutate + // the existing config for future retries/use + this.config = (0, extend_1.default)(true, {}, config); + if (this.response) { + this.response.config = (0, extend_1.default)(true, {}, this.response.config); + } + if (this.response) { + try { + this.response.data = translateData(this.config.responseType, + // workaround for `node-fetch`'s `.data` deprecation... + this.response?.bodyUsed ? this.response?.data : undefined); + } + catch { + // best effort - don't throw an error within an error + // we could set `this.response.config.responseType = 'unknown'`, but + // that would mutate future calls with this config object. + } + this.status = this.response.status; + } + if (cause instanceof DOMException) { + // The DOMException's equivalent to code is its name + // E.g.: name = `TimeoutError`, code = number + // https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name + this.code = cause.name; + } + else if (cause && + typeof cause === 'object' && + 'code' in cause && + (typeof cause.code === 'string' || typeof cause.code === 'number')) { + this.code = cause.code; + } + } + /** + * An AIP-193 conforming error extractor. + * + * @see {@link https://google.aip.dev/193#http11json-representation AIP-193} + * + * @internal + * @expiremental + * + * @param res the response object + * @returns the extracted error information + */ + static extractAPIErrorFromResponse(res, defaultErrorMessage = 'The request failed') { + let message = defaultErrorMessage; + // Use res.data as the error message + if (typeof res.data === 'string') { + message = res.data; + } + if (res.data && + typeof res.data === 'object' && + 'error' in res.data && + res.data.error && + !res.ok) { + if (typeof res.data.error === 'string') { + return { + message: res.data.error, + code: res.status, + status: res.statusText, + }; + } + if (typeof res.data.error === 'object') { + // extract status from data.message + message = + 'message' in res.data.error && + typeof res.data.error.message === 'string' + ? res.data.error.message + : message; + // extract status from data.error + const status = 'status' in res.data.error && + typeof res.data.error.status === 'string' + ? res.data.error.status + : res.statusText; + // extract code from data.error + const code = 'code' in res.data.error && typeof res.data.error.code === 'number' + ? res.data.error.code + : res.status; + if ('errors' in res.data.error && + Array.isArray(res.data.error.errors)) { + const errorMessages = []; + for (const e of res.data.error.errors) { + if (typeof e === 'object' && + 'message' in e && + typeof e.message === 'string') { + errorMessages.push(e.message); + } + } + return Object.assign({ + message: errorMessages.join('\n') || message, + code, + status, + }, res.data.error); + } + return Object.assign({ + message, + code, + status, + }, res.data.error); + } + } + return { + message, + code: res.status, + status: res.statusText, + }; + } +} +exports.GaxiosError = GaxiosError; +function translateData(responseType, data) { + switch (responseType) { + case 'stream': + return data; + case 'json': + return JSON.parse(JSON.stringify(data)); + case 'arraybuffer': + return JSON.parse(Buffer.from(data).toString('utf8')); + case 'blob': + return JSON.parse(data.text()); + default: + return data; + } +} +/** + * An experimental error redactor. + * + * @param config Config to potentially redact properties of + * @param response Config to potentially redact properties of + * + * @experimental + */ +function defaultErrorRedactor(data) { + const REDACT = '< - See `errorRedactor` option in `gaxios` for configuration>.'; + function redactHeaders(headers) { + if (!headers) + return; + headers.forEach((_, key) => { + // any casing of `Authentication` + // any casing of `Authorization` + // anything containing secret, such as 'client secret' + if (/^authentication$/i.test(key) || + /^authorization$/i.test(key) || + /secret/i.test(key)) + headers.set(key, REDACT); + }); + } + function redactString(obj, key) { + if (typeof obj === 'object' && + obj !== null && + typeof obj[key] === 'string') { + const text = obj[key]; + if (/grant_type=/i.test(text) || + /assertion=/i.test(text) || + /secret/i.test(text)) { + obj[key] = REDACT; + } + } + } + function redactObject(obj) { + if (!obj || typeof obj !== 'object') { + return; + } + else if (obj instanceof FormData || + obj instanceof URLSearchParams || + // support `node-fetch` FormData/URLSearchParams + ('forEach' in obj && 'set' in obj)) { + obj.forEach((_, key) => { + if (['grant_type', 'assertion'].includes(key) || /secret/.test(key)) { + obj.set(key, REDACT); + } + }); + } + else { + if ('grant_type' in obj) { + obj['grant_type'] = REDACT; + } + if ('assertion' in obj) { + obj['assertion'] = REDACT; + } + if ('client_secret' in obj) { + obj['client_secret'] = REDACT; + } + } + } + if (data.config) { + redactHeaders(data.config.headers); + redactString(data.config, 'data'); + redactObject(data.config.data); + redactString(data.config, 'body'); + redactObject(data.config.body); + if (data.config.url.searchParams.has('token')) { + data.config.url.searchParams.set('token', REDACT); + } + if (data.config.url.searchParams.has('client_secret')) { + data.config.url.searchParams.set('client_secret', REDACT); + } + } + if (data.response) { + defaultErrorRedactor({ config: data.response.config }); + redactHeaders(data.response.headers); + // workaround for `node-fetch`'s `.data` deprecation... + if (data.response.bodyUsed) { + redactString(data.response, 'data'); + redactObject(data.response.data); + } + } + return data; +} +//# sourceMappingURL=common.js.map + +/***/ }), + +/***/ 44450: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Gaxios = void 0; +const extend_1 = __importDefault(__webpack_require__(29936)); +const https_1 = __webpack_require__(65692); +const common_js_1 = __webpack_require__(7706); +const retry_js_1 = __webpack_require__(15053); +const stream_1 = __webpack_require__(2203); +const interceptor_js_1 = __webpack_require__(128); +const randomUUID = async () => globalThis.crypto?.randomUUID() || (await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 76982, 23))).randomUUID(); +const HTTP_STATUS_NO_CONTENT = 204; +class Gaxios { + agentCache = new Map(); + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults; + /** + * Interceptors + */ + interceptors; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + this.defaults = defaults || {}; + this.interceptors = { + request: new interceptor_js_1.GaxiosInterceptorManager(), + response: new interceptor_js_1.GaxiosInterceptorManager(), + }; + } + /** + * A {@link fetch `fetch`} compliant API for {@link Gaxios}. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const gaxios = new Gaxios(); + * const myFetch: typeof fetch = (...args) => gaxios.fetch(...args); + * await myFetch('https://example.com'); + * ``` + * + * @param args `fetch` API or `Gaxios#request` parameters + * @returns the {@link Response} with Gaxios-added properties + */ + fetch(...args) { + // Up to 2 parameters in either overload + const input = args[0]; + const init = args[1]; + let url = undefined; + const headers = new Headers(); + // prepare URL + if (typeof input === 'string') { + url = new URL(input); + } + else if (input instanceof URL) { + url = input; + } + else if (input && input.url) { + url = new URL(input.url); + } + // prepare headers + if (input && typeof input === 'object' && 'headers' in input) { + _a.mergeHeaders(headers, input.headers); + } + if (init) { + _a.mergeHeaders(headers, new Headers(init.headers)); + } + // prepare request + if (typeof input === 'object' && !(input instanceof URL)) { + // input must have been a non-URL object + return this.request({ ...init, ...input, headers, url }); + } + else { + // input must have been a string or URL + return this.request({ ...init, headers, url }); + } + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + let prepared = await this.#prepareRequest(opts); + prepared = await this.#applyRequestInterceptors(prepared); + return this.#applyResponseInterceptors(this._request(prepared)); + } + async _defaultAdapter(config) { + const fetchImpl = config.fetchImplementation || + this.defaults.fetchImplementation || + (await _a.#getFetch()); + // node-fetch v3 warns when `data` is present + // https://github.com/node-fetch/node-fetch/issues/1000 + const preparedOpts = { ...config }; + delete preparedOpts.data; + const res = (await fetchImpl(config.url, preparedOpts)); + const data = await this.getResponseData(config, res); + if (!Object.getOwnPropertyDescriptor(res, 'data')?.configurable) { + // Work-around for `node-fetch` v3 as accessing `data` would otherwise throw + Object.defineProperties(res, { + data: { + configurable: true, + writable: true, + enumerable: true, + value: data, + }, + }); + } + // Keep object as an instance of `Response` + return Object.assign(res, { config, data }); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); + } + else { + translatedResponse = await this._defaultAdapter(opts); + } + if (!opts.validateStatus(translatedResponse.status)) { + if (opts.responseType === 'stream') { + const response = []; + for await (const chunk of translatedResponse.data) { + response.push(chunk); + } + translatedResponse.data = Buffer.concat(response.map(c => (typeof c === 'string' ? Buffer.from(c) : c))).toString('utf8'); + } + const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`); + throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo); + } + return translatedResponse; + } + catch (e) { + let err; + if (e instanceof common_js_1.GaxiosError) { + err = e; + } + else if (e instanceof Error) { + err = new common_js_1.GaxiosError(e.message, opts, undefined, e); + } + else { + err = new common_js_1.GaxiosError('Unexpected Gaxios Error', opts, undefined, e); + } + const { shouldRetry, config } = await (0, retry_js_1.getRetryConfig)(err); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = + config.retryConfig.currentRetryAttempt; + // The error's config could be redacted - therefore we only want to + // copy the retry state over to the existing config + opts.retryConfig = err.config?.retryConfig; + // re-prepare timeout for the next request + this.#appendTimeoutToSignal(opts); + return this._request(opts); + } + if (opts.errorRedactor) { + opts.errorRedactor(err); + } + throw err; + } + } + async getResponseData(opts, res) { + if (res.status === HTTP_STATUS_NO_CONTENT) { + return ''; + } + if (opts.maxContentLength && + res.headers.has('content-length') && + opts.maxContentLength < + Number.parseInt(res.headers?.get('content-length') || '')) { + throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts })); + } + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': { + const data = await res.text(); + try { + return JSON.parse(data); + } + catch { + return data; + } + } + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + case 'text': + return res.text(); + default: + return this.getResponseDataFromContentType(res); + } + } + #urlMayUseProxy(url, noProxy = []) { + const candidate = new URL(url); + const noProxyList = [...noProxy]; + const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(',') || []; + for (const rule of noProxyEnvList) { + noProxyList.push(rule.trim()); + } + for (const rule of noProxyList) { + // Match regex + if (rule instanceof RegExp) { + if (rule.test(candidate.toString())) { + return false; + } + } + // Match URL + else if (rule instanceof URL) { + if (rule.origin === candidate.origin) { + return false; + } + } + // Match string regex + else if (rule.startsWith('*.') || rule.startsWith('.')) { + const cleanedRule = rule.replace(/^\*\./, '.'); + if (candidate.hostname.endsWith(cleanedRule)) { + return false; + } + } + // Basic string match + else if (rule === candidate.origin || + rule === candidate.hostname || + rule === candidate.href) { + return false; + } + } + return true; + } + /** + * Applies the request interceptors. The request interceptors are applied after the + * call to prepareRequest is completed. + * + * @param {GaxiosOptionsPrepared} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ + async #applyRequestInterceptors(options) { + let promiseChain = Promise.resolve(options); + for (const interceptor of this.interceptors.request.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; + } + /** + * Applies the response interceptors. The response interceptors are applied after the + * call to request is made. + * + * @param {GaxiosOptionsPrepared} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ + async #applyResponseInterceptors(response) { + let promiseChain = Promise.resolve(response); + for (const interceptor of this.interceptors.response.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; + } + /** + * Validates the options, merges them with defaults, and prepare request. + * + * @param options The original options passed from the client. + * @returns Prepared options, ready to make a request + */ + async #prepareRequest(options) { + // Prepare Headers - copy in order to not mutate the original objects + const preparedHeaders = new Headers(this.defaults.headers); + _a.mergeHeaders(preparedHeaders, options.headers); + // Merge options + const opts = (0, extend_1.default)(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + if (opts.baseURL) { + opts.url = new URL(opts.url, opts.baseURL); + } + // don't modify the properties of a default or provided URL + opts.url = new URL(opts.url); + if (opts.params) { + if (opts.paramsSerializer) { + let additionalQueryParams = opts.paramsSerializer(opts.params); + if (additionalQueryParams.startsWith('?')) { + additionalQueryParams = additionalQueryParams.slice(1); + } + const prefix = opts.url.toString().includes('?') ? '&' : '?'; + opts.url = opts.url + prefix + additionalQueryParams; + } + else { + const url = opts.url instanceof URL ? opts.url : new URL(opts.url); + for (const [key, value] of new URLSearchParams(opts.params)) { + url.searchParams.append(key, value); + } + opts.url = url; + } + } + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + const shouldDirectlyPassData = typeof opts.data === 'string' || + opts.data instanceof ArrayBuffer || + opts.data instanceof Blob || + // Node 18 does not have a global `File` object + (globalThis.File && opts.data instanceof File) || + opts.data instanceof FormData || + opts.data instanceof stream_1.Readable || + opts.data instanceof ReadableStream || + opts.data instanceof String || + opts.data instanceof URLSearchParams || + ArrayBuffer.isView(opts.data) || // `Buffer` (Node.js), `DataView`, `TypedArray` + /** + * @deprecated `node-fetch` or another third-party's request types + */ + ['Blob', 'File', 'FormData'].includes(opts.data?.constructor?.name || ''); + if (opts.multipart?.length) { + const boundary = await randomUUID(); + preparedHeaders.set('content-type', `multipart/related; boundary=${boundary}`); + opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary)); + } + else if (shouldDirectlyPassData) { + opts.body = opts.data; + } + else if (typeof opts.data === 'object') { + if (preparedHeaders.get('Content-Type') === + 'application/x-www-form-urlencoded') { + // If www-form-urlencoded content type has been set, but data is + // provided as an object, serialize the content + opts.body = opts.paramsSerializer + ? opts.paramsSerializer(opts.data) + : new URLSearchParams(opts.data); + } + else { + if (!preparedHeaders.has('content-type')) { + preparedHeaders.set('content-type', 'application/json'); + } + opts.body = JSON.stringify(opts.data); + } + } + else if (opts.data) { + opts.body = opts.data; + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'unknown'; + if (!preparedHeaders.has('accept') && opts.responseType === 'json') { + preparedHeaders.set('accept', 'application/json'); + } + const proxy = opts.proxy || + process?.env?.HTTPS_PROXY || + process?.env?.https_proxy || + process?.env?.HTTP_PROXY || + process?.env?.http_proxy; + if (opts.agent) { + // don't do any of the following options - use the user-provided agent. + } + else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) { + const HttpsProxyAgent = await _a.#getProxyAgent(); + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy, { + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(proxy, opts.agent); + } + } + else if (opts.cert && opts.key) { + // Configure client for mTLS + if (this.agentCache.has(opts.key)) { + opts.agent = this.agentCache.get(opts.key); + } + else { + opts.agent = new https_1.Agent({ + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(opts.key, opts.agent); + } + } + if (typeof opts.errorRedactor !== 'function' && + opts.errorRedactor !== false) { + opts.errorRedactor = common_js_1.defaultErrorRedactor; + } + if (opts.body && !('duplex' in opts)) { + /** + * required for Node.js and the type isn't available today + * @link https://github.com/nodejs/node/issues/46221 + * @link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483 + */ + opts.duplex = 'half'; + } + this.#appendTimeoutToSignal(opts); + return Object.assign(opts, { + headers: preparedHeaders, + url: opts.url instanceof URL ? opts.url : new URL(opts.url), + }); + } + #appendTimeoutToSignal(opts) { + if (opts.timeout) { + const timeoutSignal = AbortSignal.timeout(opts.timeout); + if (opts.signal && !opts.signal.aborted) { + opts.signal = AbortSignal.any([opts.signal, timeoutSignal]); + } + else { + opts.signal = timeoutSignal; + } + } + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Attempts to parse a response by looking at the Content-Type header. + * @param {Response} response the HTTP response. + * @returns a promise that resolves to the response data. + */ + async getResponseDataFromContentType(response) { + let contentType = response.headers.get('Content-Type'); + if (contentType === null) { + // Maintain existing functionality by calling text() + return response.text(); + } + contentType = contentType.toLowerCase(); + if (contentType.includes('application/json')) { + let data = await response.text(); + try { + data = JSON.parse(data); + } + catch { + // continue + } + return data; + } + else if (contentType.match(/^text\//)) { + return response.text(); + } + else { + // If the content type is something not easily handled, just return the raw data (blob) + return response.blob(); + } + } + /** + * Creates an async generator that yields the pieces of a multipart/related request body. + * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive + * multipart/related requests are not currently supported. + * + * @param {GaxiosMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. + * @param {string} boundary the boundary string to be placed between each part. + */ + async *getMultipartRequest(multipartOptions, boundary) { + const finale = `--${boundary}--`; + for (const currentPart of multipartOptions) { + const partContentType = currentPart.headers.get('Content-Type') || 'application/octet-stream'; + const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`; + yield preamble; + if (typeof currentPart.content === 'string') { + yield currentPart.content; + } + else { + yield* currentPart.content; + } + yield '\r\n'; + } + yield finale; + } + /** + * A cache for the lazily-loaded proxy agent. + * + * Should use {@link Gaxios[#getProxyAgent]} to retrieve. + */ + // using `import` to dynamically import the types here + static #proxyAgent; + /** + * A cache for the lazily-loaded fetch library. + * + * Should use {@link Gaxios[#getFetch]} to retrieve. + */ + // + static #fetch; + /** + * Imports, caches, and returns a proxy agent - if not already imported + * + * @returns A proxy agent + */ + static async #getProxyAgent() { + this.#proxyAgent ||= (await __webpack_require__.e(/* import() */ 599).then(__webpack_require__.t.bind(__webpack_require__, 4599, 23))).HttpsProxyAgent; + return this.#proxyAgent; + } + static async #getFetch() { + const hasWindow = typeof window !== 'undefined' && !!window; + this.#fetch ||= hasWindow + ? window.fetch + : (await __webpack_require__.e(/* import() */ 428).then(__webpack_require__.bind(__webpack_require__, 48428))).default; + return this.#fetch; + } + /** + * Merges headers. + * If the base headers do not exist a new `Headers` object will be returned. + * + * @remarks + * + * Using this utility can be helpful when the headers are not known to exist: + * - if they exist as `Headers`, that instance will be used + * - it improves performance and allows users to use their existing references to their `Headers` + * - if they exist in another form (`HeadersInit`), they will be used to create a new `Headers` object + * - if the base headers do not exist a new `Headers` object will be created + * + * @param base headers to append/overwrite to + * @param append headers to append/overwrite with + * @returns the base headers instance with merged `Headers` + */ + static mergeHeaders(base, ...append) { + base = base instanceof Headers ? base : new Headers(base); + for (const headers of append) { + const add = headers instanceof Headers ? headers : new Headers(headers); + add.forEach((value, key) => { + // set-cookie is the only header that would repeat. + // A bit of background: https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie + key === 'set-cookie' ? base.append(key, value) : base.set(key, value); + }); + } + return base; + } +} +exports.Gaxios = Gaxios; +_a = Gaxios; +//# sourceMappingURL=gaxios.js.map + +/***/ }), + +/***/ 10627: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.instance = exports.Gaxios = exports.GaxiosError = void 0; +exports.request = request; +const gaxios_js_1 = __webpack_require__(44450); +Object.defineProperty(exports, "Gaxios", ({ enumerable: true, get: function () { return gaxios_js_1.Gaxios; } })); +var common_js_1 = __webpack_require__(7706); +Object.defineProperty(exports, "GaxiosError", ({ enumerable: true, get: function () { return common_js_1.GaxiosError; } })); +__exportStar(__webpack_require__(128), exports); +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_js_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 128: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2024 Google LLC +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GaxiosInterceptorManager = void 0; +/** + * Class to manage collections of GaxiosInterceptors for both requests and responses. + */ +class GaxiosInterceptorManager extends Set { +} +exports.GaxiosInterceptorManager = GaxiosInterceptorManager; +//# sourceMappingURL=interceptor.js.map + +/***/ }), + +/***/ 15053: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2018 Google LLC +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRetryConfig = getRetryConfig; +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + config.retryDelayMultiplier = config.retryDelayMultiplier + ? config.retryDelayMultiplier + : 2; + config.timeOfFirstRequest = config.timeOfFirstRequest + ? config.timeOfFirstRequest + : Date.now(); + config.totalTimeout = config.totalTimeout + ? config.totalTimeout + : Number.MAX_SAFE_INTEGER; + config.maxRetryDelay = config.maxRetryDelay + ? config.maxRetryDelay + : Number.MAX_SAFE_INTEGER; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 408 - Retry ("Request Timeout") + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [408, 408], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + const delay = getNextRetryDelay(config); + // We're going to retry! Increment the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = config.retryBackoff + ? config.retryBackoff(err, delay) + : new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + await config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + const config = getConfig(err); + if ((err.config.signal?.aborted && err.code !== 'TimeoutError') || + err.code === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!config.httpMethodsToRetry || + !config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || 'GET')) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +/** + * Gets the delay to wait before the next retry. + * + * @param {RetryConfig} config The current set of retry options + * @returns {number} the amount of ms to wait before the next retry attempt. + */ +function getNextRetryDelay(config) { + // Calculate time to wait with exponential backoff. + // If this is the first retry, look for a configured retryDelay. + const retryDelay = config.currentRetryAttempt + ? 0 + : (config.retryDelay ?? 100); + // Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000) + const calculatedDelay = retryDelay + + ((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / + 2) * + 1000; + const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); + return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); +} +//# sourceMappingURL=retry.js.map + +/***/ }), + +/***/ 82594: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2012 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0; +const events_1 = __webpack_require__(24434); +const gaxios_1 = __webpack_require__(10627); +const util_1 = __webpack_require__(84358); +const google_logging_utils_1 = __webpack_require__(23760); +const shared_cjs_1 = __webpack_require__(69946); +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +exports.DEFAULT_UNIVERSE = 'googleapis.com'; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; +/** + * The base of all Auth Clients. + */ +class AuthClient extends events_1.EventEmitter { + apiKey; + projectId; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quotaProjectId; + /** + * The {@link Gaxios `Gaxios`} instance used for making requests. + */ + transporter; + credentials = {}; + eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; + forceRefreshOnFailure = false; + universeDomain = exports.DEFAULT_UNIVERSE; + /** + * Symbols that can be added to GaxiosOptions to specify the method name that is + * making an RPC call, for logging purposes, as well as a string ID that can be + * used to correlate calls and responses. + */ + static RequestMethodNameSymbol = Symbol('request method name'); + static RequestLogIdSymbol = Symbol('request log id'); + constructor(opts = {}) { + super(); + const options = (0, util_1.originalOrCamelOptions)(opts); + // Shared auth options + this.apiKey = opts.apiKey; + this.projectId = options.get('project_id') ?? null; + this.quotaProjectId = options.get('quota_project_id'); + this.credentials = options.get('credentials') ?? {}; + this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE; + // Shared client options + this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions); + if (options.get('useAuthRequestParameters') !== false) { + this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR); + this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR); + } + if (opts.eagerRefreshThresholdMillis) { + this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false; + } + /** + * A {@link fetch `fetch`} compliant API for {@link AuthClient}. + * + * @see {@link AuthClient.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const authClient = new AuthClient(); + * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args); + * await fetchWithAuthClient('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + fetch(...args) { + // Up to 2 parameters in either overload + const input = args[0]; + const init = args[1]; + let url = undefined; + const headers = new Headers(); + // prepare URL + if (typeof input === 'string') { + url = new URL(input); + } + else if (input instanceof URL) { + url = input; + } + else if (input && input.url) { + url = new URL(input.url); + } + // prepare headers + if (input && typeof input === 'object' && 'headers' in input) { + gaxios_1.Gaxios.mergeHeaders(headers, input.headers); + } + if (init) { + gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers)); + } + // prepare request + if (typeof input === 'object' && !(input instanceof URL)) { + // input must have been a non-URL object + return this.request({ ...init, ...input, headers, url }); + } + else { + // input must have been a string or URL + return this.request({ ...init, headers, url }); + } + } + /** + * Sets the auth credentials. + */ + setCredentials(credentials) { + this.credentials = credentials; + } + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers object to append additional headers to. + */ + addSharedMetadataHeaders(headers) { + // quota_project_id, stored in application_default_credentials.json, is set in + // the x-goog-user-project header, to indicate an alternate account for + // billing and quota: + if (!headers.has('x-goog-user-project') && // don't override a value the user sets. + this.quotaProjectId) { + headers.set('x-goog-user-project', this.quotaProjectId); + } + return headers; + } + /** + * Adds the `x-goog-user-project` and `authorization` headers to the target Headers + * object, if they exist on the source. + * + * @param target the headers to target + * @param source the headers to source from + * @returns the target headers + */ + addUserProjectAndAuthHeaders(target, source) { + const xGoogUserProject = source.get('x-goog-user-project'); + const authorizationHeader = source.get('authorization'); + if (xGoogUserProject) { + target.set('x-goog-user-project', xGoogUserProject); + } + if (authorizationHeader) { + target.set('authorization', authorizationHeader); + } + return target; + } + static log = (0, google_logging_utils_1.log)('auth'); + static DEFAULT_REQUEST_INTERCEPTOR = { + resolved: async (config) => { + // Set `x-goog-api-client`, if not already set + if (!config.headers.has('x-goog-api-client')) { + const nodeVersion = process.version.replace(/^v/, ''); + config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`); + } + // Set `User-Agent` + const userAgent = config.headers.get('User-Agent'); + if (!userAgent) { + config.headers.set('User-Agent', shared_cjs_1.USER_AGENT); + } + else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) { + config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`); + } + try { + const symbols = config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + // This doesn't need to be very unique or interesting, it's just an aid for + // matching requests to responses. + const logId = `${Math.floor(Math.random() * 1000)}`; + symbols[AuthClient.RequestLogIdSymbol] = logId; + // Boil down the object we're printing out. + const logObject = { + url: config.url, + headers: config.headers, + }; + if (methodName) { + AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject); + } + else { + AuthClient.log.info('[%s] request %j', logId, logObject); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + return config; + }, + }; + static DEFAULT_RESPONSE_INTERCEPTOR = { + resolved: async (response) => { + try { + const symbols = response.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data); + } + else { + AuthClient.log.info('[%s] response %j', logId, response.data); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + return response; + }, + rejected: async (error) => { + try { + const symbols = error.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data); + } + else { + AuthClient.log.error('[%s] error %j', logId, error.response?.data); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + // Re-throw the error. + throw error; + }, + }; + /** + * Sets the method name that is making a Gaxios request, so that logging may tag + * log lines with the operation. + * @param config A Gaxios request config + * @param methodName The method name making the call + */ + static setMethodName(config, methodName) { + try { + const symbols = config; + symbols[AuthClient.RequestMethodNameSymbol] = methodName; + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.AuthClient = AuthClient; +//# sourceMappingURL=authclient.js.map + +/***/ }), + +/***/ 25845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AwsClient = void 0; +const awsrequestsigner_1 = __webpack_require__(84199); +const baseexternalclient_1 = __webpack_require__(89046); +const defaultawssecuritycredentialssupplier_1 = __webpack_require__(81757); +const util_1 = __webpack_require__(84358); +const gaxios_1 = __webpack_require__(10627); +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { + environmentId; + awsSecurityCredentialsSupplier; + regionalCredVerificationUrl; + awsRequestSigner; + region; + static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15'; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; + /** + * Instantiates an AwsClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid AWS credential. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + */ + constructor(options) { + super(options); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !awsSecurityCredentialsSupplier) { + throw new Error('A credential source or AWS security credentials supplier must be specified.'); + } + if (credentialSource && awsSecurityCredentialsSupplier) { + throw new Error('Only one of credential source or AWS security credentials supplier can be specified.'); + } + if (awsSecurityCredentialsSupplier) { + this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; + this.regionalCredVerificationUrl = + AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + this.environmentId = credentialSourceOpts.get('environment_id'); + // This is only required if the AWS region is not available in the + // AWS_REGION or AWS_DEFAULT_REGION environment variables. + const regionUrl = credentialSourceOpts.get('region_url'); + // This is only required if AWS security credentials are not available in + // environment variables. + const securityCredentialsUrl = credentialSourceOpts.get('url'); + const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url'); + this.awsSecurityCredentialsSupplier = + new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ + regionUrl: regionUrl, + securityCredentialsUrl: securityCredentialsUrl, + imdsV2SessionTokenUrl: imdsV2SessionTokenUrl, + }); + this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url'); + this.credentialSourceType = 'aws'; + // Data validators. + this.validateEnvironmentId(); + } + this.awsRequestSigner = null; + this.region = ''; + } + validateEnvironmentId() { + const match = this.environmentId?.match(/^(aws)(\d+)$/); + if (!match || !this.regionalCredVerificationUrl) { + throw new Error('No valid AWS "credential_source" provided'); + } + else if (parseInt(match[2], 10) !== 1) { + throw new Error(`aws version "${match[2]}" is not supported in the current build.`); + } + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. This will call the + * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS + * Security Credentials, then use them to create a signed AWS STS request that + * can be exchanged for a GCP access token. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Initialize AWS request signer if not already initialized. + if (!this.awsRequestSigner) { + this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); + this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { + return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); + }, this.region); + } + // Generate signed request to AWS STS GetCallerIdentity API. + // Use the required regional endpoint. Otherwise, the request will fail. + const options = await this.awsRequestSigner.getRequestOptions({ + ...AwsClient.RETRY_CONFIG, + url: this.regionalCredVerificationUrl.replace('{region}', this.region), + method: 'POST', + }); + // The GCP STS endpoint expects the headers to be formatted as: + // [ + // {key: 'x-amz-date', value: '...'}, + // {key: 'authorization', value: '...'}, + // ... + // ] + // And then serialized as: + // encodeURIComponent(JSON.stringify({ + // url: '...', + // method: 'POST', + // headers: [{key: 'x-amz-date', value: '...'}, ...] + // })) + const reformattedHeader = []; + const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({ + // The full, canonical resource name of the workload identity pool + // provider, with or without the HTTPS prefix. + // Including this header as part of the signature is recommended to + // ensure data integrity. + 'x-goog-cloud-target-resource': this.audience, + }, options.headers); + // Reformat header to GCP STS expected format. + extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value })); + // Serialize the reformatted signed request. + return encodeURIComponent(JSON.stringify({ + url: options.url, + method: options.method, + headers: reformattedHeader, + })); + } +} +exports.AwsClient = AwsClient; +//# sourceMappingURL=awsclient.js.map + +/***/ }), + +/***/ 84199: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AwsRequestSigner = void 0; +const gaxios_1 = __webpack_require__(10627); +const crypto_1 = __webpack_require__(6123); +/** AWS Signature Version 4 signing algorithm identifier. */ +const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; +/** + * The termination string for the AWS credential scope value as defined in + * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + */ +const AWS_REQUEST_TYPE = 'aws4_request'; +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +class AwsRequestSigner { + getCredentials; + region; + crypto; + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials, region) { + this.getCredentials = getCredentials; + this.region = region; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + async getRequestOptions(amzOptions) { + if (!amzOptions.url) { + throw new RangeError('"url" is required in "amzOptions"'); + } + // Stringify JSON requests. This will be set in the request body of the + // generated signed request. + const requestPayloadData = typeof amzOptions.data === 'object' + ? JSON.stringify(amzOptions.data) + : amzOptions.data; + const url = amzOptions.url; + const method = amzOptions.method || 'GET'; + const requestPayload = amzOptions.body || requestPayloadData; + const additionalAmzHeaders = amzOptions.headers; + const awsSecurityCredentials = await this.getCredentials(); + const uri = new URL(url); + if (typeof requestPayload !== 'string' && requestPayload !== undefined) { + throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`); + } + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.slice(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders, + }); + // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. + const headers = gaxios_1.Gaxios.mergeHeaders( + // Add x-amz-date if available. + headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { + authorization: headerMap.authorizationHeader, + host: uri.host, + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + gaxios_1.Gaxios.mergeHeaders(headers, { + 'x-amz-security-token': awsSecurityCredentials.token, + }); + } + const awsSignedReq = { + url, + method: method, + headers, + }; + if (requestPayload !== undefined) { + awsSignedReq.body = requestPayload; + } + return awsSignedReq; + } +} +exports.AwsRequestSigner = AwsRequestSigner; +/** + * Creates the HMAC-SHA256 hash of the provided message using the + * provided key. + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The HMAC-SHA256 key to use. + * @param msg The message to hash. + * @return The computed hash bytes. + */ +async function sign(crypto, key, msg) { + return await crypto.signWithHmacSha256(key, msg); +} +/** + * Calculates the signing key used to calculate the signature for + * AWS Signature Version 4 based on: + * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The AWS secret access key. + * @param dateStamp The '%Y%m%d' date format. + * @param region The AWS region. + * @param serviceName The AWS service name, eg. sts. + * @return The signing key bytes. + */ +async function getSigningKey(crypto, key, dateStamp, region, serviceName) { + const kDate = await sign(crypto, `AWS4${key}`, dateStamp); + const kRegion = await sign(crypto, kDate, region); + const kService = await sign(crypto, kRegion, serviceName); + const kSigning = await sign(crypto, kService, 'aws4_request'); + return kSigning; +} +/** + * Generates the authentication header map needed for generating the AWS + * Signature Version 4 signed request. + * + * @param option The options needed to compute the authentication header map. + * @return The AWS authentication header map which constitutes of the following + * components: amz-date, authorization header and canonical query string. + */ +async function generateAuthenticationHeaderMap(options) { + const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders); + const requestPayload = options.requestPayload || ''; + // iam.amazonaws.com host => iam service. + // sts.us-east-2.amazonaws.com => sts service. + const serviceName = options.host.split('.')[0]; + const now = new Date(); + // Format: '%Y%m%dT%H%M%SZ'. + const amzDate = now + .toISOString() + .replace(/[-:]/g, '') + .replace(/\.[0-9]+/, ''); + // Format: '%Y%m%d'. + const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); + // Add AWS token if available. + if (options.securityCredentials.token) { + additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token); + } + // Header keys need to be sorted alphabetically. + const amzHeaders = gaxios_1.Gaxios.mergeHeaders({ + host: options.host, + }, + // Previously the date was not fixed with x-amz- and could be provided manually. + // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req + additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders); + let canonicalHeaders = ''; + // TypeScript is missing `Headers#keys` at the time of writing + const signedHeadersList = [ + ...amzHeaders.keys(), + ].sort(); + signedHeadersList.forEach(key => { + canonicalHeaders += `${key}:${amzHeaders.get(key)}\n`; + }); + const signedHeaders = signedHeadersList.join(';'); + const payloadHash = await options.crypto.sha256DigestHex(requestPayload); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + const canonicalRequest = `${options.method.toUpperCase()}\n` + + `${options.canonicalUri}\n` + + `${options.canonicalQuerystring}\n` + + `${canonicalHeaders}\n` + + `${signedHeaders}\n` + + `${payloadHash}`; + const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + const stringToSign = `${AWS_ALGORITHM}\n` + + `${amzDate}\n` + + `${credentialScope}\n` + + (await options.crypto.sha256DigestHex(canonicalRequest)); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); + const signature = await sign(options.crypto, signingKey, stringToSign); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html + const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; + return { + // Do not return x-amz-date if date is available. + amzDate: additionalAmzHeaders.has('date') ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring, + }; +} +//# sourceMappingURL=awsrequestsigner.js.map + +/***/ }), + +/***/ 89046: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; +const gaxios_1 = __webpack_require__(10627); +const stream = __webpack_require__(2203); +const authclient_1 = __webpack_require__(82594); +const sts = __webpack_require__(51537); +const util_1 = __webpack_require__(84358); +const shared_cjs_1 = __webpack_require__(69946); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** The default OAuth scope to request when none is provided. */ +const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +/** Default impersonated token lifespan in seconds.*/ +const DEFAULT_TOKEN_LIFESPAN = 3600; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * The credentials JSON file type for external account clients. + * There are 3 types of JSON configs: + * 1. authorized_user => Google end user credential + * 2. service_account => Google service account credential + * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) + */ +exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; +/** The workforce audience pattern. */ +const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token'; +/** + * Base external account client. This is used to instantiate AuthClients for + * exchanging external account credentials for GCP access token and authorizing + * requests to GCP APIs. + * The base class implements common logic for exchanging various type of + * external credentials for GCP access token. The logic of determining and + * retrieving the external credential based on the environment and + * credential_source will be left for the subclasses. + */ +class BaseExternalAccountClient extends authclient_1.AuthClient { + /** + * OAuth scopes for the GCP access token to use. When not provided, + * the default https://www.googleapis.com/auth/cloud-platform is + * used. + */ + scopes; + projectNumber; + audience; + subjectTokenType; + stsCredential; + clientAuth; + credentialSourceType; + cachedAccessToken; + serviceAccountImpersonationUrl; + serviceAccountImpersonationLifetime; + workforcePoolUserProject; + configLifetimeRequested; + tokenUrl; + /** + * @example + * ```ts + * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/'); + * ``` + */ + cloudResourceManagerURL; + supplierContext; + /** + * A pending access token request. Used for concurrent calls. + */ + #pendingAccessToken = null; + /** + * Instantiate a BaseExternalAccountClient instance using the provided JSON + * object loaded from an external account credentials file. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + */ + constructor(options) { + super(options); + const opts = (0, util_1.originalOrCamelOptions)(options); + const type = opts.get('type'); + if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { + throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + + `received "${options.type}"`); + } + const clientId = opts.get('client_id'); + const clientSecret = opts.get('client_secret'); + this.tokenUrl = + opts.get('token_url') ?? + DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain); + const subjectTokenType = opts.get('subject_token_type'); + const workforcePoolUserProject = opts.get('workforce_pool_user_project'); + const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url'); + const serviceAccountImpersonation = opts.get('service_account_impersonation'); + const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds'); + this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') || + `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); + if (clientId) { + this.clientAuth = { + confidentialClientType: 'basic', + clientId, + clientSecret, + }; + } + this.stsCredential = new sts.StsCredentials({ + tokenExchangeEndpoint: this.tokenUrl, + clientAuthentication: this.clientAuth, + }); + this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE]; + this.cachedAccessToken = null; + this.audience = opts.get('audience'); + this.subjectTokenType = subjectTokenType; + this.workforcePoolUserProject = workforcePoolUserProject; + const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); + if (this.workforcePoolUserProject && + !this.audience.match(workforceAudiencePattern)) { + throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + + 'credentials.'); + } + this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; + this.serviceAccountImpersonationLifetime = + serviceAccountImpersonationLifetime; + if (this.serviceAccountImpersonationLifetime) { + this.configLifetimeRequested = true; + } + else { + this.configLifetimeRequested = false; + this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; + } + this.projectNumber = this.getProjectNumber(this.audience); + this.supplierContext = { + audience: this.audience, + subjectTokenType: this.subjectTokenType, + transporter: this.transporter, + }; + } + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail() { + if (this.serviceAccountImpersonationUrl) { + if (this.serviceAccountImpersonationUrl.length > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84} + **/ + throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); + } + // Parse email from URL. The formal looks as follows: + // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken + const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; + const result = re.exec(this.serviceAccountImpersonationUrl); + return result?.groups?.email || null; + } + return null; + } + /** + * Provides a mechanism to inject GCP access tokens directly. + * When the provided credential expires, a new credential, using the + * external account options, is retrieved. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + super.setCredentials(credentials); + this.cachedAccessToken = credentials; + } + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = new Headers({ + authorization: `Bearer ${accessTokenResponse.token}`, + }); + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * @return A promise that resolves with the project ID corresponding to the + * current workload identity pool or current workforce pool if + * determinable. For workforce pool credential, it returns the project ID + * corresponding to the workforcePoolUserProject. + * This is introduced to match the current pattern of using the Auth + * library: + * const projectId = await auth.getProjectId(); + * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + * const res = await client.request({ url }); + * The resource may not have permission + * (resourcemanager.projects.get) to call this API or the required + * scopes may not be selected: + * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes + */ + async getProjectId() { + const projectNumber = this.projectNumber || this.workforcePoolUserProject; + if (this.projectId) { + // Return previously determined project ID. + return this.projectId; + } + else if (projectNumber) { + // Preferable not to use request() to avoid retrial policies. + const headers = await this.getRequestHeaders(); + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + headers, + url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, 'getProjectId'); + const response = await this.transporter.request(opts); + this.projectId = response.data.projectId; + return this.projectId; + } + return null; + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * External credentials are exchanged for GCP access tokens via the token + * exchange endpoint and other settings provided in the client options + * object. + * If the service_account_impersonation_url is provided, an additional + * step to exchange the external account GCP access token for a service + * account impersonated token is performed. + * @return A promise that resolves with the fresh GCP access tokens. + */ + async refreshAccessTokenAsync() { + // Use an existing access token request, or cache a new one + this.#pendingAccessToken = + this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync(); + try { + return await this.#pendingAccessToken; + } + finally { + // clear pending access token for future requests + this.#pendingAccessToken = null; + } + } + async #internalRefreshAccessTokenAsync() { + // Retrieve the external credential. + const subjectToken = await this.retrieveSubjectToken(); + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + audience: this.audience, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken, + subjectTokenType: this.subjectTokenType, + // generateAccessToken requires the provided access token to have + // scopes: + // https://www.googleapis.com/auth/iam or + // https://www.googleapis.com/auth/cloud-platform + // The new service account access token scopes will match the user + // provided ones. + scope: this.serviceAccountImpersonationUrl + ? [DEFAULT_OAUTH_SCOPE] + : this.getScopesArray(), + }; + // Exchange the external credentials for a GCP access token. + // Client auth is prioritized over passing the workforcePoolUserProject + // parameter for STS token exchange. + const additionalOptions = !this.clientAuth && this.workforcePoolUserProject + ? { userProject: this.workforcePoolUserProject } + : undefined; + const additionalHeaders = new Headers({ + 'x-goog-api-client': this.getMetricsHeaderValue(), + }); + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); + if (this.serviceAccountImpersonationUrl) { + this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); + } + else if (stsResponse.expires_in) { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, + res: stsResponse.res, + }; + } + else { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + res: stsResponse.res, + }; + } + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedAccessToken.expiry_date, + access_token: this.cachedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedAccessToken; + } + /** + * Returns the workload identity pool project number if it is determinable + * from the audience resource name. + * @param audience The STS audience used to determine the project number. + * @return The project number associated with the workload identity pool, if + * this can be determined from the STS audience field. Otherwise, null is + * returned. + */ + getProjectNumber(audience) { + // STS audience pattern: + // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... + const match = audience.match(/\/projects\/([^/]+)/); + if (!match) { + return null; + } + return match[1]; + } + /** + * Exchanges an external account GCP access token for a service + * account impersonated access token using iamcredentials + * GenerateAccessToken API. + * @param token The access token to exchange for a service account access + * token. + * @return A promise that resolves with the service account impersonated + * credentials response. + */ + async getImpersonatedAccessToken(token) { + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + url: this.serviceAccountImpersonationUrl, + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${token}`, + }, + data: { + scope: this.getScopesArray(), + lifetime: this.serviceAccountImpersonationLifetime + 's', + }, + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken'); + const response = await this.transporter.request(opts); + const successResponse = response.data; + return { + access_token: successResponse.accessToken, + // Convert from ISO format to timestamp. + expiry_date: new Date(successResponse.expireTime).getTime(), + res: response, + }; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param accessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(accessToken) { + const now = new Date().getTime(); + return accessToken.expiry_date + ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } + /** + * @return The list of scopes for the requested GCP access token. + */ + getScopesArray() { + // Since scopes can be provided as string or array, the type should + // be normalized. + if (typeof this.scopes === 'string') { + return [this.scopes]; + } + return this.scopes || [DEFAULT_OAUTH_SCOPE]; + } + getMetricsHeaderValue() { + const nodeVersion = process.version.replace(/^v/, ''); + const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; + const credentialSourceType = this.credentialSourceType + ? this.credentialSourceType + : 'unknown'; + return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; + } + getTokenUrl() { + return this.tokenUrl; + } +} +exports.BaseExternalAccountClient = BaseExternalAccountClient; +//# sourceMappingURL=baseexternalclient.js.map + +/***/ }), + +/***/ 34505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0; +const util_1 = __webpack_require__(84358); +const fs = __webpack_require__(79896); +const crypto_1 = __webpack_require__(76982); +const https = __webpack_require__(65692); +exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG'; +/** + * Thrown when the certificate source cannot be located or accessed. + */ +class CertificateSourceUnavailableError extends Error { + constructor(message) { + super(message); + this.name = 'CertificateSourceUnavailableError'; + } +} +exports.CertificateSourceUnavailableError = CertificateSourceUnavailableError; +/** + * Thrown for invalid configuration that is not related to file availability. + */ +class InvalidConfigurationError extends Error { + constructor(message) { + super(message); + this.name = 'InvalidConfigurationError'; + } +} +exports.InvalidConfigurationError = InvalidConfigurationError; +/** + * A subject token supplier that uses a client certificate for authentication. + * It provides the certificate chain as the subject token for identity federation. + */ +class CertificateSubjectTokenSupplier { + certificateConfigPath; + trustChainPath; + cert; + key; + /** + * Initializes a new instance of the CertificateSubjectTokenSupplier. + * @param opts The configuration options for the supplier. + */ + constructor(opts) { + if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) { + throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.'); + } + if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) { + throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.'); + } + this.trustChainPath = opts.trustChainPath; + this.certificateConfigPath = opts.certificateConfigLocation ?? ''; + } + /** + * Creates an HTTPS agent configured with the client certificate and private key for mTLS. + * @returns An mTLS-configured https.Agent. + */ + async createMtlsHttpsAgent() { + if (!this.key || !this.cert) { + throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key'); + } + return new https.Agent({ key: this.key, cert: this.cert }); + } + /** + * Constructs the subject token, which is the base64-encoded certificate chain. + * @returns A promise that resolves with the subject token. + */ + async getSubjectToken() { + // The "subject token" in this context is the processed certificate chain. + this.certificateConfigPath = await this.#resolveCertificateConfigFilePath(); + const { certPath, keyPath } = await this.#getCertAndKeyPaths(); + ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath)); + return await this.#processChainFromPaths(this.cert); + } + /** + * Resolves the absolute path to the certificate configuration file + * by checking the "certificate_config_location" provided in the ADC file, + * or the "GOOGLE_API_CERTIFICATE_CONFIG" environment variable + * or in the default gcloud path. + * @param overridePath An optional path to check first. + * @returns The resolved file path. + */ + async #resolveCertificateConfigFilePath() { + // 1. Check for the override path from constructor options. + const overridePath = this.certificateConfigPath; + if (overridePath) { + if (await (0, util_1.isValidFile)(overridePath)) { + return overridePath; + } + throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`); + } + // 2. Check the standard environment variable. + const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE]; + if (envPath) { + if (await (0, util_1.isValidFile)(envPath)) { + return envPath; + } + throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`); + } + // 3. Check the well-known gcloud config location. + const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)(); + if (await (0, util_1.isValidFile)(wellKnownPath)) { + return wellKnownPath; + } + // 4. If none are found, throw an error. + throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' + + `the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`); + } + /** + * Reads and parses the certificate config JSON file to extract the certificate and key paths. + * @returns An object containing the certificate and key paths. + */ + async #getCertAndKeyPaths() { + const configPath = this.certificateConfigPath; + let fileContents; + try { + fileContents = await fs.promises.readFile(configPath, 'utf8'); + } + catch (err) { + throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`); + } + try { + const config = JSON.parse(fileContents); + const certPath = config?.cert_configs?.workload?.cert_path; + const keyPath = config?.cert_configs?.workload?.key_path; + if (!certPath || !keyPath) { + throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`); + } + return { certPath, keyPath }; + } + catch (e) { + if (e instanceof InvalidConfigurationError) + throw e; + throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`); + } + } + /** + * Reads and parses the cert and key files get their content and check valid format. + * @returns An object containing the cert content and key content in buffer format. + */ + async #getKeyAndCert(certPath, keyPath) { + let cert, key; + try { + cert = await fs.promises.readFile(certPath); + new crypto_1.X509Certificate(cert); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`); + } + try { + key = await fs.promises.readFile(keyPath); + (0, crypto_1.createPrivateKey)(key); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`); + } + return { cert, key }; + } + /** + * Reads the leaf certificate and trust chain, combines them, + * and returns a JSON array of base64-encoded certificates. + * @returns A stringified JSON array of the certificate chain. + */ + async #processChainFromPaths(leafCertBuffer) { + const leafCert = new crypto_1.X509Certificate(leafCertBuffer); + // If no trust chain is provided, just use the successfully parsed leaf certificate. + if (!this.trustChainPath) { + return JSON.stringify([leafCert.raw.toString('base64')]); + } + // Handle the trust chain logic. + try { + const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8'); + const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? []; + const chainCerts = pemBlocks.map((pem, index) => { + try { + return new crypto_1.X509Certificate(pem); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + // Throw a more precise error if a single certificate in the chain is invalid. + throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`); + } + }); + const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw)); + let finalChain; + if (leafIndex === -1) { + // Leaf not found, so prepend it to the chain. + finalChain = [leafCert, ...chainCerts]; + } + else if (leafIndex === 0) { + // Leaf is already the first element, so the chain is correctly ordered. + finalChain = chainCerts; + } + else { + // Leaf is in the chain but not at the top, which is invalid. + throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`); + } + return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64'))); + } + catch (err) { + // Re-throw our specific configuration errors. + if (err instanceof InvalidConfigurationError) + throw err; + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`); + } + } +} +exports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier; +//# sourceMappingURL=certificatesubjecttokensupplier.js.map + +/***/ }), + +/***/ 81945: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2013 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Compute = void 0; +const gaxios_1 = __webpack_require__(10627); +const gcpMetadata = __webpack_require__(4381); +const oauth2client_1 = __webpack_require__(64739); +class Compute extends oauth2client_1.OAuth2Client { + serviceAccountEmail; + scopes; + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; + this.serviceAccountEmail = options.serviceAccountEmail || 'default'; + this.scopes = Array.isArray(options.scopes) + ? options.scopes + : options.scopes + ? [options.scopes] + : []; + } + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + async refreshTokenNoCache() { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath, + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(','), + }; + } + data = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError) { + e.message = `Could not refresh access token: ${e.message}`; + this.wrapError(e); + } + throw e; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res: null }; + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath, + }; + idToken = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof Error) { + e.message = `Could not fetch ID token: ${e.message}`; + } + throw e; + } + return idToken; + } + wrapError(e) { + const res = e.response; + if (res && res.status) { + e.status = res.status; + if (res.status === 403) { + e.message = + 'A Forbidden error was returned while attempting to retrieve an access ' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have the correct permission scopes specified: ' + + e.message; + } + else if (res.status === 404) { + e.message = + 'A Not Found error was returned while attempting to retrieve an access' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have any permission scopes specified: ' + + e.message; + } + } + } +} +exports.Compute = Compute; +//# sourceMappingURL=computeclient.js.map + +/***/ }), + +/***/ 81757: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2024 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DefaultAwsSecurityCredentialsSupplier = void 0; +const authclient_1 = __webpack_require__(82594); +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +class DefaultAwsSecurityCredentialsSupplier { + regionUrl; + securityCredentialsUrl; + imdsV2SessionTokenUrl; + additionalGaxiosOptions; + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts) { + this.regionUrl = opts.regionUrl; + this.securityCredentialsUrl = opts.securityCredentialsUrl; + this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + async getAwsRegion(context) { + // Priority order for region determination: + // AWS_REGION > AWS_DEFAULT_REGION > metadata server. + if (this.#regionFromEnv) { + return this.#regionFromEnv; + } + const metadataHeaders = new Headers(); + if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) { + metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter)); + } + if (!this.regionUrl) { + throw new RangeError('Unable to determine AWS region due to missing ' + + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: 'GET', + responseType: 'text', + headers: metadataHeaders, + }; + authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion'); + const response = await context.transporter.request(opts); + // Remove last character. For example, if us-east-2b is returned, + // the region would be us-east-2. + return response.data.substr(0, response.data.length - 1); + } + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + async getAwsSecurityCredentials(context) { + // Check environment variables for permanent credentials first. + // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html + if (this.#securityCredentialsFromEnv) { + return this.#securityCredentialsFromEnv; + } + const metadataHeaders = new Headers(); + if (this.imdsV2SessionTokenUrl) { + metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter)); + } + // Since the role on a VM can change, we don't need to cache it. + const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter); + // Temporary credentials typically last for several hours. + // Expiration is returned in response. + // Consider future optimization of this logic to cache AWS tokens + // until their natural expiration. + const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token, + }; + } + /** + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the IMDSv2 Session Token. + */ + async #getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: 'PUT', + responseType: 'text', + headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, + }; + authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken'); + const response = await transporter.request(opts); + return response.data; + } + /** + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the assigned role to the current + * AWS VM. This is needed for calling the security-credentials endpoint. + */ + async #getAwsRoleName(headers, transporter) { + if (!this.securityCredentialsUrl) { + throw new Error('Unable to determine AWS role name due to missing ' + + '"options.credential_source.url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.securityCredentialsUrl, + method: 'GET', + responseType: 'text', + headers: headers, + }; + authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName'); + const response = await transporter.request(opts); + return response.data; + } + /** + * Retrieves the temporary AWS credentials by calling the security-credentials + * endpoint as specified in the `credential_source` object. + * @param roleName The role attached to the current VM. + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the temporary AWS credentials + * needed for creating the GetCallerIdentity signed request. + */ + async #retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + headers: headers, + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials'); + const response = await transporter.request(opts); + return response.data; + } + get #regionFromEnv() { + // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. + // Only one is required. + return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); + } + get #securityCredentialsFromEnv() { + // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. + if (process.env['AWS_ACCESS_KEY_ID'] && + process.env['AWS_SECRET_ACCESS_KEY']) { + return { + accessKeyId: process.env['AWS_ACCESS_KEY_ID'], + secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], + token: process.env['AWS_SESSION_TOKEN'], + }; + } + return null; + } +} +exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; +//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map + +/***/ }), + +/***/ 44412: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; +const gaxios_1 = __webpack_require__(10627); +const stream = __webpack_require__(2203); +const authclient_1 = __webpack_require__(82594); +const sts = __webpack_require__(51537); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The requested token exchange subject_token_type: rfc8693#section-2.1 + */ +const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * Defines a set of Google credentials that are downscoped from an existing set + * of Google OAuth2 credentials. This is useful to restrict the Identity and + * Access Management (IAM) permissions that a short-lived credential can use. + * The common pattern of usage is to have a token broker with elevated access + * generate these downscoped credentials from higher access source credentials + * and pass the downscoped short-lived access tokens to a token consumer via + * some secure authenticated channel for limited access to Google Cloud Storage + * resources. + */ +class DownscopedClient extends authclient_1.AuthClient { + authClient; + credentialAccessBoundary; + cachedDownscopedAccessToken; + stsCredential; + /** + * Instantiates a downscoped client object using the provided source + * AuthClient and credential access boundary rules. + * To downscope permissions of a source AuthClient, a Credential Access + * Boundary that specifies which resources the new credential can access, as + * well as an upper bound on the permissions that are available on each + * resource, has to be defined. A downscoped client can then be instantiated + * using the source AuthClient and the Credential Access Boundary. + * @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**. + * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead. + */ + constructor( + /** + * AuthClient is for backwards-compatibility. + */ + options, + /** + * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead + */ + credentialAccessBoundary = { + accessBoundary: { + accessBoundaryRules: [], + }, + }) { + super(options instanceof authclient_1.AuthClient ? {} : options); + if (options instanceof authclient_1.AuthClient) { + this.authClient = options; + this.credentialAccessBoundary = credentialAccessBoundary; + } + else { + this.authClient = options.authClient; + this.credentialAccessBoundary = options.credentialAccessBoundary; + } + // Check 1-10 Access Boundary Rules are defined within Credential Access + // Boundary. + if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules + .length === 0) { + throw new Error('At least one access boundary rule needs to be defined.'); + } + else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > + exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { + throw new Error('The provided access boundary has more than ' + + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); + } + // Check at least one permission should be defined in each Access Boundary + // Rule. + for (const rule of this.credentialAccessBoundary.accessBoundary + .accessBoundaryRules) { + if (rule.availablePermissions.length === 0) { + throw new Error('At least one permission should be defined in access boundary rules.'); + } + } + this.stsCredential = new sts.StsCredentials({ + tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token`, + }); + this.cachedDownscopedAccessToken = null; + } + /** + * Provides a mechanism to inject Downscoped access tokens directly. + * The expiry_date field is required to facilitate determination of the token + * expiration which would make it easier for the token consumer to handle. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + if (!credentials.expiry_date) { + throw new Error('The access token expiry_date field is missing in the provided ' + + 'credentials.'); + } + super.setCredentials(credentials); + this.cachedDownscopedAccessToken = credentials; + } + async getAccessToken() { + // If the cached access token is unavailable or expired, force refresh. + // The Downscoped access token will be returned in + // DownscopedAccessTokenResponse format. + if (!this.cachedDownscopedAccessToken || + this.isExpired(this.cachedDownscopedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return Downscoped access token in DownscopedAccessTokenResponse format. + return { + token: this.cachedDownscopedAccessToken.access_token, + expirationTime: this.cachedDownscopedAccessToken.expiry_date, + res: this.cachedDownscopedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = new Headers({ + authorization: `Bearer ${accessTokenResponse.token}`, + }); + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * GCP access tokens are retrieved from authclient object/source credential. + * Then GCP access tokens are exchanged for downscoped access tokens via the + * token exchange endpoint. + * @return A promise that resolves with the fresh downscoped access token. + */ + async refreshAccessTokenAsync() { + // Retrieve GCP access token from source credential. + const subjectToken = (await this.authClient.getAccessToken()).token; + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken: subjectToken, + subjectTokenType: STS_SUBJECT_TOKEN_TYPE, + }; + // Exchange the source AuthClient access token for a Downscoped access + // token. + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); + /** + * The STS endpoint will only return the expiration time for the downscoped + * access token if the original access token represents a service account. + * The downscoped token's expiration time will always match the source + * credential expiration. When no expires_in is returned, we can copy the + * source credential's expiration time. + */ + const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null; + const expiryDate = stsResponse.expires_in + ? new Date().getTime() + stsResponse.expires_in * 1000 + : sourceCredExpireDate; + // Save response in cached access token. + this.cachedDownscopedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: expiryDate, + res: stsResponse.res, + }; + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedDownscopedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedDownscopedAccessToken.expiry_date, + access_token: this.cachedDownscopedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedDownscopedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param downscopedAccessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(downscopedAccessToken) { + const now = new Date().getTime(); + return downscopedAccessToken.expiry_date + ? now >= + downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.DownscopedClient = DownscopedClient; +//# sourceMappingURL=downscopedclient.js.map + +/***/ }), + +/***/ 40747: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2018 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GCPEnv = void 0; +exports.clear = clear; +exports.getEnv = getEnv; +const gcpMetadata = __webpack_require__(4381); +var GCPEnv; +(function (GCPEnv) { + GCPEnv["APP_ENGINE"] = "APP_ENGINE"; + GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; + GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; + GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; + GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; + GCPEnv["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS"; + GCPEnv["NONE"] = "NONE"; +})(GCPEnv || (exports.GCPEnv = GCPEnv = {})); +let envPromise; +function clear() { + envPromise = undefined; +} +async function getEnv() { + if (envPromise) { + return envPromise; + } + envPromise = getEnvMemoized(); + return envPromise; +} +async function getEnvMemoized() { + let env = GCPEnv.NONE; + if (isAppEngine()) { + env = GCPEnv.APP_ENGINE; + } + else if (isCloudFunction()) { + env = GCPEnv.CLOUD_FUNCTIONS; + } + else if (await isComputeEngine()) { + if (await isKubernetesEngine()) { + env = GCPEnv.KUBERNETES_ENGINE; + } + else if (isCloudRun()) { + env = GCPEnv.CLOUD_RUN; + } + else if (isCloudRunJob()) { + env = GCPEnv.CLOUD_RUN_JOBS; + } + else { + env = GCPEnv.COMPUTE_ENGINE; + } + } + else { + env = GCPEnv.NONE; + } + return env; +} +function isAppEngine() { + return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); +} +function isCloudFunction() { + return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); +} +/** + * This check only verifies that the environment is running knative. + * This must be run *after* checking for Kubernetes, otherwise it will + * return a false positive. + */ +function isCloudRun() { + return !!process.env.K_CONFIGURATION; +} +function isCloudRunJob() { + return !!process.env.CLOUD_RUN_JOB; +} +async function isKubernetesEngine() { + try { + await gcpMetadata.instance('attributes/cluster-name'); + return true; + } + catch (e) { + return false; + } +} +async function isComputeEngine() { + return gcpMetadata.isAvailable(); +} +//# sourceMappingURL=envDetect.js.map + +/***/ }), + +/***/ 69079: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2022 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0; +const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2'; +const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token'; +const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt'; +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +class ExecutableResponse { + /** + * The version of the Executable response. Only version 1 is currently supported. + */ + version; + /** + * Whether the executable ran successfully. + */ + success; + /** + * The epoch time for expiration of the token in seconds. + */ + expirationTime; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + tokenType; + /** + * The error code from the executable. + */ + errorCode; + /** + * The error message from the executable. + */ + errorMessage; + /** + * The subject token from the executable, format depends on tokenType. + */ + subjectToken; + /** + * Instantiates an ExecutableResponse instance using the provided JSON object + * from the output of the executable. + * @param responseJson Response from a 3rd party executable, loaded from a + * run of the executable or a cached output file. + */ + constructor(responseJson) { + // Check that the required fields exist in the json response. + if (!responseJson.version) { + throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); + } + if (responseJson.success === undefined) { + throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); + } + this.version = responseJson.version; + this.success = responseJson.success; + // Validate required fields for a successful response. + if (this.success) { + this.expirationTime = responseJson.expiration_time; + this.tokenType = responseJson.token_type; + // Validate token type field. + if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { + throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); + } + // Validate subject token. + if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { + if (!responseJson.saml_response) { + throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); + } + this.subjectToken = responseJson.saml_response; + } + else { + if (!responseJson.id_token) { + throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); + } + this.subjectToken = responseJson.id_token; + } + } + else { + // Both code and message must be provided for unsuccessful responses. + if (!responseJson.code) { + throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); + } + if (!responseJson.message) { + throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); + } + this.errorCode = responseJson.code; + this.errorMessage = responseJson.message; + } + } + /** + * @return A boolean representing if the response has a valid token. Returns + * true when the response was successful and the token is not expired. + */ + isValid() { + return !this.isExpired() && this.success; + } + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired() { + return (this.expirationTime !== undefined && + this.expirationTime < Math.round(Date.now() / 1000)); + } +} +exports.ExecutableResponse = ExecutableResponse; +/** + * An error thrown by the ExecutableResponse class. + */ +class ExecutableResponseError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableResponseError = ExecutableResponseError; +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +class InvalidVersionFieldError extends ExecutableResponseError { +} +exports.InvalidVersionFieldError = InvalidVersionFieldError; +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +class InvalidSuccessFieldError extends ExecutableResponseError { +} +exports.InvalidSuccessFieldError = InvalidSuccessFieldError; +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +class InvalidCodeFieldError extends ExecutableResponseError { +} +exports.InvalidCodeFieldError = InvalidCodeFieldError; +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +class InvalidMessageFieldError extends ExecutableResponseError { +} +exports.InvalidMessageFieldError = InvalidMessageFieldError; +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +class InvalidSubjectTokenError extends ExecutableResponseError { +} +exports.InvalidSubjectTokenError = InvalidSubjectTokenError; +//# sourceMappingURL=executable-response.js.map + +/***/ }), + +/***/ 69112: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2023 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0; +const authclient_1 = __webpack_require__(82594); +const oauth2common_1 = __webpack_require__(30069); +const gaxios_1 = __webpack_require__(10627); +const stream = __webpack_require__(2203); +const baseexternalclient_1 = __webpack_require__(89046); +/** + * The credentials JSON file type for external account authorized user clients. + */ +exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken'; +/** + * Handler for token refresh requests sent to the token_url endpoint for external + * authorized user credentials. + */ +class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { + #tokenRefreshEndpoint; + /** + * Initializes an ExternalAccountAuthorizedUserHandler instance. + * @param url The URL of the token refresh endpoint. + * @param transporter The transporter to use for the refresh request. + * @param clientAuthentication The client authentication credentials to use + * for the refresh request. + */ + constructor(options) { + super(options); + this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint; + } + /** + * Requests a new access token from the token_url endpoint using the provided + * refresh token. + * @param refreshToken The refresh token to use to generate a new access token. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @return A promise that resolves with the token refresh response containing + * the requested access token and its expiration time. + */ + async refreshToken(refreshToken, headers) { + const opts = { + ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, + url: this.#tokenRefreshEndpoint, + method: 'POST', + headers, + data: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + }), + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, 'refreshToken'); + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const tokenRefreshResponse = response.data; + tokenRefreshResponse.res = response; + return tokenRefreshResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +/** + * External Account Authorized User Client. This is used for OAuth2 credentials + * sourced using external identities through Workforce Identity Federation. + * Obtaining the initial access and refresh token can be done through the + * Google Cloud CLI. + */ +class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { + cachedAccessToken; + externalAccountAuthorizedUserHandler; + refreshToken; + /** + * Instantiates an ExternalAccountAuthorizedUserClient instances using the + * provided JSON object loaded from a credentials files. + * An error is throws if the credential is not valid. + * @param options The external account authorized user option object typically + * from the external accoutn authorized user JSON credential file. + */ + constructor(options) { + super(options); + if (options.universe_domain) { + this.universeDomain = options.universe_domain; + } + this.refreshToken = options.refresh_token; + const clientAuthentication = { + confidentialClientType: 'basic', + clientId: options.client_id, + clientSecret: options.client_secret, + }; + this.externalAccountAuthorizedUserHandler = + new ExternalAccountAuthorizedUserHandler({ + tokenRefreshEndpoint: options.token_url ?? + DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), + transporter: this.transporter, + clientAuthentication, + }); + this.cachedAccessToken = null; + this.quotaProjectId = options.quota_project_id; + // As threshold could be zero, + // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the + // zero value. + if (typeof options?.eagerRefreshThresholdMillis !== 'number') { + this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; + } + else { + this.eagerRefreshThresholdMillis = options + .eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure; + } + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = new Headers({ + authorization: `Bearer ${accessTokenResponse.token}`, + }); + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + async refreshAccessTokenAsync() { + // Refresh the access token using the refresh token. + const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); + this.cachedAccessToken = { + access_token: refreshResponse.access_token, + expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, + res: refreshResponse.res, + }; + if (refreshResponse.refresh_token !== undefined) { + this.refreshToken = refreshResponse.refresh_token; + } + return this.cachedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param credentials The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(credentials) { + const now = new Date().getTime(); + return credentials.expiry_date + ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; +//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map + +/***/ }), + +/***/ 28939: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ExternalAccountClient = void 0; +const baseexternalclient_1 = __webpack_require__(89046); +const identitypoolclient_1 = __webpack_require__(14032); +const awsclient_1 = __webpack_require__(25845); +const pluggable_auth_client_1 = __webpack_require__(35189); +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +class ExternalAccountClient { + constructor() { + throw new Error('ExternalAccountClients should be initialized via: ' + + 'ExternalAccountClient.fromJSON(), ' + + 'directly via explicit constructors, eg. ' + + 'new AwsClient(options), new IdentityPoolClient(options), new' + + 'PluggableAuthClientOptions, or via ' + + 'new GoogleAuth(options).getClient()'); + } + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * + * **IMPORTANT**: This method does not validate the credential configuration. + * A security risk occurs when a credential configuration configured with + * malicious URLs is used. When the credential configuration is accepted from + * an untrusted source, you should validate it before using it with this + * method. For more details, see + * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials. + * + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options) { + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if (options.credential_source?.environment_id) { + return new awsclient_1.AwsClient(options); + } + else if (options.credential_source?.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options); + } + else { + return new identitypoolclient_1.IdentityPoolClient(options); + } + } + else { + return null; + } + } +} +exports.ExternalAccountClient = ExternalAccountClient; +//# sourceMappingURL=externalclient.js.map + +/***/ }), + +/***/ 4284: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2024 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileSubjectTokenSupplier = void 0; +const util_1 = __webpack_require__(39023); +const fs = __webpack_require__(79896); +// fs.readfile is undefined in browser karma tests causing +// `npm run browser-test` to fail as test.oauth2.ts imports this file via +// src/index.ts. +// Fallback to void function to avoid promisify throwing a TypeError. +const readFile = (0, util_1.promisify)(fs.readFile ?? (() => { })); +const realpath = (0, util_1.promisify)(fs.realpath ?? (() => { })); +const lstat = (0, util_1.promisify)(fs.lstat ?? (() => { })); +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class FileSubjectTokenSupplier { + filePath; + formatType; + subjectTokenFieldName; + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts) { + this.filePath = opts.filePath; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + } + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken() { + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + let parsedFilePath = this.filePath; + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + parsedFilePath = await realpath(parsedFilePath); + if (!(await lstat(parsedFilePath)).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + let subjectToken; + const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); + if (this.formatType === 'text') { + subjectToken = rawText; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const json = JSON.parse(rawText); + subjectToken = json[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source file'); + } + return subjectToken; + } +} +exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; +//# sourceMappingURL=filesubjecttokensupplier.js.map + +/***/ }), + +/***/ 56568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2026 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GdchClient = exports.GDCH_SERVICE_ACCOUNT_TYPE = void 0; +const crypto = __webpack_require__(76982); +const fs = __webpack_require__(79896); +const https = __webpack_require__(65692); +const oauth2client_1 = __webpack_require__(64739); +const DEFAULT_LIFETIME_IN_SECONDS = 3600; +exports.GDCH_SERVICE_ACCOUNT_TYPE = 'gdch_service_account'; +class GdchClient extends oauth2client_1.OAuth2Client { + projectId; + privateKeyId; + privateKey; + serviceIdentityName; + tokenServerUri; + caCertPath; + apiAudience; + lifetime; + gdchOptions; + caAgentPromise; + cachedCaCertPath; + lastCaCertReadTime = 0; + CA_CERT_TTL_MS = 5 * 60 * 1000; + constructor(options = {}) { + super(options); + this.gdchOptions = options; + this.projectId = options.projectId || undefined; + this.privateKeyId = options.privateKeyId; + this.privateKey = options.privateKey; + this.serviceIdentityName = options.serviceIdentityName; + this.tokenServerUri = options.tokenServerUri; + this.caCertPath = options.caCertPath; + this.apiAudience = options.apiAudience; + this.lifetime = options.lifetime || DEFAULT_LIFETIME_IN_SECONDS; + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { refresh_token: 'gdch-placeholder', expiry_date: 1 }; + } + createWithGdchAudience(apiAudience) { + if (!apiAudience) { + throw new Error('Audience cannot be null or empty for GDCH service account credentials.'); + } + return new GdchClient({ + ...this.gdchOptions, + projectId: this.projectId, + privateKeyId: this.privateKeyId, + privateKey: this.privateKey, + serviceIdentityName: this.serviceIdentityName, + tokenServerUri: this.tokenServerUri, + caCertPath: this.caCertPath, + lifetime: this.lifetime, + apiAudience, + }); + } + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the GDCH credentials settings.'); + } + if (json.type !== exports.GDCH_SERVICE_ACCOUNT_TYPE) { + throw new Error(`The incoming JSON object does not have the "${exports.GDCH_SERVICE_ACCOUNT_TYPE}" type`); + } + if (json.format_version !== '1') { + throw new Error('Only format version 1 is supported.'); + } + if (!json.project) { + throw new Error('The incoming JSON object does not contain a project field'); + } + if (!json.private_key_id) { + throw new Error('The incoming JSON object does not contain a private_key_id field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + if (!json.name) { + throw new Error('The incoming JSON object does not contain a name field'); + } + if (!json.token_uri) { + throw new Error('The incoming JSON object does not contain a token_uri field'); + } + this.projectId = json.project; + this.privateKeyId = json.private_key_id; + this.privateKey = json.private_key; + this.serviceIdentityName = json.name; + this.tokenServerUri = json.token_uri; + this.caCertPath = json.ca_cert_path; + this.gdchOptions = { + ...this.gdchOptions, + projectId: json.project, + privateKeyId: json.private_key_id, + privateKey: json.private_key, + serviceIdentityName: json.name, + tokenServerUri: json.token_uri, + caCertPath: json.ca_cert_path, + }; + } + async refreshTokenNoCache() { + if (!this.apiAudience) { + throw new Error('Audience cannot be null or empty for GDCH service account credentials. ' + + 'Specify the audience by calling createWithGdchAudience.'); + } + if (!this.privateKey) { + throw new Error('Private key is not configured for GDCH credentials.'); + } + if (!this.privateKeyId) { + throw new Error('Private key ID is not configured for GDCH credentials.'); + } + if (!this.projectId) { + throw new Error('Project is not configured for GDCH credentials.'); + } + if (!this.serviceIdentityName) { + throw new Error('Service identity name is not configured for GDCH credentials.'); + } + if (!this.tokenServerUri) { + throw new Error('Token server URI is not configured for GDCH credentials.'); + } + const assertion = this.createAssertion(); + const data = { + audience: this.apiAudience, + grant_type: 'urn:ietf:params:oauth:token-type:token-exchange', + requested_token_type: 'urn:ietf:params:oauth:token-type:access_token', + subject_token: assertion, + subject_token_type: 'urn:k8s:params:oauth:token-type:serviceaccount', + }; + const requestOpts = { + url: this.tokenServerUri, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + data, + responseType: 'json', + timeout: 10000, + retry: true, + retryConfig: { + httpMethodsToRetry: ['POST'], + statusCodesToRetry: [[500, 599]], + noResponseRetries: 3, + }, + }; + if (this.caCertPath) { + requestOpts.agent = await this.getCaAgent(); + } + try { + const res = await this.transporter.request(requestOpts); + const tokenResponse = res.data; + if (!tokenResponse.access_token) { + throw new Error('Token response did not contain an access_token.'); + } + if (!tokenResponse.expires_in) { + throw new Error('Token response did not contain an expires_in field.'); + } + const tokens = { + access_token: tokenResponse.access_token, + token_type: 'STS-Bearer', + expiry_date: Date.now() + tokenResponse.expires_in * 1000, + }; + this.emit('tokens', tokens); + return { res, tokens }; + } + catch (e) { + if (e && e.config && e.config.data) { + try { + if (typeof e.config.data === 'string') { + const parsedData = JSON.parse(e.config.data); + if (parsedData.subject_token) { + parsedData.subject_token = '***REDACTED***'; + e.config.data = JSON.stringify(parsedData); + } + } + else if (typeof e.config.data === 'object' && e.config.data.subject_token) { + e.config.data.subject_token = '***REDACTED***'; + } + } + catch { } + } + if (e instanceof Error) { + e.message = `Error getting access token for GDCH service account: ${e.message}, iss: ${this.serviceIdentityName}`; + } + throw e; + } + } + createAssertion() { + const header = { + alg: 'ES256', + typ: 'JWT', + kid: this.privateKeyId, + }; + const issSub = `system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`; + const currentTime = Math.floor(Date.now() / 1000); + const payload = { + iss: issSub, + sub: issSub, + iat: currentTime, + exp: currentTime + this.lifetime, + aud: this.tokenServerUri, + }; + const encodedHeader = this.base64UrlEncode(JSON.stringify(header)); + const encodedPayload = this.base64UrlEncode(JSON.stringify(payload)); + const signingInput = `${encodedHeader}.${encodedPayload}`; + const signature = crypto.sign('sha256', Buffer.from(signingInput), { + key: this.privateKey, + dsaEncoding: 'ieee-p1363', + }); + const encodedSignature = this.base64UrlEncode(signature); + return `${signingInput}.${encodedSignature}`; + } + async requestAsync(opts, retry = false) { + if (this.caCertPath && !opts.agent) { + const url = (opts.url || '').toString(); + if (!url.includes('googleapis.com') && !url.includes('google.com')) { + opts.agent = await this.getCaAgent(); + } + } + return super.requestAsync(opts, retry); + } + getCaAgent() { + if (!this.caCertPath) { + this.caAgentPromise = undefined; + this.cachedCaCertPath = undefined; + this.lastCaCertReadTime = 0; + return undefined; + } + const now = Date.now(); + const isCacheExpired = now - this.lastCaCertReadTime > this.CA_CERT_TTL_MS; + if (this.caAgentPromise && + this.caCertPath === this.cachedCaCertPath && + !isCacheExpired) { + return this.caAgentPromise; + } + this.cachedCaCertPath = this.caCertPath; + this.lastCaCertReadTime = now; + const currentPath = this.caCertPath; + this.caAgentPromise = (async () => { + try { + const ca = await fs.promises.readFile(currentPath); + return new https.Agent({ ca }); + } + catch (err) { + if (this.cachedCaCertPath === currentPath) { + this.caAgentPromise = undefined; + this.cachedCaCertPath = undefined; + this.lastCaCertReadTime = 0; + } + if (err instanceof Error) { + err.message = `Error reading certificate file from CA cert path, value '${currentPath}': ${err.message}`; + } + throw err; + } + })(); + return this.caAgentPromise; + } + toJSON() { + return { + ...this, + privateKey: this.privateKey ? '***REDACTED***' : undefined, + _clientSecret: this._clientSecret ? '***REDACTED***' : undefined, + apiKey: this.apiKey ? '***REDACTED***' : undefined, + gdchOptions: this.gdchOptions + ? { + ...this.gdchOptions, + privateKey: this.gdchOptions.privateKey ? '***REDACTED***' : undefined, + clientSecret: this.gdchOptions.clientSecret ? '***REDACTED***' : undefined, + client_secret: this.gdchOptions.client_secret ? '***REDACTED***' : undefined, + apiKey: this.gdchOptions.apiKey ? '***REDACTED***' : undefined, + credentials: this.gdchOptions.credentials + ? { + ...this.gdchOptions.credentials, + access_token: this.gdchOptions.credentials.access_token + ? '***REDACTED***' + : undefined, + refresh_token: this.gdchOptions.credentials.refresh_token + ? '***REDACTED***' + : undefined, + } + : undefined, + } + : undefined, + credentials: { + ...this.credentials, + access_token: this.credentials?.access_token ? '***REDACTED***' : undefined, + refresh_token: this.credentials?.refresh_token ? '***REDACTED***' : undefined, + }, + }; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.toJSON(); + } + base64UrlEncode(str) { + const buffer = typeof str === 'string' ? Buffer.from(str) : str; + return buffer.toString('base64url'); + } +} +exports.GdchClient = GdchClient; +//# sourceMappingURL=gdchclient.js.map + +/***/ }), + +/***/ 2662: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2019 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0; +const child_process_1 = __webpack_require__(35317); +const fs = __webpack_require__(79896); +const gaxios_1 = __webpack_require__(10627); +const gcpMetadata = __webpack_require__(4381); +const os = __webpack_require__(70857); +const path = __webpack_require__(16928); +const crypto_1 = __webpack_require__(6123); +const computeclient_1 = __webpack_require__(81945); +const idtokenclient_1 = __webpack_require__(20630); +const envDetect_1 = __webpack_require__(40747); +const jwtclient_1 = __webpack_require__(27397); +const refreshclient_1 = __webpack_require__(16983); +const impersonated_1 = __webpack_require__(19588); +const externalclient_1 = __webpack_require__(28939); +const baseexternalclient_1 = __webpack_require__(89046); +const authclient_1 = __webpack_require__(82594); +const externalAccountAuthorizedUserClient_1 = __webpack_require__(69112); +const gdchclient_1 = __webpack_require__(56568); +const util_1 = __webpack_require__(84358); +exports.GoogleAuthExceptionMessages = { + API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.', + NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.', + NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' + + 'To learn more about Universe Domain retrieval, visit: \n' + + 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys', +}; +class GoogleAuth { + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + checkIsGCE = undefined; + useJWTAccessWithScope; + defaultServicePath; + // Note: this properly is only public to satisfy unit tests. + // https://github.com/Microsoft/TypeScript/issues/5228 + get isGCE() { + return this.checkIsGCE; + } + _findProjectIdPromise; + _cachedProjectId; + // To save the contents of the JSON credential file + jsonContent = null; + apiKey; + cachedCredential = null; + /** + * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. + */ + #pendingAuthClient = null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes; + keyFilename; + scopes; + clientOptions = {}; + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts = {}) { + this._cachedProjectId = opts.projectId || null; + this.cachedCredential = opts.authClient || null; + this.keyFilename = opts.keyFilename || opts.keyFile; + this.scopes = opts.scopes; + this.clientOptions = opts.clientOptions || {}; + this.jsonContent = opts.credentials || null; + this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; + // Cannot use both API Key + Credentials + if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { + throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); + } + if (opts.universeDomain) { + this.clientOptions.universeDomain = opts.universeDomain; + } + } + // GAPIC client libraries should always use self-signed JWTs. The following + // variables are set on the JWT client in order to indicate the type of library, + // and sign the JWT with the correct audience and scopes (if not supplied). + setGapicJWTValues(client) { + client.defaultServicePath = this.defaultServicePath; + client.useJWTAccessWithScope = this.useJWTAccessWithScope; + client.defaultScopes = this.defaultScopes; + } + getProjectId(callback) { + if (callback) { + this.getProjectIdAsync().then(r => callback(null, r), callback); + } + else { + return this.getProjectIdAsync(); + } + } + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + async getProjectIdOptional() { + try { + return await this.getProjectId(); + } + catch (e) { + if (e instanceof Error && + e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { + return null; + } + else { + throw e; + } + } + } + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + async findAndCacheProjectId() { + let projectId = null; + projectId ||= await this.getProductionProjectId(); + projectId ||= await this.getFileProjectId(); + projectId ||= await this.getDefaultServiceProjectId(); + projectId ||= await this.getGCEProjectId(); + projectId ||= await this.getExternalAccountClientProjectId(); + if (projectId) { + this._cachedProjectId = projectId; + return projectId; + } + else { + throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); + } + } + async getProjectIdAsync() { + if (this._cachedProjectId) { + return this._cachedProjectId; + } + if (!this._findProjectIdPromise) { + this._findProjectIdPromise = this.findAndCacheProjectId(); + } + return this._findProjectIdPromise; + } + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + async getUniverseDomainFromMetadataServer() { + let universeDomain; + try { + universeDomain = await gcpMetadata.universe('universe-domain'); + universeDomain ||= authclient_1.DEFAULT_UNIVERSE; + } + catch (e) { + if (e && e?.response?.status === 404) { + universeDomain = authclient_1.DEFAULT_UNIVERSE; + } + else { + throw e; + } + } + return universeDomain; + } + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + async getUniverseDomain() { + let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain'); + try { + universeDomain ??= (await this.getClient()).universeDomain; + } + catch { + // client or ADC is not available + universeDomain ??= authclient_1.DEFAULT_UNIVERSE; + } + return universeDomain; + } + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + getAnyScopes() { + return this.scopes || this.defaultScopes; + } + getApplicationDefault(optionsOrCallback = {}, callback) { + let options; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); + } + else { + return this.getApplicationDefaultAsync(options); + } + } + async getApplicationDefaultAsync(options = {}) { + // If we've already got a cached credential, return it. + // This will also preserve one's configured quota project, in case they + // set one directly on the credential previously. + if (this.cachedCredential) { + // cache, while preserving existing quota project preferences + return await this.#prepareAndCacheClient(this.cachedCredential, null); + } + let credential; + // Check for the existence of a local environment variable pointing to the + // location of the credential file. This is typically used in local + // developer scenarios. + credential = + await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await this.#prepareAndCacheClient(credential); + } + // Look in the well-known credential file location. + credential = + await this._tryGetApplicationCredentialsFromWellKnownFile(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await this.#prepareAndCacheClient(credential); + } + // Determine if we're running on GCE. + if (await this._checkIsGCE()) { + options.scopes = this.getAnyScopes(); + return await this.#prepareAndCacheClient(new computeclient_1.Compute(options)); + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); + } + async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) { + const projectId = await this.getProjectIdOptional(); + if (quotaProjectIdOverride) { + credential.quotaProjectId = quotaProjectIdOverride; + } + this.cachedCredential = credential; + return { credential, projectId }; + } + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + async _checkIsGCE() { + if (this.checkIsGCE === undefined) { + this.checkIsGCE = + gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable()); + } + return this.checkIsGCE; + } + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { + const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || + process.env['google_application_credentials']; + if (!credentialsPath || credentialsPath.length === 0) { + return null; + } + try { + return await this._getApplicationCredentialsFromFilePath(credentialsPath, options); + } + catch (e) { + if (e instanceof Error) { + e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; + } + throw e; + } + } + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromWellKnownFile(options) { + // First, figure out the location of the Cloud SDK config directory. The + // `CLOUDSDK_CONFIG` environment variable overrides the platform-specific + // default location; when it is set, `gcloud` stores the application default + // credentials file there, so it takes precedence. + let configDir = process.env['CLOUDSDK_CONFIG']; + if (!configDir) { + if (this._isWindows()) { + // Windows + if (process.env['APPDATA']) { + configDir = path.join(process.env['APPDATA'], 'gcloud'); + } + } + else { + // Linux or Mac + const home = process.env['HOME']; + if (home) { + configDir = path.join(home, '.config', 'gcloud'); + } + } + } + // The config directory could not be determined. + if (!configDir) { + return null; + } + const location = path.join(configDir, 'application_default_credentials.json'); + // The file does not exist. + if (!fs.existsSync(location)) { + return null; + } + // The file seems to exist. Try to use it. + const client = await this._getApplicationCredentialsFromFilePath(location, options); + return client; + } + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + async _getApplicationCredentialsFromFilePath(filePath, options = {}) { + // Make sure the path looks like a string. + if (!filePath || filePath.length === 0) { + throw new Error('The file path is invalid.'); + } + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + filePath = fs.realpathSync(filePath); + if (!fs.lstatSync(filePath).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + // Now open a read stream on the file, and parse it. + const readStream = fs.createReadStream(filePath); + return this.fromStream(readStream, options); + } + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing an impersonated refresh token'); + } + if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); + } + if (!json.source_credentials) { + throw new Error('The incoming JSON object does not contain a source_credentials field'); + } + if (!json.service_account_impersonation_url) { + throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field'); + } + const sourceClient = this.fromJSON(json.source_credentials); + if (json.service_account_impersonation_url?.length > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85} + **/ + throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`); + } + // Extract service account from service_account_impersonation_url + const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target; + if (!targetPrincipal) { + throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); + } + const targetScopes = (this.scopes || json.scopes || this.defaultScopes) ?? []; + return new impersonated_1.Impersonated({ + ...json, + sourceClient, + targetPrincipal, + targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes], + }); + } + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @deprecated This method is being deprecated because of a potential security risk. + * + * This method does not validate the credential configuration. The security + * risk occurs when a credential configuration is accepted from a source that + * is not under your control and used without validation on your side. + * + * If you know that you will be loading credential configurations of a + * specific type, it is recommended to use a credential-type-specific + * constructor. This will ensure that an unexpected credential type with + * potential for malicious intent is not loaded unintentionally. You might + * still have to do validation for certain credential types. Please follow + * the recommendation for that method. For example, if you want to load only + * service accounts, you can use the `JWT` constructor: + * ``` + * const {JWT} = require('google-auth-library'); + * const keys = require('/path/to/key.json'); + * const client = new JWT({ + * email: keys.client_email, + * key: keys.private_key, + * scopes: ['https://www.googleapis.com/auth/cloud-platform'], + * }); + * ``` + * + * If you are loading your credential configuration from an untrusted source and have + * not mitigated the risks (e.g. by validating the configuration yourself), make + * these changes as soon as possible to prevent security risks to your environment. + * + * Regardless of the method used, it is always your responsibility to validate + * configurations received from external sources. + * + * For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json, options = {}) { + let client; + // user's preferred universe domain + const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { + client = new refreshclient_1.UserRefreshClient(options); + client.fromJSON(json); + } + else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + client = this.fromImpersonatedJSON(json); + } + else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + client = externalclient_1.ExternalAccountClient.fromJSON({ + ...json, + ...options, + }); + client.scopes = this.getAnyScopes(); + } + else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { + client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({ + ...json, + ...options, + }); + } + else if (json.type === gdchclient_1.GDCH_SERVICE_ACCOUNT_TYPE) { + client = new gdchclient_1.GdchClient(options); + client.fromJSON(json); + } + else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + this.setGapicJWTValues(client); + client.fromJSON(json); + } + if (preferredUniverseDomain) { + client.universeDomain = preferredUniverseDomain; + } + return client; + } + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + _cacheClientFromJSON(json, options) { + const client = this.fromJSON(json, options); + // cache both raw data used to instantiate client and client itself. + this.jsonContent = json; + this.cachedCredential = client; + return client; + } + fromStream(inputStream, optionsOrCallback = {}, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); + } + else { + return this.fromStreamAsync(inputStream, options); + } + } + fromStreamAsync(inputStream, options) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the Google auth settings.'); + } + const chunks = []; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => chunks.push(chunk)) + .on('end', () => { + try { + try { + const data = JSON.parse(chunks.join('')); + const r = this._cacheClientFromJSON(data, options); + return resolve(r); + } + catch (err) { + // If we failed parsing this.keyFileName, assume that it + // is a PEM or p12 certificate: + if (!this.keyFilename) + throw err; + const client = new jwtclient_1.JWT({ + ...this.clientOptions, + keyFile: this.keyFilename, + }); + this.cachedCredential = client; + this.setGapicJWTValues(client); + return resolve(client); + } + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey, options = {}) { + return new jwtclient_1.JWT({ ...options, apiKey }); + } + /** + * Determines whether the current operating system is Windows. + * @api private + */ + _isWindows() { + const sys = os.platform(); + if (sys && sys.length >= 3) { + if (sys.substring(0, 3).toLowerCase() === 'win') { + return true; + } + } + return false; + } + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + async getDefaultServiceProjectId() { + return new Promise(resolve => { + (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { + if (!err && stdout) { + try { + const projectId = JSON.parse(stdout).configuration.properties.core.project; + resolve(projectId); + return; + } + catch (e) { + // ignore errors + } + } + resolve(null); + }); + }); + } + /** + * Loads the project id from environment variables. + * @api private + */ + getProductionProjectId() { + return (process.env['GCLOUD_PROJECT'] || + process.env['GOOGLE_CLOUD_PROJECT'] || + process.env['gcloud_project'] || + process.env['google_cloud_project']); + } + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + async getFileProjectId() { + if (this.cachedCredential) { + // Try to read the project ID from the cached credentials file + return this.cachedCredential.projectId; + } + // Ensure the projectId is loaded from the keyFile if available. + if (this.keyFilename) { + const creds = await this.getClient(); + if (creds && creds.projectId) { + return creds.projectId; + } + } + // Try to load a credentials file and read its project ID + const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); + if (r) { + return r.projectId; + } + else { + return null; + } + } + /** + * Gets the project ID from external account client if available. + */ + async getExternalAccountClientProjectId() { + if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + return null; + } + const creds = await this.getClient(); + // Do not suppress the underlying error, as the error could contain helpful + // information for debugging and fixing. This is especially true for + // external account creds as in order to get the project ID, the following + // operations have to succeed: + // 1. Valid credentials file should be supplied. + // 2. Ability to retrieve access tokens from STS token exchange API. + // 3. Ability to exchange for service account impersonated credentials (if + // enabled). + // 4. Ability to get project info using the access token from step 2 or 3. + // Without surfacing the error, it is harder for developers to determine + // which step went wrong. + return await creds.getProjectId(); + } + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + async getGCEProjectId() { + try { + const r = await gcpMetadata.project('project-id'); + return r; + } + catch (e) { + // Ignore any errors + return null; + } + } + getCredentials(callback) { + if (callback) { + this.getCredentialsAsync().then(r => callback(null, r), callback); + } + else { + return this.getCredentialsAsync(); + } + } + async getCredentialsAsync() { + const client = await this.getClient(); + if (client instanceof impersonated_1.Impersonated) { + return { client_email: client.getTargetPrincipal() }; + } + if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { + const serviceAccountEmail = client.getServiceAccountEmail(); + if (serviceAccountEmail) { + return { + client_email: serviceAccountEmail, + universe_domain: client.universeDomain, + }; + } + } + if (this.jsonContent) { + return { + client_email: this.jsonContent.client_email, + private_key: this.jsonContent.private_key, + universe_domain: this.jsonContent.universe_domain, + }; + } + if (await this._checkIsGCE()) { + const [client_email, universe_domain] = await Promise.all([ + gcpMetadata.instance('service-accounts/default/email'), + this.getUniverseDomain(), + ]); + return { client_email, universe_domain }; + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); + } + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + async getClient() { + if (this.cachedCredential) { + return this.cachedCredential; + } + // Use an existing auth client request, or cache a new one + this.#pendingAuthClient = + this.#pendingAuthClient || this.#determineClient(); + try { + const client = await this.#pendingAuthClient; + if (client instanceof gdchclient_1.GdchClient && !client.apiAudience) { + const opts = this.clientOptions; + const endpoint = opts.apiEndpoint || opts.servicePath; + if (endpoint) { + const scheme = endpoint.startsWith('http') ? '' : 'https://'; + const formattedAudience = `${scheme}${endpoint}`.replace(/\/+$/, ''); + const newClient = client.createWithGdchAudience(formattedAudience); + this.cachedCredential = newClient; + return newClient; + } + } + return client; + } + finally { + // reset the pending auth client in case it is changed later + this.#pendingAuthClient = null; + } + } + async #determineClient() { + if (this.jsonContent) { + return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); + } + else if (this.keyFilename) { + const filePath = path.resolve(this.keyFilename); + const stream = fs.createReadStream(filePath); + return await this.fromStreamAsync(stream, this.clientOptions); + } + else if (this.apiKey) { + const client = await this.fromAPIKey(this.apiKey, this.clientOptions); + client.scopes = this.scopes; + const { credential } = await this.#prepareAndCacheClient(client); + return credential; + } + else { + const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); + return credential; + } + } + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + async getIdTokenClient(targetAudience) { + const client = await this.getClient(); + if (!('fetchIdToken' in client)) { + throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); + } + return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); + } + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + async getAccessToken() { + const client = await this.getClient(); + return (await client.getAccessToken()).token; + } + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + async getRequestHeaders(url) { + const client = await this.getClient(); + return client.getRequestHeaders(url); + } + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + async authorizeRequest(opts = {}) { + const url = opts.url; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers); + return opts; + } + /** + * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}. + * + * @see {@link GoogleAuth.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const auth = new GoogleAuth(); + * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args); + * await fetchWithAuth('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + async fetch(...args) { + const client = await this.getClient(); + return client.fetch(...args); + } + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * + * @see {@link GoogleAuth.fetch} for the modern method. + * + * @param opts Axios request options for the HTTP request. + */ + async request(opts) { + const client = await this.getClient(); + return client.request(opts); + } + /** + * Determine the compute environment in which the code is running. + */ + getEnv() { + return (0, envDetect_1.getEnv)(); + } + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + async sign(data, endpoint) { + const client = await this.getClient(); + const universe = await this.getUniverseDomain(); + endpoint = + endpoint || + `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; + if (client instanceof impersonated_1.Impersonated) { + const signed = await client.sign(data); + return signed.signedBlob; + } + const crypto = (0, crypto_1.createCrypto)(); + if (client instanceof jwtclient_1.JWT && client.key) { + const sign = await crypto.sign(client.key, data); + return sign; + } + const creds = await this.getCredentials(); + if (!creds.client_email) { + throw new Error('Cannot sign data without `client_email`.'); + } + return this.signBlob(crypto, creds.client_email, data, endpoint); + } + async signBlob(crypto, emailOrUniqueId, data, endpoint) { + const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); + const res = await this.request({ + method: 'POST', + url: url.href, + data: { + payload: crypto.encodeBase64StringUtf8(data), + }, + retry: true, + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }); + return res.data.signedBlob; + } +} +exports.GoogleAuth = GoogleAuth; +//# sourceMappingURL=googleauth.js.map + +/***/ }), + +/***/ 30310: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2014 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IAMAuth = void 0; +class IAMAuth { + selector; + token; + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector, token) { + this.selector = selector; + this.token = token; + this.selector = selector; + this.token = token; + } + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders() { + return { + 'x-goog-iam-authority-selector': this.selector, + 'x-goog-iam-authorization-token': this.token, + }; + } +} +exports.IAMAuth = IAMAuth; +//# sourceMappingURL=iam.js.map + +/***/ }), + +/***/ 14032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IdentityPoolClient = void 0; +const baseexternalclient_1 = __webpack_require__(89046); +const util_1 = __webpack_require__(84358); +const filesubjecttokensupplier_1 = __webpack_require__(4284); +const urlsubjecttokensupplier_1 = __webpack_require__(44571); +const certificatesubjecttokensupplier_1 = __webpack_require__(34505); +const stscredentials_1 = __webpack_require__(51537); +const gaxios_1 = __webpack_require__(10627); +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + subjectTokenSupplier; + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + */ + constructor(options) { + super(options); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const subjectTokenSupplier = opts.get('subject_token_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !subjectTokenSupplier) { + throw new Error('A credential source or subject token supplier must be specified.'); + } + if (credentialSource && subjectTokenSupplier) { + throw new Error('Only one of credential source or subject token supplier can be specified.'); + } + if (subjectTokenSupplier) { + this.subjectTokenSupplier = subjectTokenSupplier; + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); + // Text is the default format type. + const formatType = formatOpts.get('type') || 'text'; + const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); + if (formatType !== 'json' && formatType !== 'text') { + throw new Error(`Invalid credential_source format "${formatType}"`); + } + if (formatType === 'json' && !formatSubjectTokenFieldName) { + throw new Error('Missing subject_token_field_name for JSON credential_source format'); + } + const file = credentialSourceOpts.get('file'); + const url = credentialSourceOpts.get('url'); + const certificate = credentialSourceOpts.get('certificate'); + const headers = credentialSourceOpts.get('headers'); + if ((file && url) || (url && certificate) || (file && certificate)) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); + } + else if (file) { + this.credentialSourceType = 'file'; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + }); + } + else if (url) { + this.credentialSourceType = 'url'; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url: url, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers: headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, + }); + } + else if (certificate) { + this.credentialSourceType = 'certificate'; + const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({ + useDefaultCertificateConfig: certificate.use_default_certificate_config, + certificateConfigLocation: certificate.certificate_config_location, + trustChainPath: certificate.trust_chain_path, + }); + this.subjectTokenSupplier = certificateSubjecttokensupplier; + } + else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); + } + } + } + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) { + const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent(); + this.stsCredential = new stscredentials_1.StsCredentials({ + tokenExchangeEndpoint: this.getTokenUrl(), + clientAuthentication: this.clientAuth, + transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }), + }); + this.transporter = new gaxios_1.Gaxios({ + ...(this.transporter.defaults || {}), + agent: mtlsAgent, + }); + } + return subjectToken; + } +} +exports.IdentityPoolClient = IdentityPoolClient; +//# sourceMappingURL=identitypoolclient.js.map + +/***/ }), + +/***/ 20630: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2020 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IdTokenClient = void 0; +const oauth2client_1 = __webpack_require__(64739); +class IdTokenClient extends oauth2client_1.OAuth2Client { + targetAudience; + idTokenProvider; + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options) { + super(options); + this.targetAudience = options.targetAudience; + this.idTokenProvider = options.idTokenProvider; + } + async getRequestMetadataAsync() { + if (!this.credentials.id_token || + !this.credentials.expiry_date || + this.isTokenExpiring()) { + const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); + this.credentials = { + id_token: idToken, + expiry_date: this.getIdTokenExpiryDate(idToken), + }; + } + const headers = new Headers({ + authorization: 'Bearer ' + this.credentials.id_token, + }); + return { headers }; + } + getIdTokenExpiryDate(idToken) { + const payloadB64 = idToken.split('.')[1]; + if (payloadB64) { + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); + return payload.exp * 1000; + } + } +} +exports.IdTokenClient = IdTokenClient; +//# sourceMappingURL=idtokenclient.js.map + +/***/ }), + +/***/ 19588: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +/** + * Copyright 2021 Google LLC + * + * 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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; +const oauth2client_1 = __webpack_require__(64739); +const gaxios_1 = __webpack_require__(10627); +const util_1 = __webpack_require__(84358); +exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; +class Impersonated extends oauth2client_1.OAuth2Client { + sourceClient; + targetPrincipal; + targetScopes; + delegates; + lifetime; + endpoint; + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * **IMPORTANT**: This method does not validate the credential configuration. + * A security risk occurs when a credential configuration configured with + * malicious URLs is used. When the credential configuration is accepted from + * an untrusted source, you should validate it before using it with this + * method. For more details, see + * https://cloud.google.com/docs/authentication/external/externally-sourced-credentials. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { + expiry_date: 1, + refresh_token: 'impersonated-placeholder', + }; + this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client(); + this.targetPrincipal = options.targetPrincipal ?? ''; + this.delegates = options.delegates ?? []; + this.targetScopes = options.targetScopes ?? []; + this.lifetime = options.lifetime ?? 3600; + const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (!usingExplicitUniverseDomain) { + // override the default universe with the source's universe + this.universeDomain = this.sourceClient.universeDomain; + } + else if (this.sourceClient.universeDomain !== this.universeDomain) { + // non-default universe and is not matching the source - this could be a credential leak + throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + } + this.endpoint = + options.endpoint ?? `https://iamcredentials.${this.universeDomain}`; + } + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + async sign(blobToSign) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:signBlob`; + const body = { + delegates: this.delegates, + payload: Buffer.from(blobToSign).toString('base64'), + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data; + } + /** The service account email to be impersonated. */ + getTargetPrincipal() { + return this.targetPrincipal; + } + /** + * Refreshes the access token. + */ + async refreshToken() { + try { + await this.sourceClient.getAccessToken(); + const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; + const u = `${this.endpoint}/v1/${name}:generateAccessToken`; + const body = { + delegates: this.delegates, + scope: this.targetScopes, + lifetime: this.lifetime + 's', + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + const tokenResponse = res.data; + this.credentials.access_token = tokenResponse.accessToken; + this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); + return { + tokens: this.credentials, + res, + }; + } + catch (error) { + if (!(error instanceof Error)) + throw error; + let status = 0; + let message = ''; + if (error instanceof gaxios_1.GaxiosError) { + status = error?.response?.data?.error?.status; + message = error?.response?.data?.error?.message; + } + if (status && message) { + error.message = `${status}: unable to impersonate: ${message}`; + throw error; + } + else { + error.message = `unable to impersonate: ${error}`; + throw error; + } + } + } + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + async fetchIdToken(targetAudience, options) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:generateIdToken`; + const body = { + delegates: this.delegates, + audience: targetAudience, + includeEmail: options?.includeEmail ?? true, + useEmailAzp: options?.includeEmail ?? true, + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data.token; + } +} +exports.Impersonated = Impersonated; +//# sourceMappingURL=impersonated.js.map + +/***/ }), + +/***/ 15900: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2015 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JWTAccess = void 0; +const jws = __webpack_require__(16798); +const util_1 = __webpack_require__(84358); +const DEFAULT_HEADER = { + alg: 'RS256', + typ: 'JWT', +}; +class JWTAccess { + email; + key; + keyId; + projectId; + eagerRefreshThresholdMillis; + cache = new util_1.LRUCache({ + capacity: 500, + maxAge: 60 * 60 * 1000, + }); + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email, key, keyId, eagerRefreshThresholdMillis) { + this.email = email; + this.key = key; + this.keyId = keyId; + this.eagerRefreshThresholdMillis = + eagerRefreshThresholdMillis ?? 5 * 60 * 1000; + } + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url, scopes) { + let cacheKey = url; + if (scopes && Array.isArray(scopes) && scopes.length) { + cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; + } + else if (typeof scopes === 'string') { + cacheKey = url ? `${url}_${scopes}` : scopes; + } + if (!cacheKey) { + throw Error('Scopes or url must be provided'); + } + return cacheKey; + } + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url, additionalClaims, scopes) { + // Return cached authorization headers, unless we are within + // eagerRefreshThresholdMillis ms of them expiring: + const key = this.getCachedKey(url, scopes); + const cachedToken = this.cache.get(key); + const now = Date.now(); + if (cachedToken && + cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { + // Copying headers into a new `Headers` object to avoid potential leakage - + // as this is a cache it is possible for multiple requests to reference this + // same value. + return new Headers(cachedToken.headers); + } + const iat = Math.floor(Date.now() / 1000); + const exp = JWTAccess.getExpirationTime(iat); + let defaultClaims; + // Turn scopes into space-separated string + if (Array.isArray(scopes)) { + scopes = scopes.join(' '); + } + // If scopes are specified, sign with scopes + if (scopes) { + defaultClaims = { + iss: this.email, + sub: this.email, + scope: scopes, + exp, + iat, + }; + } + else { + defaultClaims = { + iss: this.email, + sub: this.email, + aud: url, + exp, + iat, + }; + } + // if additionalClaims are provided, ensure they do not collide with + // other required claims. + if (additionalClaims) { + for (const claim in defaultClaims) { + if (additionalClaims[claim]) { + throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + } + } + } + const header = this.keyId + ? { ...DEFAULT_HEADER, kid: this.keyId } + : DEFAULT_HEADER; + const payload = Object.assign(defaultClaims, additionalClaims); + // Sign the jwt and add it to the cache + const signedJWT = jws.sign({ header, payload, secret: this.key }); + const headers = new Headers({ authorization: `Bearer ${signedJWT}` }); + this.cache.set(key, { + expiration: exp * 1000, + headers, + }); + return headers; + } + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + static getExpirationTime(iat) { + const exp = iat + 3600; // 3600 seconds = 1 hour + return exp; + } + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + reject(new Error('Must pass in a stream containing the service account auth settings.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('data', chunk => (s += chunk)) + .on('error', reject) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (err) { + reject(err); + } + }); + }); + } +} +exports.JWTAccess = JWTAccess; +//# sourceMappingURL=jwtaccess.js.map + +/***/ }), + +/***/ 27397: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2013 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JWT = void 0; +const googleToken_1 = __webpack_require__(20451); +const getCredentials_1 = __webpack_require__(22629); +const jwtaccess_1 = __webpack_require__(15900); +const oauth2client_1 = __webpack_require__(64739); +const authclient_1 = __webpack_require__(82594); +class JWT extends oauth2client_1.OAuth2Client { + email; + keyFile; + key; + keyId; + defaultScopes; + scopes; + scope; + subject; + gtoken; + additionalClaims; + useJWTAccessWithScope; + defaultServicePath; + access; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param options the + */ + constructor(options = {}) { + super(options); + this.email = options.email; + this.keyFile = options.keyFile; + this.key = options.key; + this.keyId = options.keyId; + this.scopes = options.scopes; + this.subject = options.subject; + this.additionalClaims = options.additionalClaims; + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; + } + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes) { + const jwt = new JWT(this); + jwt.scopes = scopes; + return jwt; + } + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + async getRequestMetadataAsync(url) { + url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; + const useSelfSignedJWT = (!this.hasUserScopes() && url) || + (this.useJWTAccessWithScope && this.hasAnyScopes()) || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { + throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); + } + if (!this.apiKey && useSelfSignedJWT) { + if (this.additionalClaims && + this.additionalClaims.target_audience) { + const { tokens } = await this.refreshToken(); + return { + headers: this.addSharedMetadataHeaders(new Headers({ + authorization: `Bearer ${tokens.id_token}`, + })), + }; + } + else { + // no scopes have been set, but a uri has been provided. Use JWTAccess + // credentials. + if (!this.access) { + this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); + } + let scopes; + if (this.hasUserScopes()) { + scopes = this.scopes; + } + else if (!url) { + scopes = this.defaultScopes; + } + const useScopes = this.useJWTAccessWithScope || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, + // Scopes take precedent over audience for signing, + // so we only provide them if `useJWTAccessWithScope` is on or + // if we are in a non-default universe + useScopes ? scopes : undefined); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + else if (this.hasAnyScopes() || this.apiKey) { + return super.getRequestMetadataAsync(url); + } + else { + // If no audience, apiKey, or scopes are provided, we should not attempt + // to populate any headers: + return { headers: new Headers() }; + } + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + // Create a new gToken for fetching an ID token + const gtoken = new googleToken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: { target_audience: targetAudience }, + transporter: this.transporter, + }); + await gtoken.getToken({ + forceRefresh: true, + }); + if (!gtoken.idToken) { + throw new Error('Unknown error: Failed to fetch ID token'); + } + return gtoken.idToken; + } + /** + * Determine if there are currently scopes available. + */ + hasUserScopes() { + if (!this.scopes) { + return false; + } + return this.scopes.length > 0; + } + /** + * Are there any default or user scopes defined. + */ + hasAnyScopes() { + if (this.scopes && this.scopes.length > 0) + return true; + if (this.defaultScopes && this.defaultScopes.length > 0) + return true; + return false; + } + authorize(callback) { + if (callback) { + this.authorizeAsync().then(r => callback(null, r), callback); + } + else { + return this.authorizeAsync(); + } + } + async authorizeAsync() { + const result = await this.refreshToken(); + if (!result) { + throw new Error('No result returned'); + } + this.credentials = result.tokens; + this.credentials.refresh_token = 'jwt-placeholder'; + this.key = this.gtoken.googleTokenOptions?.key; + this.email = this.gtoken.googleTokenOptions?.iss; + return result.tokens; + } + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + async refreshTokenNoCache() { + const gtoken = this.createGToken(); + const token = await gtoken.getToken({ + forceRefresh: this.isTokenExpiring(), + }); + const tokens = { + access_token: token.access_token, + token_type: 'Bearer', + expiry_date: gtoken.expiresAt, + id_token: gtoken.idToken, + }; + this.emit('tokens', tokens); + return { res: null, tokens }; + } + /** + * Create a gToken if it doesn't already exist. + */ + createGToken() { + if (!this.gtoken) { + this.gtoken = new googleToken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: this.additionalClaims, + transporter: this.transporter, + }); + } + return this.gtoken; + } + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the service account auth settings.'); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (e) { + reject(e); + } + }); + }); + } + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey) { + if (typeof apiKey !== 'string') { + throw new Error('Must provide an API Key string.'); + } + this.apiKey = apiKey; + } + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + async getCredentials() { + if (this.key) { + return { private_key: this.key, client_email: this.email }; + } + else if (this.keyFile) { + const gtoken = this.createGToken(); + const creds = await (0, getCredentials_1.getCredentials)(this.keyFile); + return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } + throw new Error('A key or a keyFile must be provided to getCredentials.'); + } +} +exports.JWT = JWT; +//# sourceMappingURL=jwtclient.js.map + +/***/ }), + +/***/ 27186: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2014 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LoginTicket = void 0; +class LoginTicket { + envelope; + payload; + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env, pay) { + this.envelope = env; + this.payload = pay; + } + getEnvelope() { + return this.envelope; + } + getPayload() { + return this.payload; + } + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId() { + const payload = this.getPayload(); + if (payload && payload.sub) { + return payload.sub; + } + return null; + } + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes() { + return { envelope: this.getEnvelope(), payload: this.getPayload() }; + } +} +exports.LoginTicket = LoginTicket; +//# sourceMappingURL=loginticket.js.map + +/***/ }), + +/***/ 64739: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2019 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; +const gaxios_1 = __webpack_require__(10627); +const querystring = __webpack_require__(83480); +const stream = __webpack_require__(2203); +const formatEcdsa = __webpack_require__(58210); +const util_1 = __webpack_require__(84358); +const crypto_1 = __webpack_require__(6123); +const authclient_1 = __webpack_require__(82594); +const loginticket_1 = __webpack_require__(27186); +var CodeChallengeMethod; +(function (CodeChallengeMethod) { + CodeChallengeMethod["Plain"] = "plain"; + CodeChallengeMethod["S256"] = "S256"; +})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); +var CertificateFormat; +(function (CertificateFormat) { + CertificateFormat["PEM"] = "PEM"; + CertificateFormat["JWK"] = "JWK"; +})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +var ClientAuthentication; +(function (ClientAuthentication) { + ClientAuthentication["ClientSecretPost"] = "ClientSecretPost"; + ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic"; + ClientAuthentication["None"] = "None"; +})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); +class OAuth2Client extends authclient_1.AuthClient { + redirectUri; + certificateCache = {}; + certificateExpiry = null; + certificateCacheFormat = CertificateFormat.PEM; + refreshTokenPromises = new Map(); + endpoints; + issuers; + clientAuthentication; + // TODO: refactor tests to make this private + _clientId; + // TODO: refactor tests to make this private + _clientSecret; + refreshHandler; + /** + * An OAuth2 Client for Google APIs. + * + * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + */ + constructor(options = {}, + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + clientSecret, + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + redirectUri) { + super(typeof options === 'object' ? options : {}); + if (typeof options !== 'object') { + options = { + clientId: options, + clientSecret, + redirectUri, + }; + } + this._clientId = options.clientId || options.client_id; + this._clientSecret = options.clientSecret || options.client_secret; + this.redirectUri = options.redirectUri || options.redirect_uris?.[0]; + this.endpoints = { + tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo', + oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth', + oauth2TokenUrl: 'https://oauth2.googleapis.com/token', + oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke', + oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs', + oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs', + oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key', + ...options.endpoints, + }; + this.clientAuthentication = + options.clientAuthentication || ClientAuthentication.ClientSecretPost; + this.issuers = options.issuers || [ + 'accounts.google.com', + 'https://accounts.google.com', + this.universeDomain, + ]; + } + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; + /** + * Clock skew - five minutes in seconds + */ + static CLOCK_SKEW_SECS_ = 300; + /** + * The default max Token Lifetime is one day in seconds + */ + static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts = {}) { + if (opts.code_challenge_method && !opts.code_challenge) { + throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); + } + opts.response_type = opts.response_type || 'code'; + opts.client_id = opts.client_id || this._clientId; + opts.redirect_uri = opts.redirect_uri || this.redirectUri; + // Allow scopes to be passed either as array or a string + if (Array.isArray(opts.scope)) { + opts.scope = opts.scope.join(' '); + } + const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); + return (rootUrl + + '?' + + querystring.stringify(opts)); + } + generateCodeVerifier() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); + } + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + async generateCodeVerifierAsync() { + // base64 encoding uses 6 bits per character, and we want to generate128 + // characters. 6*128/8 = 96. + const crypto = (0, crypto_1.createCrypto)(); + const randomString = crypto.randomBytesBase64(96); + // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ + // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just + // swapping out a few chars. + const codeVerifier = randomString + .replace(/\+/g, '~') + .replace(/=/g, '_') + .replace(/\//g, '-'); + // Generate the base64 encoded SHA256 + const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); + // We need to use base64UrlEncoding instead of standard base64 + const codeChallenge = unencodedCodeChallenge + .split('=')[0] + .replace(/\+/g, '-') + .replace(/\//g, '_'); + return { codeVerifier, codeChallenge }; + } + getToken(codeOrOptions, callback) { + const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; + if (callback) { + this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); + } + else { + return this.getTokenAsync(options); + } + } + async getTokenAsync(options) { + const url = this.endpoints.oauth2TokenUrl.toString(); + const headers = new Headers(); + const values = { + client_id: options.client_id || this._clientId, + code_verifier: options.codeVerifier, + code: options.code, + grant_type: 'authorization_code', + redirect_uri: options.redirect_uri || this.redirectUri, + }; + if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { + const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); + headers.set('authorization', `Basic ${basic.toString('base64')}`); + } + if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { + values.client_secret = this._clientSecret; + } + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), + headers, + }; + authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync'); + const res = await this.transporter.request(opts); + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + async refreshToken(refreshToken) { + if (!refreshToken) { + return this.refreshTokenNoCache(refreshToken); + } + // If a request to refresh using the same token has started, + // return the same promise. + if (this.refreshTokenPromises.has(refreshToken)) { + return this.refreshTokenPromises.get(refreshToken); + } + const p = this.refreshTokenNoCache(refreshToken).then(r => { + this.refreshTokenPromises.delete(refreshToken); + return r; + }, e => { + this.refreshTokenPromises.delete(refreshToken); + throw e; + }); + this.refreshTokenPromises.set(refreshToken, p); + return p; + } + async refreshTokenNoCache(refreshToken) { + if (!refreshToken) { + throw new Error('No refresh token is set.'); + } + const url = this.endpoints.oauth2TokenUrl.toString(); + const data = { + refresh_token: refreshToken, + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + }; + let res; + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)), + }; + authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache'); + // request for new token + res = await this.transporter.request(opts); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError && + e.message === 'invalid_grant' && + e.response?.data && + /ReAuth/i.test(e.response.data.error_description)) { + e.message = JSON.stringify(e.response.data); + } + throw e; + } + const tokens = res.data; + // TODO: de-duplicate this code from a few spots + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + refreshAccessToken(callback) { + if (callback) { + this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); + } + else { + return this.refreshAccessTokenAsync(); + } + } + async refreshAccessTokenAsync() { + const r = await this.refreshToken(this.credentials.refresh_token); + const tokens = r.tokens; + tokens.refresh_token = this.credentials.refresh_token; + this.credentials = tokens; + return { credentials: this.credentials, res: r.res }; + } + getAccessToken(callback) { + if (callback) { + this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); + } + else { + return this.getAccessTokenAsync(); + } + } + async getAccessTokenAsync() { + const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); + if (shouldRefresh) { + if (!this.credentials.refresh_token) { + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); + return { token: this.credentials.access_token }; + } + } + else { + throw new Error('No refresh token or refresh handler callback is set.'); + } + } + const r = await this.refreshAccessTokenAsync(); + if (!r.credentials || (r.credentials && !r.credentials.access_token)) { + throw new Error('Could not refresh access token.'); + } + return { token: r.credentials.access_token, res: r.res }; + } + else { + return { token: this.credentials.access_token }; + } + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { authorization: 'Bearer ' } + */ + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; + } + async getRequestMetadataAsync(url) { + url; + const thisCreds = this.credentials; + if (!thisCreds.access_token && + !thisCreds.refresh_token && + !this.apiKey && + !this.refreshHandler) { + throw new Error('No access, refresh token, API key or refresh handler callback is set.'); + } + if (thisCreds.access_token && !this.isTokenExpiring()) { + thisCreds.token_type = thisCreds.token_type || 'Bearer'; + const headers = new Headers({ + authorization: thisCreds.token_type + ' ' + thisCreds.access_token, + }); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + // If refreshHandler exists, call processAndValidateRefreshHandler(). + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); + const headers = new Headers({ + authorization: 'Bearer ' + this.credentials.access_token, + }); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + if (this.apiKey) { + return { headers: new Headers({ 'X-Goog-Api-Key': this.apiKey }) }; + } + let r = null; + let tokens = null; + try { + r = await this.refreshToken(thisCreds.refresh_token); + tokens = r.tokens; + } + catch (err) { + const e = err; + if (e.response && + (e.response.status === 403 || e.response.status === 404)) { + e.message = `Could not refresh access token: ${e.message}`; + } + throw e; + } + const credentials = this.credentials; + credentials.token_type = credentials.token_type || 'Bearer'; + tokens.refresh_token = credentials.refresh_token; + this.credentials = tokens; + const headers = new Headers({ + authorization: credentials.token_type + ' ' + tokens.access_token, + }); + return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; + } + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token) { + return new OAuth2Client().getRevokeTokenURL(token).toString(); + } + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token) { + const url = new URL(this.endpoints.oauth2RevokeUrl); + url.searchParams.append('token', token); + return url; + } + revokeToken(token, callback) { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url: this.getRevokeTokenURL(token).toString(), + method: 'POST', + }; + authclient_1.AuthClient.setMethodName(opts, 'revokeToken'); + if (callback) { + this.transporter + .request(opts) + .then(r => callback(null, r), callback); + } + else { + return this.transporter.request(opts); + } + } + revokeCredentials(callback) { + if (callback) { + this.revokeCredentialsAsync().then(res => callback(null, res), callback); + } + else { + return this.revokeCredentialsAsync(); + } + } + async revokeCredentialsAsync() { + const token = this.credentials.access_token; + this.credentials = {}; + if (token) { + return this.revokeToken(token); + } + else { + throw new Error('No access token to revoke.'); + } + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + async requestAsync(opts, reAuthRetried = false) { + try { + const r = await this.getRequestMetadataAsync(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, r.headers); + if (this.apiKey) { + opts.headers.set('X-Goog-Api-Key', this.apiKey); + } + return await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - An access_token and refresh_token were available, but either no + // expiry_date was available or the forceRefreshOnFailure flag is set. + // The absent expiry_date case can happen when developers stash the + // access_token and refresh_token for later use, but the access_token + // fails on the first try because it's expired. Some developers may + // choose to enable forceRefreshOnFailure to mitigate time-related + // errors. + // Or the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - No refresh_token was available + // - An access_token and a refreshHandler callback were available, but + // either no expiry_date was available or the forceRefreshOnFailure + // flag is set. The access_token fails on the first try because it's + // expired. Some developers may choose to enable forceRefreshOnFailure + // to mitigate time-related errors. + const mayRequireRefresh = this.credentials && + this.credentials.access_token && + this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure); + const mayRequireRefreshWithNoRefreshToken = this.credentials && + this.credentials.access_token && + !this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure) && + this.refreshHandler; + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefresh) { + await this.refreshAccessTokenAsync(); + return this.requestAsync(opts, true); + } + else if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefreshWithNoRefreshToken) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); + } + return this.requestAsync(opts, true); + } + } + throw e; + } + } + verifyIdToken(options, callback) { + // This function used to accept two arguments instead of an options object. + // Check the types to help users upgrade with less pain. + // This check can be removed after a 2.0 release. + if (callback && typeof callback !== 'function') { + throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); + } + if (callback) { + this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); + } + else { + return this.verifyIdTokenAsync(options); + } + } + async verifyIdTokenAsync(options) { + if (!options.idToken) { + throw new Error('The verifyIdToken method requires an ID Token'); + } + const response = await this.getFederatedSignonCertsAsync(); + const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); + return login; + } + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + async getTokenInfo(accessToken) { + const { data } = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + headers: { + 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8', + authorization: `Bearer ${accessToken}`, + }, + url: this.endpoints.tokenInfoUrl.toString(), + }); + const info = Object.assign({ + expiry_date: new Date().getTime() + data.expires_in * 1000, + scopes: data.scope.split(' '), + }, data); + delete info.expires_in; + delete info.scope; + return info; + } + getFederatedSignonCerts(callback) { + if (callback) { + this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); + } + else { + return this.getFederatedSignonCertsAsync(); + } + } + async getFederatedSignonCertsAsync() { + const nowTime = new Date().getTime(); + const format = (0, crypto_1.hasBrowserCrypto)() + ? CertificateFormat.JWK + : CertificateFormat.PEM; + if (this.certificateExpiry && + nowTime < this.certificateExpiry.getTime() && + this.certificateCacheFormat === format) { + return { certs: this.certificateCache, format }; + } + let res; + let url; + switch (format) { + case CertificateFormat.PEM: + url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); + break; + case CertificateFormat.JWK: + url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url, + }; + authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync'); + res = await this.transporter.request(opts); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + const cacheControl = res?.headers.get('cache-control'); + let cacheAge = -1; + if (cacheControl) { + const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups + ?.maxAge; + if (maxAge) { + // Cache results with max-age (in seconds) + cacheAge = Number(maxAge) * 1000; // milliseconds + } + } + let certificates = {}; + switch (format) { + case CertificateFormat.PEM: + certificates = res.data; + break; + case CertificateFormat.JWK: + for (const key of res.data.keys) { + certificates[key.kid] = key; + } + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + const now = new Date(); + this.certificateExpiry = + cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); + this.certificateCache = certificates; + this.certificateCacheFormat = format; + return { certs: certificates, format, res }; + } + getIapPublicKeys(callback) { + if (callback) { + this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); + } + else { + return this.getIapPublicKeysAsync(); + } + } + async getIapPublicKeysAsync() { + let res; + const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url, + }; + authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync'); + res = await this.transporter.request(opts); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + return { pubkeys: res.data, res }; + } + verifySignedJwtWithCerts() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); + } + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { + const crypto = (0, crypto_1.createCrypto)(); + if (!maxExpiry) { + maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + } + const segments = jwt.split('.'); + if (segments.length !== 3) { + throw new Error('Wrong number of segments in token: ' + jwt); + } + const signed = segments[0] + '.' + segments[1]; + let signature = segments[2]; + let envelope; + let payload; + try { + envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; + } + throw err; + } + if (!envelope) { + throw new Error("Can't parse token envelope: " + segments[0]); + } + try { + payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token payload '${segments[0]}`; + } + throw err; + } + if (!payload) { + throw new Error("Can't parse token payload: " + segments[1]); + } + if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { + // If this is not present, then there's no reason to attempt verification + throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); + } + const cert = certs[envelope.kid]; + if (envelope.alg === 'ES256') { + signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); + } + const verified = await crypto.verify(cert, signed, signature); + if (!verified) { + throw new Error('Invalid token signature: ' + jwt); + } + if (!payload.iat) { + throw new Error('No issue time in token: ' + JSON.stringify(payload)); + } + if (!payload.exp) { + throw new Error('No expiration time in token: ' + JSON.stringify(payload)); + } + const iat = Number(payload.iat); + if (isNaN(iat)) + throw new Error('iat field using invalid format'); + const exp = Number(payload.exp); + if (isNaN(exp)) + throw new Error('exp field using invalid format'); + const now = new Date().getTime() / 1000; + if (exp >= now + maxExpiry) { + throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); + } + const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; + const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; + if (now < earliest) { + throw new Error('Token used too early, ' + + now + + ' < ' + + earliest + + ': ' + + JSON.stringify(payload)); + } + if (now > latest) { + throw new Error('Token used too late, ' + + now + + ' > ' + + latest + + ': ' + + JSON.stringify(payload)); + } + if (issuers && issuers.indexOf(payload.iss) < 0) { + throw new Error('Invalid issuer, expected one of [' + + issuers + + '], but got ' + + payload.iss); + } + // Check the audience matches if we have one + if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { + const aud = payload.aud; + let audVerified = false; + // If the requiredAudience is an array, check if it contains token + // audience + if (requiredAudience.constructor === Array) { + audVerified = requiredAudience.indexOf(aud) > -1; + } + else { + audVerified = aud === requiredAudience; + } + if (!audVerified) { + throw new Error('Wrong recipient, payload audience != requiredAudience'); + } + } + return new loginticket_1.LoginTicket(envelope, payload); + } + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + async processAndValidateRefreshHandler() { + if (this.refreshHandler) { + const accessTokenResponse = await this.refreshHandler(); + if (!accessTokenResponse.access_token) { + throw new Error('No access token is returned by the refreshHandler callback.'); + } + return accessTokenResponse; + } + return; + } + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + isTokenExpiring() { + const expiryDate = this.credentials.expiry_date; + return expiryDate + ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis + : false; + } +} +exports.OAuth2Client = OAuth2Client; +//# sourceMappingURL=oauth2client.js.map + +/***/ }), + +/***/ 30069: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OAuthClientAuthHandler = void 0; +exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; +const gaxios_1 = __webpack_require__(10627); +const crypto_1 = __webpack_require__(6123); +/** List of HTTP methods that accept request bodies. */ +const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; +/** + * Abstract class for handling client authentication in OAuth-based + * operations. + * When request-body client authentication is used, only application/json and + * application/x-www-form-urlencoded content types for HTTP methods that support + * request bodies are supported. + */ +class OAuthClientAuthHandler { + #crypto = (0, crypto_1.createCrypto)(); + #clientAuthentication; + transporter; + /** + * Instantiates an OAuth client authentication handler. + * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**. + */ + constructor(options) { + if (options && 'clientId' in options) { + this.#clientAuthentication = options; + this.transporter = new gaxios_1.Gaxios(); + } + else { + this.#clientAuthentication = options?.clientAuthentication; + this.transporter = options?.transporter || new gaxios_1.Gaxios(); + } + } + /** + * Applies client authentication on the OAuth request's headers or POST + * body but does not process the request. + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + applyClientAuthenticationOptions(opts, bearerToken) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + // Inject authenticated header. + this.injectAuthenticatedHeaders(opts, bearerToken); + // Inject authenticated request body. + if (!bearerToken) { + this.injectAuthenticatedRequestBody(opts); + } + } + /** + * Applies client authentication on the request's header if either + * basic authentication or bearer token authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + injectAuthenticatedHeaders(opts, bearerToken) { + // Bearer token prioritized higher than basic Auth. + if (bearerToken) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, { + authorization: `Bearer ${bearerToken}`, + }); + } + else if (this.#clientAuthentication?.confidentialClientType === 'basic') { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + const clientId = this.#clientAuthentication.clientId; + const clientSecret = this.#clientAuthentication.clientSecret || ''; + const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); + gaxios_1.Gaxios.mergeHeaders(opts.headers, { + authorization: `Basic ${base64EncodedCreds}`, + }); + } + } + /** + * Applies client authentication on the request's body if request-body + * client authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + */ + injectAuthenticatedRequestBody(opts) { + if (this.#clientAuthentication?.confidentialClientType === 'request-body') { + const method = (opts.method || 'GET').toUpperCase(); + if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) { + throw new Error(`${method} HTTP method does not support ` + + `${this.#clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + // Get content-type + const headers = new Headers(opts.headers); + const contentType = headers.get('content-type'); + // Inject authenticated request body + if (contentType?.startsWith('application/x-www-form-urlencoded') || + opts.data instanceof URLSearchParams) { + const data = new URLSearchParams(opts.data ?? ''); + data.append('client_id', this.#clientAuthentication.clientId); + data.append('client_secret', this.#clientAuthentication.clientSecret || ''); + opts.data = data; + } + else if (contentType?.startsWith('application/json')) { + opts.data = opts.data || {}; + Object.assign(opts.data, { + client_id: this.#clientAuthentication.clientId, + client_secret: this.#clientAuthentication.clientSecret || '', + }); + } + else { + throw new Error(`${contentType} content-types are not supported with ` + + `${this.#clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + } + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.OAuthClientAuthHandler = OAuthClientAuthHandler; +/** + * Converts an OAuth error response to a native JavaScript Error. + * @param resp The OAuth error response to convert to a native Error object. + * @param err The optional original error. If provided, the error properties + * will be copied to the new error. + * @return The converted native Error object. + */ +function getErrorFromOAuthErrorResponse(resp, err) { + // Error response. + const errorCode = resp.error; + const errorDescription = resp.error_description; + const errorUri = resp.error_uri; + let message = `Error code ${errorCode}`; + if (typeof errorDescription !== 'undefined') { + message += `: ${errorDescription}`; + } + if (typeof errorUri !== 'undefined') { + message += ` - ${errorUri}`; + } + const newError = new Error(message); + // Copy properties from original error to newly generated error. + if (err) { + const keys = Object.keys(err); + if (err.stack) { + // Copy error.stack if available. + keys.push('stack'); + } + keys.forEach(key => { + // Do not overwrite the message field. + if (key !== 'message') { + Object.defineProperty(newError, key, { + value: err[key], + writable: false, + enumerable: true, + }); + } + }); + } + return newError; +} +//# sourceMappingURL=oauth2common.js.map + +/***/ }), + +/***/ 54949: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2024 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PassThroughClient = void 0; +const authclient_1 = __webpack_require__(82594); +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +class PassThroughClient extends authclient_1.AuthClient { + /** + * Creates a request without any authentication headers or checks. + * + * @remarks + * + * In testing environments it may be useful to change the provided + * {@link AuthClient.transporter} for any desired request overrides/handling. + * + * @param opts + * @returns The response of the request. + */ + async request(opts) { + return this.transporter.request(opts); + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getAccessToken() { + return {}; + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getRequestHeaders() { + return new Headers(); + } +} +exports.PassThroughClient = PassThroughClient; +//# sourceMappingURL=passthrough.js.map + +/***/ }), + +/***/ 35189: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2022 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PluggableAuthClient = exports.ExecutableError = void 0; +const baseexternalclient_1 = __webpack_require__(89046); +const executable_response_1 = __webpack_require__(69079); +const pluggable_auth_handler_1 = __webpack_require__(80212); +var pluggable_auth_handler_2 = __webpack_require__(80212); +Object.defineProperty(exports, "ExecutableError", ({ enumerable: true, get: function () { return pluggable_auth_handler_2.ExecutableError; } })); +/** + * The default executable timeout when none is provided, in milliseconds. + */ +const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; +/** + * The minimum allowed executable timeout in milliseconds. + */ +const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; +/** + * The maximum allowed executable timeout in milliseconds. + */ +const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; +/** + * The environment variable to check to see if executable can be run. + * Value must be set to '1' for the executable to run. + */ +const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES'; +/** + * The maximum currently supported executable version. + */ +const MAXIMUM_EXECUTABLE_VERSION = 1; +/** + * PluggableAuthClient enables the exchange of workload identity pool external credentials for + * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These + * scripts/executables are completely independent of the Google Cloud Auth libraries. These + * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token + * to be exchanged for a Google access token. + * + *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable + * must be set to '1'. This is for security reasons. + * + *

Both OIDC and SAML are supported. The executable must adhere to a specific response format + * defined below. + * + *

The executable must print out the 3rd party token to STDOUT in JSON format. When an + * output_file is specified in the credential configuration, the executable must also handle writing the + * JSON response to this file. + * + *

+ * OIDC response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:id_token",
+ *   "id_token": "HEADER.PAYLOAD.SIGNATURE",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * SAML2 response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:saml2",
+ *   "saml_response": "...",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * Error response sample:
+ * {
+ *   "version": 1,
+ *   "success": false,
+ *   "code": "401",
+ *   "message": "Error message."
+ * }
+ * 
+ * + *

The "expiration_time" field in the JSON response is only required for successful + * responses when an output file was specified in the credential configuration + * + *

The auth libraries will populate certain environment variables that will be accessible by the + * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, + * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and + * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE. + * + *

Please see this repositories README for a complete executable request/response specification. + */ +class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * The command used to retrieve the third party token. + */ + command; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis; + /** + * The path to file to check for cached executable response. + */ + outputFile; + /** + * Executable and output file handler. + */ + handler; + /** + * Instantiates a PluggableAuthClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid pluggable auth credential. + * @param options The external account options object typically loaded from + * the external account JSON credential file. + */ + constructor(options) { + super(options); + if (!options.credential_source.executable) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + this.command = options.credential_source.executable.command; + if (!this.command) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + // Check if the provided timeout exists and if it is valid. + if (options.credential_source.executable.timeout_millis === undefined) { + this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; + } + else { + this.timeoutMillis = options.credential_source.executable.timeout_millis; + if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || + this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { + throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); + } + } + this.outputFile = options.credential_source.executable.output_file; + this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ + command: this.command, + timeoutMillis: this.timeoutMillis, + outputFile: this.outputFile, + }); + this.credentialSourceType = 'executable'; + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. + * This uses the `options.credential_source` object to figure out how + * to retrieve the token using the current environment. In this case, + * this calls a user provided executable which returns the subject token. + * The logic is summarized as: + * 1. Validated that the executable is allowed to run. The + * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to + * 1 for security reasons. + * 2. If an output file is specified by the user, check the file location + * for a response. If the file exists and contains a valid response, + * return the subject token from the file. + * 3. Call the provided executable and return response. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Check if the executable is allowed to run. + if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') { + throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' + + 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' + + 'Variable to 1.'); + } + let executableResponse = undefined; + // Try to get cached executable response from output file. + if (this.outputFile) { + executableResponse = await this.handler.retrieveCachedResponse(); + } + // If no response from output file, call the executable. + if (!executableResponse) { + // Set up environment map with required values for the executable. + const envMap = new Map(); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType); + // Always set to 0 because interactive mode is not supported. + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0'); + if (this.outputFile) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile); + } + const serviceAccountEmail = this.getServiceAccountEmail(); + if (serviceAccountEmail) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail); + } + executableResponse = + await this.handler.retrieveResponseFromExecutable(envMap); + } + if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { + throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); + } + // Check that response was successful. + if (!executableResponse.success) { + throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); + } + // Check that response contains expiration time if output file was specified. + if (this.outputFile) { + if (!executableResponse.expirationTime) { + throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.'); + } + } + // Check that response is not expired. + if (executableResponse.isExpired()) { + throw new Error('Executable response is expired.'); + } + // Return subject token from response. + return executableResponse.subjectToken; + } +} +exports.PluggableAuthClient = PluggableAuthClient; +//# sourceMappingURL=pluggable-auth-client.js.map + +/***/ }), + +/***/ 80212: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2022 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PluggableAuthHandler = exports.ExecutableError = void 0; +const executable_response_1 = __webpack_require__(69079); +const childProcess = __webpack_require__(35317); +const fs = __webpack_require__(79896); +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +class ExecutableError extends Error { + /** + * The exit code returned by the executable. + */ + code; + constructor(message, code) { + super(`The executable failed with exit code: ${code} and error message: ${message}.`); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableError = ExecutableError; +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +class PluggableAuthHandler { + commandComponents; + timeoutMillis; + outputFile; + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options) { + if (!options.command) { + throw new Error('No command provided.'); + } + this.commandComponents = PluggableAuthHandler.parseCommand(options.command); + this.timeoutMillis = options.timeoutMillis; + if (!this.timeoutMillis) { + throw new Error('No timeoutMillis provided.'); + } + this.outputFile = options.outputFile; + } + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap) { + return new Promise((resolve, reject) => { + // Spawn process to run executable using added environment variables. + const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { + env: { ...process.env, ...Object.fromEntries(envMap) }, + }); + let output = ''; + // Append stdout to output as executable runs. + child.stdout.on('data', (data) => { + output += data; + }); + // Append stderr as executable runs. + child.stderr.on('data', (err) => { + output += err; + }); + // Set up a timeout to end the child process and throw an error. + const timeout = setTimeout(() => { + // Kill child process and remove listeners so 'close' event doesn't get + // read after child process is killed. + child.removeAllListeners(); + child.kill(); + return reject(new Error('The executable failed to finish within the timeout specified.')); + }, this.timeoutMillis); + child.on('close', (code) => { + // Cancel timeout if executable closes before timeout is reached. + clearTimeout(timeout); + if (code === 0) { + // If the executable completed successfully, try to return the parsed response. + try { + const responseJson = JSON.parse(output); + const response = new executable_response_1.ExecutableResponse(responseJson); + return resolve(response); + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + return reject(error); + } + return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); + } + } + else { + return reject(new ExecutableError(output, code.toString())); + } + }); + }); + } + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + async retrieveCachedResponse() { + if (!this.outputFile || this.outputFile.length === 0) { + return undefined; + } + let filePath; + try { + filePath = await fs.promises.realpath(this.outputFile); + } + catch { + // If file path cannot be resolved, return undefined. + return undefined; + } + if (!(await fs.promises.lstat(filePath)).isFile()) { + // If path does not lead to file, return undefined. + return undefined; + } + const responseString = await fs.promises.readFile(filePath, { + encoding: 'utf8', + }); + if (responseString === '') { + return undefined; + } + try { + const responseJson = JSON.parse(responseString); + const response = new executable_response_1.ExecutableResponse(responseJson); + // Check if response is successful and unexpired. + if (response.isValid()) { + return new executable_response_1.ExecutableResponse(responseJson); + } + return undefined; + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + throw error; + } + throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); + } + } + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + static parseCommand(command) { + // Split the command into components by splitting on spaces, + // unless spaces are contained in quotation marks. + const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); + if (!components) { + throw new Error(`Provided command: "${command}" could not be parsed.`); + } + // Remove quotation marks from the beginning and end of each component if they are present. + for (let i = 0; i < components.length; i++) { + if (components[i][0] === '"' && components[i].slice(-1) === '"') { + components[i] = components[i].slice(1, -1); + } + } + return components; + } +} +exports.PluggableAuthHandler = PluggableAuthHandler; +//# sourceMappingURL=pluggable-auth-handler.js.map + +/***/ }), + +/***/ 16983: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2015 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0; +const oauth2client_1 = __webpack_require__(64739); +const authclient_1 = __webpack_require__(82594); +exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; +class UserRefreshClient extends oauth2client_1.OAuth2Client { + // TODO: refactor tests to make this private + // In a future gts release, the _propertyName rule will be lifted. + // This is also a hard one because `this.refreshToken` is a function. + _refreshToken; + /** + * The User Refresh Token client. + * + * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + */ + constructor(optionsOrClientId, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + clientSecret, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + refreshToken, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + eagerRefreshThresholdMillis, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + forceRefreshOnFailure) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { + clientId: optionsOrClientId, + clientSecret, + refreshToken, + eagerRefreshThresholdMillis, + forceRefreshOnFailure, + }; + super(opts); + this._refreshToken = opts.refreshToken; + this.credentials.refresh_token = opts.refreshToken; + } + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + async refreshTokenNoCache() { + return super.refreshTokenNoCache(this._refreshToken); + } + async fetchIdToken(targetAudience) { + const opts = { + ...UserRefreshClient.RETRY_CONFIG, + url: this.endpoints.oauth2TokenUrl, + method: 'POST', + data: new URLSearchParams({ + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + refresh_token: this._refreshToken, + target_audience: targetAudience, + }), + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken'); + const res = await this.transporter.request(opts); + return res.data.id_token; + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the user refresh token'); + } + if (json.type !== 'authorized_user') { + throw new Error('The incoming JSON object does not have the "authorized_user" type'); + } + if (!json.client_id) { + throw new Error('The incoming JSON object does not contain a client_id field'); + } + if (!json.client_secret) { + throw new Error('The incoming JSON object does not contain a client_secret field'); + } + if (!json.refresh_token) { + throw new Error('The incoming JSON object does not contain a refresh_token field'); + } + this._clientId = json.client_id; + this._clientSecret = json.client_secret; + this._refreshToken = json.refresh_token; + this.credentials.refresh_token = json.refresh_token; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + async fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + return reject(new Error('Must pass in a stream containing the user refresh token.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + return resolve(); + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json) { + const client = new UserRefreshClient(); + client.fromJSON(json); + return client; + } +} +exports.UserRefreshClient = UserRefreshClient; +//# sourceMappingURL=refreshclient.js.map + +/***/ }), + +/***/ 51537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2021 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StsCredentials = void 0; +const gaxios_1 = __webpack_require__(10627); +const authclient_1 = __webpack_require__(82594); +const oauth2common_1 = __webpack_require__(30069); +const util_1 = __webpack_require__(84358); +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { + #tokenExchangeEndpoint; + /** + * Initializes an STS credentials instance. + * + * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**. + * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead. + */ + constructor(options = { + tokenExchangeEndpoint: '', + }, + /** + * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead + */ + clientAuthentication) { + if (typeof options !== 'object' || options instanceof URL) { + options = { + tokenExchangeEndpoint: options, + clientAuthentication, + }; + } + super(options); + this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint; + } + /** + * Exchanges the provided token for another type of token based on the + * rfc8693 spec. + * @param stsCredentialsOptions The token exchange options used to populate + * the token exchange request. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @param options Optional additional GCP-specific non-spec defined options + * to send with the request. + * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` + * @return A promise that resolves with the token exchange response containing + * the requested token and its expiration time. + */ + async exchangeToken(stsCredentialsOptions, headers, options) { + const values = { + grant_type: stsCredentialsOptions.grantType, + resource: stsCredentialsOptions.resource, + audience: stsCredentialsOptions.audience, + scope: stsCredentialsOptions.scope?.join(' '), + requested_token_type: stsCredentialsOptions.requestedTokenType, + subject_token: stsCredentialsOptions.subjectToken, + subject_token_type: stsCredentialsOptions.subjectTokenType, + actor_token: stsCredentialsOptions.actingParty?.actorToken, + actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType, + // Non-standard GCP-specific options. + options: options && JSON.stringify(options), + }; + const opts = { + ...StsCredentials.RETRY_CONFIG, + url: this.#tokenExchangeEndpoint.toString(), + method: 'POST', + headers, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), + responseType: 'json', + }; + authclient_1.AuthClient.setMethodName(opts, 'exchangeToken'); + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const stsSuccessfulResponse = response.data; + stsSuccessfulResponse.res = response; + return stsSuccessfulResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +exports.StsCredentials = StsCredentials; +//# sourceMappingURL=stscredentials.js.map + +/***/ }), + +/***/ 44571: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2024 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UrlSubjectTokenSupplier = void 0; +const authclient_1 = __webpack_require__(82594); +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class UrlSubjectTokenSupplier { + url; + headers; + formatType; + subjectTokenFieldName; + additionalGaxiosOptions; + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts) { + this.url = opts.url; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + this.headers = opts.headers; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Sends a GET request to the URL provided in the constructor and resolves + * with the returned external subject token. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.url, + method: 'GET', + headers: this.headers, + responseType: this.formatType, + }; + authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken'); + let subjectToken; + if (this.formatType === 'text') { + const response = await context.transporter.request(opts); + subjectToken = response.data; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const response = await context.transporter.request(opts); + subjectToken = response.data[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source URL'); + } + return subjectToken; + } +} +exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; +//# sourceMappingURL=urlsubjecttokensupplier.js.map + +/***/ }), + +/***/ 72278: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2019 Google LLC +// +// 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. +/* global window */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BrowserCrypto = void 0; +// This file implements crypto functions we need using in-browser +// SubtleCrypto interface `window.crypto.subtle`. +const base64js = __webpack_require__(29872); +const shared_1 = __webpack_require__(61927); +class BrowserCrypto { + constructor() { + if (typeof window === 'undefined' || + window.crypto === undefined || + window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } + } + async sha256DigestBase64(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); + } + randomBytesBase64(count) { + const array = new Uint8Array(count); + window.crypto.getRandomValues(array); + return base64js.fromByteArray(array); + } + static padBase64(base64) { + // base64js requires padding, so let's add some '=' + while (base64.length % 4 !== 0) { + base64 += '='; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); + // SubtleCrypto's verify method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.verify(algo, cryptoKey, Buffer.from(signatureArray), dataArray); + return result; + } + async sign(privateKey, data) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); + // SubtleCrypto's sign method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); + } + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text) { + const uint8array = new TextEncoder().encode(text); + const result = base64js.fromByteArray(uint8array); + return result; + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return (0, shared_1.fromArrayBufferToHex)(outputBuffer); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + // Convert key, if provided in ArrayBuffer format, to string. + const rawKey = typeof key === 'string' + ? key + : String.fromCharCode(...new Uint16Array(key)); + const enc = new TextEncoder(); + const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { + name: 'HMAC', + hash: { + name: 'SHA-256', + }, + }, false, ['sign']); + return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); + } +} +exports.BrowserCrypto = BrowserCrypto; +//# sourceMappingURL=crypto.js.map + +/***/ }), + +/***/ 6123: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2019 Google LLC +// +// 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. +/* global window */ +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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createCrypto = createCrypto; +exports.hasBrowserCrypto = hasBrowserCrypto; +const crypto_1 = __webpack_require__(72278); +const crypto_2 = __webpack_require__(89396); +__exportStar(__webpack_require__(61927), exports); +// Crypto interface will provide required crypto functions. +// Use `createCrypto()` factory function to create an instance +// of Crypto. It will either use Node.js `crypto` module, or +// use browser's SubtleCrypto interface. Since most of the +// SubtleCrypto methods return promises, we must make those +// methods return promises here as well, even though in Node.js +// they are synchronous. +function createCrypto() { + if (hasBrowserCrypto()) { + return new crypto_1.BrowserCrypto(); + } + return new crypto_2.NodeCrypto(); +} +function hasBrowserCrypto() { + return (typeof window !== 'undefined' && + typeof window.crypto !== 'undefined' && + typeof window.crypto.subtle !== 'undefined'); +} +//# sourceMappingURL=crypto.js.map + +/***/ }), + +/***/ 89396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2019 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NodeCrypto = void 0; +const crypto = __webpack_require__(76982); +class NodeCrypto { + async sha256DigestBase64(str) { + return crypto.createHash('sha256').update(str).digest('base64'); + } + randomBytesBase64(count) { + return crypto.randomBytes(count).toString('base64'); + } + async verify(pubkey, data, signature) { + const verifier = crypto.createVerify('RSA-SHA256'); + verifier.update(data); + verifier.end(); + return verifier.verify(pubkey, signature, 'base64'); + } + async sign(privateKey, data) { + const signer = crypto.createSign('RSA-SHA256'); + signer.update(data); + signer.end(); + return signer.sign(privateKey, 'base64'); + } + decodeBase64StringUtf8(base64) { + return Buffer.from(base64, 'base64').toString('utf-8'); + } + encodeBase64StringUtf8(text) { + return Buffer.from(text, 'utf-8').toString('base64'); + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + return crypto.createHash('sha256').update(str).digest('hex'); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + const cryptoKey = typeof key === 'string' ? key : toBuffer(key); + return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); + } +} +exports.NodeCrypto = NodeCrypto; +/** + * Converts a Node.js Buffer to an ArrayBuffer. + * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer + * @param buffer The Buffer input to covert. + * @return The ArrayBuffer representation of the input. + */ +function toArrayBuffer(buffer) { + const ab = new ArrayBuffer(buffer.length); + const view = new Uint8Array(ab); + for (let i = 0; i < buffer.length; ++i) { + view[i] = buffer[i]; + } + return ab; +} +/** + * Converts an ArrayBuffer to a Node.js Buffer. + * @param arrayBuffer The ArrayBuffer input to covert. + * @return The Buffer representation of the input. + */ +function toBuffer(arrayBuffer) { + return Buffer.from(arrayBuffer); +} +//# sourceMappingURL=crypto.js.map + +/***/ }), + +/***/ 61927: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromArrayBufferToHex = fromArrayBufferToHex; +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +function fromArrayBufferToHex(arrayBuffer) { + // Convert buffer to byte array. + const byteArray = Array.from(new Uint8Array(arrayBuffer)); + // Convert bytes to hex string. + return byteArray + .map(byte => { + return byte.toString(16).padStart(2, '0'); + }) + .join(''); +} +//# sourceMappingURL=shared.js.map + +/***/ }), + +/***/ 12876: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ErrorWithCode = void 0; +class ErrorWithCode extends Error { + code; + constructor(message, code) { + super(message); + this.code = code; + } +} +exports.ErrorWithCode = ErrorWithCode; +//# sourceMappingURL=errorWithCode.js.map + +/***/ }), + +/***/ 22629: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCredentials = getCredentials; +const path = __webpack_require__(16928); +const fs = __webpack_require__(79896); +const util_1 = __webpack_require__(39023); +const errorWithCode_1 = __webpack_require__(12876); +const readFile = fs.readFile + ? (0, util_1.promisify)(fs.readFile) + : async () => { + // if running in the web-browser, fs.readFile may not have been shimmed. + throw new errorWithCode_1.ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); + }; +var ExtensionFiles; +(function (ExtensionFiles) { + ExtensionFiles["JSON"] = ".json"; + ExtensionFiles["DER"] = ".der"; + ExtensionFiles["CRT"] = ".crt"; + ExtensionFiles["PEM"] = ".pem"; + ExtensionFiles["P12"] = ".p12"; + ExtensionFiles["PFX"] = ".pfx"; +})(ExtensionFiles || (ExtensionFiles = {})); +/** + * Provides credentials from a JSON key file. + */ +class JsonCredentialsProvider { + keyFilePath; + constructor(keyFilePath) { + this.keyFilePath = keyFilePath; + } + /** + * Reads a JSON key file and extracts the private key and client email. + * @returns A promise that resolves with the credentials. + */ + async getCredentials() { + const key = await readFile(this.keyFilePath, 'utf8'); + let body; + try { + body = JSON.parse(key); + } + catch (error) { + const err = error; + throw new Error(`Invalid JSON key file: ${err.message}`); + } + const privateKey = body.private_key; + const clientEmail = body.client_email; + if (!privateKey || !clientEmail) { + throw new errorWithCode_1.ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); + } + return { privateKey, clientEmail }; + } +} +/** + * Provides credentials from a PEM-like key file. + */ +class PemCredentialsProvider { + keyFilePath; + constructor(keyFilePath) { + this.keyFilePath = keyFilePath; + } + /** + * Reads a PEM-like key file. + * @returns A promise that resolves with the private key. + */ + async getCredentials() { + const privateKey = await readFile(this.keyFilePath, 'utf8'); + return { privateKey }; + } +} +/** + * Handles unsupported P12/PFX certificate types. + */ +class P12CredentialsProvider { + /** + * Throws an error as P12/PFX certificates are not supported. + * @returns A promise that rejects with an error. + */ + async getCredentials() { + throw new errorWithCode_1.ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE'); + } +} +/** + * Factory class to create the appropriate credentials provider. + */ +class CredentialsProviderFactory { + /** + * Creates a credential provider based on the key file extension. + * @param keyFilePath The path to the key file. + * @returns An instance of a class that implements ICredentialsProvider. + */ + static create(keyFilePath) { + const keyFileExtension = path.extname(keyFilePath); + switch (keyFileExtension) { + case ExtensionFiles.JSON: + return new JsonCredentialsProvider(keyFilePath); + case ExtensionFiles.DER: + case ExtensionFiles.CRT: + case ExtensionFiles.PEM: + return new PemCredentialsProvider(keyFilePath); + case ExtensionFiles.P12: + case ExtensionFiles.PFX: + return new P12CredentialsProvider(); + default: + throw new errorWithCode_1.ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + } +} +/** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ +async function getCredentials(keyFilePath) { + const provider = CredentialsProviderFactory.create(keyFilePath); + return provider.getCredentials(); +} +//# sourceMappingURL=getCredentials.js.map + +/***/ }), + +/***/ 66122: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getToken = getToken; +const jwsSign_1 = __webpack_require__(47970); +/** The URL for Google's OAuth 2.0 token endpoint. */ +const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'; +/** The grant type for JWT-based authorization. */ +const GOOGLE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; +/** + * Generates the request options for fetching a token. + * @param tokenOptions The options for the token. + * @returns The Gaxios options for the request. + */ +const generateRequestOptions = (tokenOptions) => { + return { + method: 'POST', + url: GOOGLE_TOKEN_URL, + data: new URLSearchParams({ + grant_type: GOOGLE_GRANT_TYPE, // Grant type for JWT + assertion: (0, jwsSign_1.getJwsSign)(tokenOptions), + }), + responseType: 'json', + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }; +}; +/** + * Fetches an access token. + * @param tokenOptions The options for the token. + * @returns A promise that resolves with the token data. + */ +async function getToken(tokenOptions) { + if (!tokenOptions.transporter) { + throw new Error('No transporter set.'); + } + try { + const gaxiosOptions = generateRequestOptions(tokenOptions); + const response = await tokenOptions.transporter.request(gaxiosOptions); + return response.data; + } + catch (e) { + // The error is re-thrown, but we want to format it to be more + // informative. + const err = e; + const errorData = err.response?.data; + if (errorData?.error) { + err.message = `${errorData.error}: ${errorData.error_description}`; + } + throw err; + } +} +//# sourceMappingURL=getToken.js.map + +/***/ }), + +/***/ 20451: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GoogleToken = void 0; +const gaxios_1 = __webpack_require__(10627); +const tokenHandler_1 = __webpack_require__(16840); +const revokeToken_1 = __webpack_require__(40464); +/** + * The GoogleToken class is used to manage authentication with Google's OAuth 2.0 authorization server. + * It handles fetching, caching, and refreshing of access tokens. + */ +class GoogleToken { + /** The configuration options for this token instance. */ + tokenOptions; + /** The handler for token fetching and caching logic. */ + tokenHandler; + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options) { + this.tokenOptions = options || {}; + // If a transporter is not set, by default set it to use gaxios. + this.tokenOptions.transporter = this.tokenOptions.transporter || { + request: opts => (0, gaxios_1.request)(opts), + }; + if (!this.tokenOptions.iss) { + this.tokenOptions.iss = this.tokenOptions.email; + } + if (typeof this.tokenOptions.scope === 'object') { + this.tokenOptions.scope = this.tokenOptions.scope.join(' '); + } + this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); + } + get expiresAt() { + return this.tokenHandler.tokenExpiresAt; + } + /** + * The most recent access token obtained by this client. + */ + get accessToken() { + return this.tokenHandler.token?.access_token; + } + /** + * The most recent ID token obtained by this client. + */ + get idToken() { + return this.tokenHandler.token?.id_token; + } + /** + * The token type of the most recent access token. + */ + get tokenType() { + return this.tokenHandler.token?.token_type; + } + /** + * The refresh token for the current credentials. + */ + get refreshToken() { + return this.tokenHandler.token?.refresh_token; + } + /** + * A boolean indicating if the current token has expired. + */ + hasExpired() { + return this.tokenHandler.hasExpired(); + } + /** + * A boolean indicating if the current token is expiring soon, + * based on the `eagerRefreshThresholdMillis` option. + */ + isTokenExpiring() { + return this.tokenHandler.isTokenExpiring(); + } + getToken(callbackOrOptions, opts = { forceRefresh: false }) { + // Handle the various method overloads. + let callback; + if (typeof callbackOrOptions === 'function') { + callback = callbackOrOptions; + } + else if (typeof callbackOrOptions === 'object') { + opts = callbackOrOptions; + } + // Delegate the token fetching to the token handler. + const promise = this.tokenHandler.getToken(opts.forceRefresh ?? false); + // If a callback is provided, use it, otherwise return the promise. + if (callback) { + promise.then(token => callback(null, token), callback); + } + return promise; + } + revokeToken(callback) { + if (!this.accessToken) { + return Promise.reject(new Error('No token to revoke.')); + } + const promise = (0, revokeToken_1.revokeToken)(this.accessToken, this.tokenOptions.transporter); + // If a callback is provided, use it. + if (callback) { + promise.then(() => callback(), callback); + } + // After revoking, reset the token handler to clear the cached token. + this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); + } + /** + * Returns the configuration options for this token instance. + */ + get googleTokenOptions() { + return this.tokenOptions; + } +} +exports.GoogleToken = GoogleToken; +//# sourceMappingURL=googleToken.js.map + +/***/ }), + +/***/ 47970: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.buildPayloadForJwsSign = buildPayloadForJwsSign; +exports.getJwsSign = getJwsSign; +const jws_1 = __webpack_require__(16798); +/** The default algorithm for signing JWTs. */ +const ALG_RS256 = 'RS256'; +/** The URL for Google's OAuth 2.0 token endpoint. */ +const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'; +/** + * Builds the JWT payload for signing. + * @param tokenOptions The options for the token. + * @returns The JWT payload. + */ +function buildPayloadForJwsSign(tokenOptions) { + const iat = Math.floor(new Date().getTime() / 1000); + const payload = { + iss: tokenOptions.iss, + scope: tokenOptions.scope, + aud: GOOGLE_TOKEN_URL, + exp: iat + 3600, + iat, + sub: tokenOptions.sub, + ...tokenOptions.additionalClaims, + }; + return payload; +} +/** + * Creates a signed JWS (JSON Web Signature). + * @param tokenOptions The options for the token. + * @returns The signed JWS. + */ +function getJwsSign(tokenOptions) { + const payload = buildPayloadForJwsSign(tokenOptions); + return (0, jws_1.sign)({ + header: { alg: ALG_RS256 }, + payload, + secret: tokenOptions.key, + }); +} +//# sourceMappingURL=jwsSign.js.map + +/***/ }), + +/***/ 40464: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2025 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.revokeToken = revokeToken; +/** The URL for Google's OAuth 2.0 token revocation endpoint. */ +const GOOGLE_REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke?token='; +/** The default retry behavior for the revoke token request. */ +const DEFAULT_RETRY_VALUE = true; +/** + * Revokes a given access token. + * @param accessToken The access token to revoke. + * @param transporter The transporter to make the request with. + * @returns A promise that resolves with the revocation response. + */ +async function revokeToken(accessToken, transporter) { + const url = GOOGLE_REVOKE_TOKEN_URL + accessToken; + return await transporter.request({ + url, + retry: DEFAULT_RETRY_VALUE, + }); +} +//# sourceMappingURL=revokeToken.js.map + +/***/ }), + +/***/ 16840: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TokenHandler = void 0; +const getToken_1 = __webpack_require__(66122); +const getCredentials_1 = __webpack_require__(22629); +/** + * Manages the fetching and caching of access tokens. + */ +class TokenHandler { + /** The cached access token. */ + token; + /** The expiration time of the cached access token. */ + tokenExpiresAt; + /** A promise for an in-flight token request. */ + inFlightRequest; + tokenOptions; + /** + * Creates an instance of TokenHandler. + * @param tokenOptions The options for fetching tokens. + * @param transporter The transporter to use for making requests. + */ + constructor(tokenOptions) { + this.tokenOptions = tokenOptions; + } + /** + * Processes the credentials, loading them from a key file if necessary. + * This method is called before any token request. + */ + async processCredentials() { + if (!this.tokenOptions.key && !this.tokenOptions.keyFile) { + throw new Error('No key or keyFile set.'); + } + if (!this.tokenOptions.key && this.tokenOptions.keyFile) { + const credentials = await (0, getCredentials_1.getCredentials)(this.tokenOptions.keyFile); + this.tokenOptions.key = credentials.privateKey; + this.tokenOptions.email = credentials.clientEmail; + } + } + /** + * Checks if the cached token is expired or close to expiring. + * @returns True if the token is expiring, false otherwise. + */ + isTokenExpiring() { + if (!this.token || !this.tokenExpiresAt) { + return true; + } + const now = new Date().getTime(); + const eagerRefreshThresholdMillis = this.tokenOptions.eagerRefreshThresholdMillis ?? 0; + return this.tokenExpiresAt <= now + eagerRefreshThresholdMillis; + } + /** + * Returns whether the token has completely expired. + * + * @returns true if the token has expired, false otherwise. + */ + hasExpired() { + const now = new Date().getTime(); + if (this.token && this.tokenExpiresAt) { + const now = new Date().getTime(); + return now >= this.tokenExpiresAt; + } + return true; + } + /** + * Fetches an access token, using a cached one if available and not expired. + * @param forceRefresh If true, forces a new token to be fetched. + * @returns A promise that resolves with the token data. + */ + async getToken(forceRefresh) { + // Ensure credentials are processed before proceeding. + await this.processCredentials(); + // If there's an in-flight request, return it. + if (this.inFlightRequest && !forceRefresh) { + return this.inFlightRequest; + } + // If we have a valid, non-expiring token, return it. + if (this.token && !this.isTokenExpiring() && !forceRefresh) { + return this.token; + } + // Otherwise, fetch a new token. + try { + this.inFlightRequest = (0, getToken_1.getToken)(this.tokenOptions); + const token = await this.inFlightRequest; + // Cache the new token and its expiration time. + this.token = token; + this.tokenExpiresAt = + new Date().getTime() + (token.expires_in ?? 0) * 1000; + return token; + } + finally { + // Clear the in-flight request promise once it's settled. + this.inFlightRequest = undefined; + } + } +} +exports.TokenHandler = TokenHandler; +//# sourceMappingURL=tokenHandler.js.map + +/***/ }), + +/***/ 17220: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GoogleAuth = exports.auth = exports.GDCH_SERVICE_ACCOUNT_TYPE = exports.GdchClient = exports.PassThroughClient = exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0; +// Copyright 2017 Google LLC +// +// 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. +const googleauth_1 = __webpack_require__(2662); +Object.defineProperty(exports, "GoogleAuth", ({ enumerable: true, get: function () { return googleauth_1.GoogleAuth; } })); +// Export common deps to ensure types/instances are the exact match. Useful +// for consistently configuring the library across versions. +exports.gcpMetadata = __webpack_require__(4381); +exports.gaxios = __webpack_require__(10627); +var authclient_1 = __webpack_require__(82594); +Object.defineProperty(exports, "AuthClient", ({ enumerable: true, get: function () { return authclient_1.AuthClient; } })); +Object.defineProperty(exports, "DEFAULT_UNIVERSE", ({ enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } })); +var computeclient_1 = __webpack_require__(81945); +Object.defineProperty(exports, "Compute", ({ enumerable: true, get: function () { return computeclient_1.Compute; } })); +var envDetect_1 = __webpack_require__(40747); +Object.defineProperty(exports, "GCPEnv", ({ enumerable: true, get: function () { return envDetect_1.GCPEnv; } })); +var iam_1 = __webpack_require__(30310); +Object.defineProperty(exports, "IAMAuth", ({ enumerable: true, get: function () { return iam_1.IAMAuth; } })); +var idtokenclient_1 = __webpack_require__(20630); +Object.defineProperty(exports, "IdTokenClient", ({ enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } })); +var jwtaccess_1 = __webpack_require__(15900); +Object.defineProperty(exports, "JWTAccess", ({ enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } })); +var jwtclient_1 = __webpack_require__(27397); +Object.defineProperty(exports, "JWT", ({ enumerable: true, get: function () { return jwtclient_1.JWT; } })); +var impersonated_1 = __webpack_require__(19588); +Object.defineProperty(exports, "Impersonated", ({ enumerable: true, get: function () { return impersonated_1.Impersonated; } })); +var oauth2client_1 = __webpack_require__(64739); +Object.defineProperty(exports, "CodeChallengeMethod", ({ enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } })); +Object.defineProperty(exports, "OAuth2Client", ({ enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } })); +Object.defineProperty(exports, "ClientAuthentication", ({ enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } })); +var loginticket_1 = __webpack_require__(27186); +Object.defineProperty(exports, "LoginTicket", ({ enumerable: true, get: function () { return loginticket_1.LoginTicket; } })); +var refreshclient_1 = __webpack_require__(16983); +Object.defineProperty(exports, "UserRefreshClient", ({ enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } })); +var awsclient_1 = __webpack_require__(25845); +Object.defineProperty(exports, "AwsClient", ({ enumerable: true, get: function () { return awsclient_1.AwsClient; } })); +var awsrequestsigner_1 = __webpack_require__(84199); +Object.defineProperty(exports, "AwsRequestSigner", ({ enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } })); +var identitypoolclient_1 = __webpack_require__(14032); +Object.defineProperty(exports, "IdentityPoolClient", ({ enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } })); +var externalclient_1 = __webpack_require__(28939); +Object.defineProperty(exports, "ExternalAccountClient", ({ enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } })); +var baseexternalclient_1 = __webpack_require__(89046); +Object.defineProperty(exports, "BaseExternalAccountClient", ({ enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } })); +var downscopedclient_1 = __webpack_require__(44412); +Object.defineProperty(exports, "DownscopedClient", ({ enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } })); +var pluggable_auth_client_1 = __webpack_require__(35189); +Object.defineProperty(exports, "PluggableAuthClient", ({ enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } })); +Object.defineProperty(exports, "ExecutableError", ({ enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } })); +var externalAccountAuthorizedUserClient_1 = __webpack_require__(69112); +Object.defineProperty(exports, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", ({ enumerable: true, get: function () { return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; } })); +Object.defineProperty(exports, "ExternalAccountAuthorizedUserClient", ({ enumerable: true, get: function () { return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient; } })); +var passthrough_1 = __webpack_require__(54949); +Object.defineProperty(exports, "PassThroughClient", ({ enumerable: true, get: function () { return passthrough_1.PassThroughClient; } })); +var gdchclient_1 = __webpack_require__(56568); +Object.defineProperty(exports, "GdchClient", ({ enumerable: true, get: function () { return gdchclient_1.GdchClient; } })); +Object.defineProperty(exports, "GDCH_SERVICE_ACCOUNT_TYPE", ({ enumerable: true, get: function () { return gdchclient_1.GDCH_SERVICE_ACCOUNT_TYPE; } })); +__exportStar(__webpack_require__(20451), exports); +const auth = new googleauth_1.GoogleAuth(); +exports.auth = auth; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 84358: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2023 Google LLC +// +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LRUCache = void 0; +exports.snakeToCamel = snakeToCamel; +exports.originalOrCamelOptions = originalOrCamelOptions; +exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject; +exports.isValidFile = isValidFile; +exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation; +const fs = __webpack_require__(79896); +const os = __webpack_require__(70857); +const path = __webpack_require__(16928); +const WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json'; +const CLOUDSDK_CONFIG_DIRECTORY = 'gcloud'; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @param str the string to convert + * @returns the camelCase'd string + */ +function snakeToCamel(str) { + return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase()); +} +/** + * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference + * for original, non-camelCase key. + * + * @param obj object to lookup a value in + * @returns a `get` function for getting `obj[key || snakeKey]`, if available + */ +function originalOrCamelOptions(obj) { + /** + * + * @param key an index of object, preferably snake_case + * @returns the value `obj[key || snakeKey]`, if available + */ + function get(key) { + const o = (obj || {}); + return o[key] ?? o[snakeToCamel(key)]; + } + return { get }; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + */ +class LRUCache { + capacity; + /** + * Maps are in order. Thus, the older item is the first item. + * + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} + */ + #cache = new Map(); + maxAge; + constructor(options) { + this.capacity = options.capacity; + this.maxAge = options.maxAge; + } + /** + * Moves the key to the end of the cache. + * + * @param key the key to move + * @param value the value of the key + */ + #moveToEnd(key, value) { + this.#cache.delete(key); + this.#cache.set(key, { + value, + lastAccessed: Date.now(), + }); + } + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key, value) { + this.#moveToEnd(key, value); + this.#evict(); + } + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key) { + const item = this.#cache.get(key); + if (!item) + return; + this.#moveToEnd(key, item.value); + this.#evict(); + return item.value; + } + /** + * Maintain the cache based on capacity and TTL. + */ + #evict() { + const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; + /** + * Because we know Maps are in order, this item is both the + * last item in the list (capacity) and oldest (maxAge). + */ + let oldestItem = this.#cache.entries().next(); + while (!oldestItem.done && + (this.#cache.size > this.capacity || // too many + oldestItem.value[1].lastAccessed < cutoffDate) // too old + ) { + this.#cache.delete(oldestItem.value[0]); + oldestItem = this.#cache.entries().next(); + } + } +} +exports.LRUCache = LRUCache; +// Given and object remove fields where value is undefined. +function removeUndefinedValuesInObject(object) { + Object.entries(object).forEach(([key, value]) => { + if (value === undefined || value === 'undefined') { + delete object[key]; + } + }); + return object; +} +/** + * Helper to check if a path points to a valid file. + */ +async function isValidFile(filePath) { + try { + const stats = await fs.promises.lstat(filePath); + return stats.isFile(); + } + catch (e) { + return false; + } +} +/** + * Determines the well-known gcloud location for the certificate config file. + * @returns The platform-specific path to the configuration file. + * @internal + */ +function getWellKnownCertificateConfigFileLocation() { + const configDir = process.env.CLOUDSDK_CONFIG || + (_isWindows() + ? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY) + : path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY)); + return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE); +} +/** + * Checks if the current operating system is Windows. + * @returns True if the OS is Windows, false otherwise. + * @internal + */ +function _isWindows() { + return os.platform().startsWith('win'); +} +//# sourceMappingURL=util.js.map + +/***/ }), + +/***/ 42149: +/***/ ((__unused_webpack_module, exports) => { + + +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Colours = void 0; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +class Colours { + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream) { + return (stream && // May happen in browsers. + stream.isTTY && + (typeof stream.getColorDepth === 'function' + ? stream.getColorDepth() > 2 + : true)); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process === null || process === void 0 ? void 0 : process.stderr); + if (!this.enabled) { + Colours.reset = ''; + Colours.bright = ''; + Colours.dim = ''; + Colours.red = ''; + Colours.green = ''; + Colours.yellow = ''; + Colours.blue = ''; + Colours.magenta = ''; + Colours.cyan = ''; + Colours.white = ''; + Colours.grey = ''; + } + else { + Colours.reset = '\u001b[0m'; + Colours.bright = '\u001b[1m'; + Colours.dim = '\u001b[2m'; + Colours.red = '\u001b[31m'; + Colours.green = '\u001b[32m'; + Colours.yellow = '\u001b[33m'; + Colours.blue = '\u001b[34m'; + Colours.magenta = '\u001b[35m'; + Colours.cyan = '\u001b[36m'; + Colours.white = '\u001b[37m'; + Colours.grey = '\u001b[90m'; + } + } +} +exports.Colours = Colours; +Colours.enabled = false; +Colours.reset = ''; +Colours.bright = ''; +Colours.dim = ''; +Colours.red = ''; +Colours.green = ''; +Colours.yellow = ''; +Colours.blue = ''; +Colours.magenta = ''; +Colours.cyan = ''; +Colours.white = ''; +Colours.grey = ''; +Colours.refresh(); +//# sourceMappingURL=colours.js.map + +/***/ }), + +/***/ 23760: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + 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 __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(33181), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 33181: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +// Copyright 2021-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + 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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; +exports.getNodeBackend = getNodeBackend; +exports.getDebugBackend = getDebugBackend; +exports.getStructuredBackend = getStructuredBackend; +exports.setBackend = setBackend; +exports.log = log; +const events_1 = __webpack_require__(24434); +const process = __importStar(__webpack_require__(932)); +const util = __importStar(__webpack_require__(39023)); +const colours_1 = __webpack_require__(42149); +// Some functions (as noted) are based on the Node standard library, from +// the following file: +// +// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "events you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +var LogSeverity; +(function (LogSeverity) { + LogSeverity["DEFAULT"] = "DEFAULT"; + LogSeverity["DEBUG"] = "DEBUG"; + LogSeverity["INFO"] = "INFO"; + LogSeverity["WARNING"] = "WARNING"; + LogSeverity["ERROR"] = "ERROR"; +})(LogSeverity || (exports.LogSeverity = LogSeverity = {})); +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +class AdhocDebugLogger extends events_1.EventEmitter { + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + // Also add an instance pointer back to us. + instance: this, + // And pull over the EventEmitter functionality. + on: (event, listener) => this.on(event, listener), + }); + // Convenience methods for log levels. + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace) => log(namespace, this.func); + } + invoke(fields, ...args) { + // Push out any upstream logger first. + if (this.upstream) { + try { + this.upstream(fields, ...args); + } + catch (e) { + // Swallow exceptions to avoid interfering with other logging. + } + } + // Emit sink events. + try { + this.emit('log', fields, args); + } + catch (e) { + // Swallow exceptions to avoid interfering with other logging. + } + } + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); + } +} +exports.AdhocDebugLogger = AdhocDebugLogger; +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +exports.placeholder = new AdhocDebugLogger('', () => { }).func; +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +class DebugLogBackendBase { + constructor() { + var _a; + this.cached = new Map(); + this.filters = []; + this.filtersSet = false; + // Look for the Node config variable for what systems to enable. We'll store + // these for the log method below, which will call setFilters() once. + let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; + if (nodeFlag === 'all') { + nodeFlag = '*'; + } + this.filters = nodeFlag.split(','); + } + log(namespace, fields, ...args) { + try { + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; + } + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); + } + logger(fields, ...args); + } + catch (e) { + // Silently ignore all errors; we don't want them to interfere with + // the user's running app. + // e; + console.error(e); + } + } +} +exports.DebugLogBackendBase = DebugLogBackendBase; +// The basic backend. This one definitely works, but it's less feature-filled. +// +// Rather than using util.debuglog, this implements the same basic logic directly. +// The reason for this decision is that debuglog checks the value of the +// NODE_DEBUG environment variable before any user code runs; we therefore +// can't pipe our own enables into it (and util.debuglog will never print unless +// the user duplicates it into NODE_DEBUG, which isn't reasonable). +// +class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + // Default to allowing all systems, since we gate earlier based on whether the + // variable is empty. + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => { }; + } + return (fields, ...args) => { + var _a; + // TODO: `fields` needs to be turned into a string here, one way or another. + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; + break; + default: + level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; + break; + } + const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length + ? JSON.stringify(filteredFields) + : ''; + const fieldsColour = fieldsJson + ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` + : ''; + console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); + }; + } + // Regexp patterns below are from here: + // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 + setFilters() { + const totalFilters = this.filters.join(','); + const regexp = totalFilters + .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^'); + this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); + } +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +function getNodeBackend() { + return new NodeBackend(); +} +class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; + } + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + // TODO: `fields` needs to be turned into a string here. + debugLogger(args[0], ...args.slice(1)); + }; + } + setFilters() { + var _a; + const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; + process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; + } +} +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); +} +/** + * This pretty much works like the Node logger, but it outputs structured + * logging JSON matching Google Cloud's ingestion specs. Rather than handling + * its own output, it wraps another backend. The passed backend must be a subclass + * of `DebugLogBackendBase` (any of the backends exposed by this package will work). + */ +class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a; + super(); + this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : undefined; + } + makeLogger(namespace) { + var _a; + const debugLogger = (_a = this.upstream) === null || _a === void 0 ? void 0 : _a.makeLogger(namespace); + return (fields, ...args) => { + var _a; + const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; + const json = Object.assign({ + severity, + message: util.format(...args), + }, fields); + const jsonString = JSON.stringify(json); + if (debugLogger) { + debugLogger(fields, jsonString); + } + else { + console.log('%s', jsonString); + } + }; + } + setFilters() { + var _a; + (_a = this.upstream) === null || _a === void 0 ? void 0 : _a.setFilters(); + } +} +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); +} +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +exports.env = { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', +}; +// Keep a copy of all namespaced loggers so users can reliably .on() them. +// Note that these cached functions will need to deal with changes in the backend. +const loggerCache = new Map(); +// Our current global backend. This might be: +let cachedBackend = undefined; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); +} +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +function log(namespace, parent) { + // If the enable environment variable isn't set, do nothing. The user + // can still choose to set a backend of their choice using the manual + // `setBackend()`. + if (!cachedBackend) { + const enablesFlag = process.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; + } + } + // This might happen mostly if the typings are dropped in a user's code, + // or if they're calling from JavaScript. + if (!namespace) { + return exports.placeholder; + } + // Handle sub-loggers. + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; + } + // Reuse loggers so things like event sinks are persistent. + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; + } + // Do we have a backend yet? + if (cachedBackend === null) { + // Explicitly disabled. + return exports.placeholder; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + // The logger is further wrapped so we can handle the backend changing out. + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + // Did the user pass a custom backend? + if (cachedBackend === null) { + // Explicitly disabled. + return; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; +} +//# sourceMappingURL=logging-utils.js.map + +/***/ }), + +/***/ 97222: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var json_stringify = (__webpack_require__(44455).stringify); +var json_parse = __webpack_require__(17161); + +module.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + } +}; +//create the default method members with no options applied for backwards compatibility +module.exports.parse = json_parse(); +module.exports.stringify = json_stringify; + + +/***/ }), + +/***/ 17161: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BigNumber = null; + +// regexpxs extracted from +// (c) BSD-3-Clause +// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors + +const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; +const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + +/* + json_parse.js + 2012-06-20 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This file creates a json_parse function. + During create you can (optionally) specify some behavioural switches + + require('json-bigint')(options) + + The optional options parameter holds switches that drive certain + aspects of the parsing process: + * options.strict = true will warn about duplicate-key usage in the json. + The default (strict = false) will silently ignore those and overwrite + values for keys that are in duplicate use. + + The resulting function follows this signature: + json_parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = json_parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + This is a reference implementation. You are free to copy, modify, or + redistribute. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode, + hasOwnProperty, message, n, name, prototype, push, r, t, text +*/ + +var json_parse = function (options) { + 'use strict'; + + // This is a function that can parse a JSON text, producing a JavaScript + // data structure. It is a simple, recursive descent parser. It does not use + // eval or regular expressions, so it can be used as a model for implementing + // a JSON parser in other languages. + + // We are defining the function inside of another function to avoid creating + // global variables. + + // Default options one can override by passing options to the parse() + var _options = { + strict: false, // not being strict means do not generate syntax errors for "duplicate key" + storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string + alwaysParseAsBig: false, // toggles whether all numbers should be Big + useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js + protoAction: 'error', + constructorAction: 'error', + }; + + // If there are options, then use them to override the default _options + if (options !== undefined && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = + options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = + options.useNativeBigInt === true ? options.useNativeBigInt : false; + + if (typeof options.constructorAction !== 'undefined') { + if ( + options.constructorAction === 'error' || + options.constructorAction === 'ignore' || + options.constructorAction === 'preserve' + ) { + _options.constructorAction = options.constructorAction; + } else { + throw new Error( + `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` + ); + } + } + + if (typeof options.protoAction !== 'undefined') { + if ( + options.protoAction === 'error' || + options.protoAction === 'ignore' || + options.protoAction === 'preserve' + ) { + _options.protoAction = options.protoAction; + } else { + throw new Error( + `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` + ); + } + } + } + + var at, // The index of the current character + ch, // The current character + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t', + }, + text, + error = function (m) { + // Call error when something is wrong. + + throw { + name: 'SyntaxError', + message: m, + at: at, + text: text, + }; + }, + next = function (c) { + // If a c parameter is provided, verify that it matches the current character. + + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + + // Get the next character. When there are no more characters, + // return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; + }, + number = function () { + // Parse a number value. + + var number, + string = ''; + + if (ch === '-') { + string = '-'; + next('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error('Bad number'); + } else { + if (BigNumber == null) BigNumber = __webpack_require__(49017); + //if (number > 9007199254740992 || number < -9007199254740992) + // Bignumber has stricter check: everything with length > 15 digits disallowed + if (string.length > 15) + return _options.storeAsString + ? string + : _options.useNativeBigInt + ? BigInt(string) + : new BigNumber(string); + else + return !_options.alwaysParseAsBig + ? number + : _options.useNativeBigInt + ? BigInt(number) + : new BigNumber(number); + } + }, + string = function () { + // Parse a string value. + + var hex, + i, + string = '', + uffff; + + // When parsing for string values, we must look for " and \ characters. + + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) string += text.substring(startAt, at - 1); + next(); + return string; + } + if (ch === '\\') { + if (at - 1 > startAt) string += text.substring(startAt, at - 1); + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + startAt = at; + } + } + } + error('Bad string'); + }, + white = function () { + // Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + word = function () { + // true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + value, // Place holder for the value function. + array = function () { + // Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error('Bad array'); + }, + object = function () { + // Parse an object value. + + var key, + object = Object.create(null); + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if ( + _options.strict === true && + Object.hasOwnProperty.call(object, key) + ) { + error('Duplicate key "' + key + '"'); + } + + if (suspectProtoRx.test(key) === true) { + if (_options.protoAction === 'error') { + error('Object contains forbidden prototype property'); + } else if (_options.protoAction === 'ignore') { + value(); + } else { + object[key] = value(); + } + } else if (suspectConstructorRx.test(key) === true) { + if (_options.constructorAction === 'error') { + error('Object contains forbidden constructor property'); + } else if (_options.constructorAction === 'ignore') { + value(); + } else { + object[key] = value(); + } + } else { + object[key] = value(); + } + + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + error('Bad object'); + }; + + value = function () { + // Parse a JSON value. It could be an object, an array, a string, a number, + // or a word. + + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); + } + }; + + // Return the json_parse function. It will have access to all of the above + // functions and variables. + + return function (source, reviver) { + var result; + + text = source + ''; + at = 0; + ch = ' '; + result = value(); + white(); + if (ch) { + error('Syntax error'); + } + + // If there is a reviver function, we recursively walk the new structure, + // passing each name/value pair to the reviver function for possible + // transformation, starting with a temporary root object that holds the result + // in an empty key. If there is not a reviver function, we simply return the + // result. + + return typeof reviver === 'function' + ? (function walk(holder, key) { + var k, + v, + value = holder[key]; + if (value && typeof value === 'object') { + Object.keys(value).forEach(function (k) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + }); + } + return reviver.call(holder, key, value); + })({ '': result }, '') + : result; + }; +}; + +module.exports = json_parse; + + +/***/ }), + +/***/ 44455: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var BigNumber = __webpack_require__(49017); + +/* + json2.js + 2013-05-26 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +var JSON = module.exports; + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key], + isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value)); + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + if (isBigNumber) { + return value; + } else { + return quote(value); + } + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + case 'bigint': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + Object.keys(value).forEach(function(k) { + var v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + }); + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } +}()); + + +/***/ }), + +/***/ 62104: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(5725).Buffer); +var crypto = __webpack_require__(76982); +var formatEcdsa = __webpack_require__(58210); +var util = __webpack_require__(39023); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +var bufferEqual; +var timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + + return crypto.timingSafeEqual(a, b) +} : function timingSafeEqual(a, b) { + if (!bufferEqual) { + bufferEqual = __webpack_require__(53775); + } + + return bufferEqual(a, b) +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; + + +/***/ }), + +/***/ 16798: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/*global exports*/ +var SignStream = __webpack_require__(36690); +var VerifyStream = __webpack_require__(76682); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; + + +/***/ }), + +/***/ 61189: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global module, process*/ +var Buffer = (__webpack_require__(5725).Buffer); +var Stream = __webpack_require__(2203); +var util = __webpack_require__(39023); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; + + +/***/ }), + +/***/ 36690: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global module*/ +var Buffer = (__webpack_require__(5725).Buffer); +var DataStream = __webpack_require__(61189); +var jwa = __webpack_require__(62104); +var Stream = __webpack_require__(2203); +var toString = __webpack_require__(65540); +var util = __webpack_require__(39023); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret; + secret = secret == null ? opts.privateKey : secret; + secret = secret == null ? opts.key : secret; + if (/^hs/i.test(opts.header.alg) === true && secret == null) { + throw new TypeError('secret must be a string or buffer or a KeyObject') + } + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; + + +/***/ }), + +/***/ 65540: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global module*/ +var Buffer = (__webpack_require__(20181).Buffer); + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; + + +/***/ }), + +/***/ 76682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global module*/ +var Buffer = (__webpack_require__(5725).Buffer); +var DataStream = __webpack_require__(61189); +var jwa = __webpack_require__(62104); +var Stream = __webpack_require__(2203); +var toString = __webpack_require__(65540); +var util = __webpack_require__(39023); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret; + secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey; + secretOrKey = secretOrKey == null ? opts.key : secretOrKey; + if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) { + throw new TypeError('secret must be a string or buffer or a KeyObject') + } + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; + + +/***/ }), + +/***/ 37301: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +const retry = __webpack_require__(27956); + +const networkErrorMsgs = [ + 'Failed to fetch', // Chrome + 'NetworkError when attempting to fetch resource.', // Firefox + 'The Internet connection appears to be offline.', // Safari + 'Network request failed' // `cross-fetch` +]; + +class AbortError extends Error { + constructor(message) { + super(); + + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + + this.name = 'AbortError'; + this.message = message; + } +} + +const decorateErrorWithCounts = (error, attemptNumber, options) => { + // Minus 1 from attemptNumber because the first attempt does not count as a retry + const retriesLeft = options.retries - (attemptNumber - 1); + + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; +}; + +const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); + +const pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => {}, + retries: 10, + ...options + }; + + const operation = retry.operation(options); + + operation.attempt(async attemptNumber => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + + try { + await options.onFailedAttempt(error); + } catch (error) { + reject(error); + return; + } + + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); +}); + +module.exports = pRetry; +// TODO: remove this in the next major version +module.exports["default"] = pRetry; + +module.exports.AbortError = AbortError; + + +/***/ }), + +/***/ 27956: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(94026); + +/***/ }), + +/***/ 94026: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var RetryOperation = __webpack_require__(78060); + +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); +}; + +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } + + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); + + return timeouts; +}; + +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; + + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); + } + } + } + + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; + + +/***/ }), + +/***/ 78060: +/***/ ((module) => { + +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; + } + + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } +} +module.exports = RetryOperation; + +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); +} + +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + + this._timeouts = []; + this._cachedTimeouts = null; +}; + +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } + + this._errors.push(err); + + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + + var self = this; + this._timer = setTimeout(function() { + self._attempts++; + + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); + + if (self._options.unref) { + self._timeout.unref(); + } + } + + self._fn(self._attempts); + }, timeout); + + if (this._options.unref) { + this._timer.unref(); + } + + return true; +}; + +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } + + this._operationStart = new Date().getTime(); + + this._fn(this._attempts); +}; + +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = RetryOperation.prototype.try; + +RetryOperation.prototype.errors = function() { + return this._errors; +}; + +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; + +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + + return mainError; +}; + + +/***/ }), + +/***/ 5725: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(20181) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 65348: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { EMPTY_BUFFER } = __webpack_require__(93920); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = __webpack_require__(48812); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} + + +/***/ }), + +/***/ 93920: +/***/ ((module) => { + + + +const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; +const hasBlob = typeof Blob !== 'undefined'; + +if (hasBlob) BINARY_TYPES.push('blob'); + +module.exports = { + BINARY_TYPES, + CLOSE_TIMEOUT: 30000, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + hasBlob, + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; + + +/***/ }), + +/***/ 79947: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { kForOnEventAttribute, kListener } = __webpack_require__(93920); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} + + +/***/ }), + +/***/ 98904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { tokenChars } = __webpack_require__(72002); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; + + +/***/ }), + +/***/ 5933: +/***/ ((module) => { + + + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; + + +/***/ }), + +/***/ 61613: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const zlib = __webpack_require__(43106); + +const bufferUtil = __webpack_require__(65348); +const Limiter = __webpack_require__(5933); +const { kStatusCode } = __webpack_require__(93920); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {Boolean} [options.isServer=false] Create the instance in either + * server or client mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + */ + constructor(options) { + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._maxPayload = this._options.maxPayload | 0; + this._isServer = !!this._options.isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + (typeof params.client_max_window_bits === 'number' + ? opts.clientMaxWindowBits > params.client_max_window_bits + : !params.client_max_window_bits)) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + + // + // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the + // fact that in Node.js versions prior to 13.10.0, the callback for + // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing + // `zlib.reset()` ensures that either the callback is invoked or an error is + // emitted. + // + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + + err[kStatusCode] = 1007; + this[kCallback](err); +} + + +/***/ }), + +/***/ 37620: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { Writable } = __webpack_require__(2203); + +const PerMessageDeflate = __webpack_require__(61613); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = __webpack_require__(93920); +const { concat, toArrayBuffer, unmask } = __webpack_require__(65348); +const { isValidStatusCode, isValidUTF8 } = __webpack_require__(72002); + +const FastBuffer = Buffer[Symbol.species]; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const DEFER_EVENT = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxBufferedChunks=0] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=0] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowSynchronousEvents = + options.allowSynchronousEvents !== undefined + ? options.allowSynchronousEvents + : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxBufferedChunks = options.maxBufferedChunks | 0; + this._maxFragments = options.maxFragments | 0; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._numFragments = 0; + this._fragments = []; + + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + if ( + this._maxBufferedChunks > 0 && + this._buffers.length >= this._maxBufferedChunks + ) { + cb( + this.createError( + RangeError, + 'Too many buffered chunks', + false, + 1008, + 'WS_ERR_TOO_MANY_BUFFERED_PARTS' + ) + ); + return; + } + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + + if (!this._errored) cb(); + } + + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + const error = this.createError( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + + cb(error); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if (!this._fragmented) { + const error = this.createError( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + const error = this.createError( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + + cb(error); + return; + } + + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + + cb(error); + return; + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) { + this.controlMessage(data, cb); + return; + } + + if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) { + const error = this.createError( + RangeError, + 'Too many message fragments', + false, + 1008, + 'WS_ERR_TOO_MANY_BUFFERED_PARTS' + ); + + cb(error); + return; + } + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + this.dataMessage(cb); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + + this._fragments.push(buf); + } + + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._numFragments = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else if (this._binaryType === 'blob') { + data = new Blob(fragments); + } else { + data = fragments; + } + + if (this._allowSynchronousEvents) { + this.emit('message', data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 0x08) { + if (data.length === 0) { + this._loop = false; + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + + cb(error); + return; + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + this._loop = false; + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } +} + +module.exports = Receiver; + + +/***/ }), + +/***/ 18604: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + + + +const { Duplex } = __webpack_require__(2203); +const { randomFillSync } = __webpack_require__(76982); +const { + types: { isUint8Array } +} = __webpack_require__(39023); + +const PerMessageDeflate = __webpack_require__(61613); +const { EMPTY_BUFFER, kWebSocket, NOOP } = __webpack_require__(93920); +const { isBlob, isValidStatusCode } = __webpack_require__(72002); +const { mask: applyMask, toBuffer } = __webpack_require__(65348); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); +const RANDOM_POOL_SIZE = 8 * 1024; +let randomPool; +let randomPoolPointer = RANDOM_POOL_SIZE; + +const DEFAULT = 0; +const DEFLATING = 1; +const GET_BLOB_DATA = 2; + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = undefined; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + /* istanbul ignore else */ + if (randomPool === undefined) { + // + // This is lazily initialized because server-sent frames must not + // be masked so it may never be used. + // + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else if (isUint8Array(data)) { + buf.set(data, 2); + } else { + throw new TypeError('Second argument must be a string or a Uint8Array'); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } + + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + + blob + .arrayBuffer() + .then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while the blob was being read' + ); + + // + // `callCallbacks` is called in the next tick to ensure that errors + // that might be thrown in the callbacks behave like errors thrown + // outside the promise chain. + // + process.nextTick(callCallbacks, this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + + if (!compress) { + this._state = DEFAULT; + this.sendFrame(Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); + } + }) + .catch((err) => { + // + // `onError` is called in the next tick for the same reason that + // `callCallbacks` above is. + // + process.nextTick(onError, this, err, cb); + }); + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + callCallbacks(this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {(Buffer | String)[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Calls queued callbacks with an error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error to call the callbacks with + * @param {Function} [cb] The first callback + * @private + */ +function callCallbacks(sender, err, cb) { + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } +} + +/** + * Handles a `Sender` error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error + * @param {Function} [cb] The first pending callback + * @private + */ +function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); +} + + +/***/ }), + +/***/ 62509: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ + + +const WebSocket = __webpack_require__(16126); +const { Duplex } = __webpack_require__(2203); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; + + +/***/ }), + +/***/ 1643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { tokenChars } = __webpack_require__(72002); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; + + +/***/ }), + +/***/ 72002: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +const { isUtf8 } = __webpack_require__(20181); + +const { hasBlob } = __webpack_require__(93920); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +/** + * Determines whether a value is a `Blob`. + * + * @param {*} value The value to be tested + * @return {Boolean} `true` if `value` is a `Blob`, else `false` + * @private + */ +function isBlob(value) { + return ( + hasBlob && + typeof value === 'object' && + typeof value.arrayBuffer === 'function' && + typeof value.type === 'string' && + typeof value.stream === 'function' && + (value[Symbol.toStringTag] === 'Blob' || + value[Symbol.toStringTag] === 'File') + ); +} + +module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = __webpack_require__(60710); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} + + +/***/ }), + +/***/ 96264: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ + + + +const EventEmitter = __webpack_require__(24434); +const http = __webpack_require__(58611); +const { Duplex } = __webpack_require__(2203); +const { createHash } = __webpack_require__(76982); + +const extension = __webpack_require__(98904); +const PerMessageDeflate = __webpack_require__(61613); +const subprotocol = __webpack_require__(1643); +const WebSocket = __webpack_require__(16126); +const { CLOSE_TIMEOUT, GUID, kWebSocket } = __webpack_require__(93920); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to + * wait for the closing handshake to finish after `websocket.close()` is + * called + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxBufferedChunks=262144] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=16384] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowSynchronousEvents: true, + autoPong: true, + maxBufferedChunks: 256 * 1024, + maxFragments: 16 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + closeTimeout: CLOSE_TIMEOUT, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const upgrade = req.headers.upgrade; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (key === undefined || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 13 && version !== 8) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { + 'Sec-WebSocket-Version': '13, 8' + }); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate({ + ...this.options.perMessageDeflate, + isServer: true, + maxPayload: this.options.maxPayload + }); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null, undefined, this.options); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxBufferedChunks: this.options.maxBufferedChunks, + maxFragments: this.options.maxFragments, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @param {Object} [headers] The HTTP response headers + * @private + */ +function abortHandshakeOrEmitwsClientError( + server, + req, + socket, + code, + message, + headers +) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message, headers); + } +} + + +/***/ }), + +/***/ 16126: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ + + + +const EventEmitter = __webpack_require__(24434); +const https = __webpack_require__(65692); +const http = __webpack_require__(58611); +const net = __webpack_require__(69278); +const tls = __webpack_require__(64756); +const { randomBytes, createHash } = __webpack_require__(76982); +const { Duplex, Readable } = __webpack_require__(2203); +const { URL } = __webpack_require__(87016); + +const PerMessageDeflate = __webpack_require__(61613); +const Receiver = __webpack_require__(37620); +const Sender = __webpack_require__(18604); +const { isBlob } = __webpack_require__(72002); + +const { + BINARY_TYPES, + CLOSE_TIMEOUT, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = __webpack_require__(93920); +const { + EventTarget: { addEventListener, removeEventListener } +} = __webpack_require__(79947); +const { format, parse } = __webpack_require__(98904); +const { toBuffer } = __webpack_require__(65348); + +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + if (!options || options.protocols === undefined) { + protocols = []; + } else if (Array.isArray(options.protocols)) { + protocols = options.protocols; + } else { + protocols = [options.protocols]; + } + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + + if (options.protocols === undefined) { + protocols = []; + } else if (Array.isArray(options.protocols)) { + protocols = options.protocols; + } else { + protocols = [options.protocols]; + } + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._closeTimeout = options.closeTimeout; + this._isServer = true; + } + } + + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxBufferedChunks=0] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=0] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxBufferedChunks: options.maxBufferedChunks, + maxFragments: options.maxFragments, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + const sender = new Sender(socket, this._extensions, options.generateMask); + + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + sender.onerror = senderOnError; + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + this._readyState = WebSocket.CLOSING; + setCloseTimer(this); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait + * for the closing handshake to finish after `websocket.close()` is called + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxBufferedChunks=262144] The maximum number of + * buffered data chunks + * @param {Number} [options.maxFragments=16384] The maximum number of message + * fragments + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + closeTimeout: CLOSE_TIMEOUT, + protocolVersion: protocolVersions[1], + maxBufferedChunks: 256 * 1024, + maxFragments: 16 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + protocols: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + websocket._closeTimeout = opts.closeTimeout; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = + opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate({ + ...opts.perMessageDeflate, + isServer: false, + maxPayload: opts.maxPayload + }); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const upgrade = res.headers.upgrade; + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxBufferedChunks: opts.maxBufferedChunks, + maxFragments: opts.maxFragments, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + // + // The following assignment is practically useless and is done only for + // consistency. + // + websocket._errorEmitted = true; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The `Sender` error event handler. + * + * @param {Error} The error + * @private + */ +function senderOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket.readyState === WebSocket.CLOSED) return; + if (websocket.readyState === WebSocket.OPEN) { + websocket._readyState = WebSocket.CLOSING; + setCloseTimer(websocket); + } + + // + // `socket.end()` is used instead of `socket.destroy()` to allow the other + // peer to finish sending queued data. There is no need to set a timer here + // because `CLOSING` means that it is already set or not needed. + // + this._socket.end(); + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * Set a timer to destroy the underlying raw socket of a WebSocket. + * + * @param {WebSocket} websocket The WebSocket instance + * @private + */ +function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + websocket._closeTimeout + ); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written. If instead, the + // socket is paused, any possible buffered data will be read as a single + // chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + this._readableState.length !== 0 + ) { + const chunk = this.read(this._readableState.length); + + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} + + +/***/ }), + +/***/ 48812: +/***/ ((module) => { + +module.exports = eval("require")("bufferutil"); + + +/***/ }), + +/***/ 60710: +/***/ ((module) => { + +module.exports = eval("require")("utf-8-validate"); + + +/***/ }), + +/***/ 79870: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +/** + * Copyright 2022 Google LLC + * + * 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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GCE_LINUX_BIOS_PATHS = void 0; +exports.isGoogleCloudServerless = isGoogleCloudServerless; +exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; +exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; +exports.isGoogleComputeEngine = isGoogleComputeEngine; +exports.detectGCPResidency = detectGCPResidency; +const fs_1 = __webpack_require__(79896); +const os_1 = __webpack_require__(70857); +/** + * Known paths unique to Google Compute Engine Linux instances + */ +exports.GCE_LINUX_BIOS_PATHS = { + BIOS_DATE: '/sys/class/dmi/id/bios_date', + BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor', +}; +const GCE_MAC_ADDRESS_REGEX = /^42:01/; +/** + * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). + * + * Uses the: + * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. + * + * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. + */ +function isGoogleCloudServerless() { + /** + * `CLOUD_RUN_JOB` is used for Cloud Run Jobs + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * + * `FUNCTION_NAME` is used in older Cloud Functions environments: + * - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}. + * + * `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments: + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}. + */ + const isGFEnvironment = process.env.CLOUD_RUN_JOB || + process.env.FUNCTION_NAME || + process.env.K_SERVICE; + return !!isGFEnvironment; +} +/** + * Determines if the process is running on a Linux Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. + */ +function isGoogleComputeEngineLinux() { + if ((0, os_1.platform)() !== 'linux') + return false; + try { + // ensure this file exist + (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); + // ensure this file exist and matches + const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8'); + return /Google/.test(biosVendor); + } + catch { + return false; + } +} +/** + * Determines if the process is running on a Google Compute Engine instance with a known + * MAC address. + * + * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. + */ +function isGoogleComputeEngineMACAddress() { + const interfaces = (0, os_1.networkInterfaces)(); + for (const item of Object.values(interfaces)) { + if (!item) + continue; + for (const { mac } of item) { + if (GCE_MAC_ADDRESS_REGEX.test(mac)) { + return true; + } + } + } + return false; +} +/** + * Determines if the process is running on a Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. + */ +function isGoogleComputeEngine() { + return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); +} +/** + * Determines if the process is running on Google Cloud Platform. + * + * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. + */ +function detectGCPResidency() { + return isGoogleCloudServerless() || isGoogleComputeEngine(); +} +//# sourceMappingURL=gcp-residency.js.map + +/***/ }), + +/***/ 4381: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + +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 () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0; +exports.instance = instance; +exports.project = project; +exports.universe = universe; +exports.bulk = bulk; +exports.isAvailable = isAvailable; +exports.resetIsAvailableCache = resetIsAvailableCache; +exports.getGCPResidency = getGCPResidency; +exports.setGCPResidency = setGCPResidency; +exports.requestTimeout = requestTimeout; +/** + * Copyright 2018 Google LLC + * + * 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. + */ +const gaxios_1 = __webpack_require__(10627); +const jsonBigint = __webpack_require__(97222); +const gcp_residency_1 = __webpack_require__(79870); +const logger = __importStar(__webpack_require__(23760)); +exports.BASE_PATH = '/computeMetadata/v1'; +exports.HOST_ADDRESS = 'http://169.254.169.254'; +exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; +exports.HEADER_NAME = 'Metadata-Flavor'; +exports.HEADER_VALUE = 'Google'; +exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); +const log = logger.log('gcp-metadata'); +/** + * Metadata server detection override options. + * + * Available via `process.env.METADATA_SERVER_DETECTION`. + */ +exports.METADATA_SERVER_DETECTION = Object.freeze({ + 'assume-present': "don't try to ping the metadata server, but assume it's present", + none: "don't try to ping the metadata server, but don't try to use it either", + 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)", + 'ping-only': 'skip the BIOS probe, and go straight to pinging', +}); +/** + * Returns the base URL while taking into account the GCE_METADATA_HOST + * environment variable if it exists. + * + * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1. + */ +function getBaseUrl(baseUrl) { + if (!baseUrl) { + baseUrl = + process.env.GCE_METADATA_IP || + process.env.GCE_METADATA_HOST || + exports.HOST_ADDRESS; + } + // If no scheme is provided default to HTTP: + if (!/^https?:\/\//.test(baseUrl)) { + baseUrl = `http://${baseUrl}`; + } + return new URL(exports.BASE_PATH, baseUrl).href; +} +// Accepts an options object passed from the user to the API. In previous +// versions of the API, it referred to a `Request` or an `Axios` request +// options object. Now it refers to an object with very limited property +// names. This is here to help ensure users don't pass invalid options when +// they upgrade from 0.4 to 0.5 to 0.8. +function validate(options) { + Object.keys(options).forEach(key => { + switch (key) { + case 'params': + case 'property': + case 'headers': + break; + case 'qs': + throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); + default: + throw new Error(`'${key}' is not a valid configuration option.`); + } + }); +} +async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { + const headers = new Headers(exports.HEADERS); + let metadataKey = ''; + let params = {}; + if (typeof type === 'object') { + const metadataAccessor = type; + new Headers(metadataAccessor.headers).forEach((value, key) => headers.set(key, value)); + metadataKey = metadataAccessor.metadataKey; + params = metadataAccessor.params || params; + noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries; + fastFail = metadataAccessor.fastFail || fastFail; + } + else { + metadataKey = type; + } + if (typeof options === 'string') { + metadataKey += `/${options}`; + } + else { + validate(options); + if (options.property) { + metadataKey += `/${options.property}`; + } + new Headers(options.headers).forEach((value, key) => headers.set(key, value)); + params = options.params || params; + } + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const req = { + url: `${getBaseUrl()}/${metadataKey}`, + headers, + retryConfig: { noResponseRetries }, + params, + responseType: 'text', + timeout: requestTimeout(), + }; + log.info('instance request %j', req); + const res = await requestMethod(req); + log.info('instance metadata is %s', res.data); + const metadataFlavor = res.headers.get(exports.HEADER_NAME); + if (metadataFlavor !== exports.HEADER_VALUE) { + throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : 'no header'}`); + } + if (typeof res.data === 'string') { + try { + return jsonBigint.parse(res.data); + } + catch { + /* ignore */ + } + } + return res.data; +} +async function fastFailMetadataRequest(options) { + const secondaryOptions = { + ...options, + url: options.url + ?.toString() + .replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)), + }; + // We race a connection between DNS/IP to metadata server. There are a couple + // reasons for this: + // + // 1. the DNS is slow in some GCP environments; by checking both, we might + // detect the runtime environment significantly faster. + // 2. we can't just check the IP, which is tarpitted and slow to respond + // on a user's local machine. + // + // Returns first resolved promise or if all promises get rejected we return an AggregateError. + // + // Note, however, if a failure happens prior to a success, a rejection should + // occur, this is for folks running locally. + // + const r1 = (0, gaxios_1.request)(options); + const r2 = (0, gaxios_1.request)(secondaryOptions); + return Promise.any([r1, r2]); +} +/** + * Obtain metadata for the current GCE instance. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const serviceAccount: {} = await instance('service-accounts/'); + * const serviceAccountEmail: string = await instance('service-accounts/default/email'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instance(options) { + return metadataAccessor('instance', options); +} +/** + * Obtain metadata for the current GCP project. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const projectId: string = await project('project-id'); + * const numericProjectId: number = await project('numeric-project-id'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function project(options) { + return metadataAccessor('project', options); +} +/** + * Obtain metadata for the current universe. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const universeDomain: string = await universe('universe-domain'); + * ``` + */ +function universe(options) { + return metadataAccessor('universe', options); +} +/** + * Retrieve metadata items in parallel. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const data = await bulk([ + * { + * metadataKey: 'instance', + * }, + * { + * metadataKey: 'project/project-id', + * }, + * ] as const); + * + * // data.instance; + * // data['project/project-id']; + * ``` + * + * @param properties The metadata properties to retrieve + * @returns The metadata in `metadatakey:value` format + */ +async function bulk(properties) { + const r = {}; + await Promise.all(properties.map(item => { + return (async () => { + const res = await metadataAccessor(item); + const key = item.metadataKey; + r[key] = res; + })(); + })); + return r; +} +/* + * How many times should we retry detecting GCP environment. + */ +function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES + ? Number(process.env.DETECT_GCP_RETRIES) + : 0; +} +let cachedIsAvailableResponse; +/** + * Determine if the metadata server is currently available. + */ +async function isAvailable() { + if (process.env.METADATA_SERVER_DETECTION) { + const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); + if (!(value in exports.METADATA_SERVER_DETECTION)) { + throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`); + } + switch (value) { + case 'assume-present': + return true; + case 'none': + return false; + case 'bios-only': + return getGCPResidency(); + case 'ping-only': + // continue, we want to ping the server + } + } + try { + // If a user is instantiating several GCP libraries at the same time, + // this may result in multiple calls to isAvailable(), to detect the + // runtime environment. We use the same promise for each of these calls + // to reduce the network load. + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), + // If the default HOST_ADDRESS has been overridden, we should not + // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in + // a non-GCP environment): + !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); + } + await cachedIsAvailableResponse; + return true; + } + catch (e) { + const err = e; + if (process.env.DEBUG_AUTH) { + console.info(err); + } + if (err.type === 'request-timeout') { + // If running in a GCP environment, metadata endpoint should return + // within ms. + return false; + } + if (err.response && err.response.status === 404) { + return false; + } + else { + if (!(err.response && err.response.status === 404) && + // A warning is emitted if we see an unexpected err.code, or err.code + // is not populated: + (!err.code || + ![ + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'ENOENT', + 'ENOTFOUND', + 'ECONNREFUSED', + ].includes(err.code.toString()))) { + let code = 'UNKNOWN'; + if (err.code) + code = err.code.toString(); + process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning'); + } + // Failure to resolve the metadata service means that it is not available. + return false; + } + } +} +/** + * reset the memoized isAvailable() lookup. + */ +function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; +} +/** + * A cache for the detected GCP Residency. + */ +exports.gcpResidencyCache = null; +/** + * Detects GCP Residency. + * Caches results to reduce costs for subsequent calls. + * + * @see setGCPResidency for setting + */ +function getGCPResidency() { + if (exports.gcpResidencyCache === null) { + setGCPResidency(); + } + return exports.gcpResidencyCache; +} +/** + * Sets the detected GCP Residency. + * Useful for forcing metadata server detection behavior. + * + * Set `null` to autodetect the environment (default behavior). + * @see getGCPResidency for getting + */ +function setGCPResidency(value = null) { + exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); +} +/** + * Obtain the timeout for requests to the metadata server. + * + * In certain environments and conditions requests can take longer than + * the default timeout to complete. This function will determine the + * appropriate timeout based on the environment. + * + * @returns {number} a request timeout duration in milliseconds. + */ +function requestTimeout() { + return getGCPResidency() ? 0 : 3000; +} +__exportStar(__webpack_require__(79870), exports); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 39122: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +// Copyright 2023 Google LLC +// 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. +const pkg = __webpack_require__(62598); +module.exports = { pkg }; +//# sourceMappingURL=util.cjs.map + +/***/ }), + +/***/ 69946: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + +// Copyright 2023 Google LLC +// 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0; +const pkg = __webpack_require__(21930); +exports.pkg = pkg; +const PRODUCT_NAME = 'google-api-nodejs-client'; +exports.PRODUCT_NAME = PRODUCT_NAME; +const USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; +exports.USER_AGENT = USER_AGENT; +//# sourceMappingURL=shared.cjs.map + +/***/ }), + +/***/ 81247: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AT: () => (/* binding */ supportsGoogleStrictToolSampling), +/* harmony export */ B1: () => (/* binding */ convertTools), +/* harmony export */ Ih: () => (/* binding */ usesGoogleThinkingLevel), +/* harmony export */ O5: () => (/* binding */ resolveGoogleThinkingLevel), +/* harmony export */ RE: () => (/* binding */ toGoogleSdkThinkingLevel), +/* harmony export */ _0: () => (/* binding */ convertMessages), +/* harmony export */ cq: () => (/* binding */ getDisabledGoogleThinkingConfig), +/* harmony export */ f7: () => (/* binding */ mapStopReason), +/* harmony export */ hz: () => (/* binding */ resolveGoogleFunctionCallingMode), +/* harmony export */ ng: () => (/* binding */ toGoogleThinkingLevel), +/* harmony export */ oH: () => (/* binding */ isThinkingPart), +/* harmony export */ pc: () => (/* binding */ retainThoughtSignature), +/* harmony export */ rM: () => (/* binding */ retryGoogleRequest) +/* harmony export */ }); +/* unused harmony exports requiresToolCallId, mapToolChoice, mapStopReasonString */ +/* harmony import */ var _google_genai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(74751); +/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(25941); +/* harmony import */ var _utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(46863); +/* harmony import */ var _utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(43780); +/* harmony import */ var _utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19883); +/* harmony import */ var _constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(37776); +/* harmony import */ var _transform_messages_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48809); +/** + * Shared utilities for Google Generative AI and Google Vertex providers. + */ + + + + + + + +const GOOGLE_SDK_THINKING_LEVEL_MAP = { + THINKING_LEVEL_UNSPECIFIED: _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ThinkingLevel */ .HL.THINKING_LEVEL_UNSPECIFIED, + MINIMAL: _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ThinkingLevel */ .HL.MINIMAL, + LOW: _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ThinkingLevel */ .HL.LOW, + MEDIUM: _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ThinkingLevel */ .HL.MEDIUM, + HIGH: _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .ThinkingLevel */ .HL.HIGH, +}; +/** Resolve a supported pi level or model-specific Google mapping to a standard Google level. */ +function resolveGoogleThinkingLevel(model, level) { + const mapped = model.thinkingLevelMap?.[level]; + const resolvedLevel = typeof mapped === "string" ? mapped.toLowerCase() : level; + switch (resolvedLevel) { + case "minimal": + case "low": + case "medium": + case "high": + return resolvedLevel; + default: + throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`); + } +} +/** + * Whether this model uses Gemini's discrete `thinkingLevel` control instead of + * the token-based `thinkingBudget` control. Supported levels come from the + * model's `thinkingLevelMap`; this only selects the Google wire format. + */ +function usesGoogleThinkingLevel(model) { + const id = model.id.toLowerCase(); + return ( + // Match Gemini 3 Pro/Flash IDs with or without a minor version, such as + // gemini-3-flash-preview, gemini-3.1-pro-preview, and gemini-3.8-flash. + /gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id) || + id === "gemini-flash-latest" || + id === "gemini-flash-lite-latest" || + // Match both hosted Gemma 4 naming forms: gemma-4-* and gemma4-*. + /gemma-?4/.test(id)); +} +function toGoogleThinkingLevel(level) { + switch (level) { + case "minimal": + return "MINIMAL"; + case "low": + return "LOW"; + case "medium": + return "MEDIUM"; + case "high": + return "HIGH"; + } +} +function toGoogleSdkThinkingLevel(level) { + return GOOGLE_SDK_THINKING_LEVEL_MAP[level]; +} +function getDisabledGoogleThinkingConfig(model) { + if (!usesGoogleThinkingLevel(model)) + return { thinkingBudget: 0 }; + const fallback = (0,_models_js__WEBPACK_IMPORTED_MODULE_1__/* .clampThinkingLevel */ .Kt)(model, "off"); + if (fallback === "off") + return { thinkingBudget: 0 }; + const resolvedLevel = resolveGoogleThinkingLevel(model, fallback); + const apiLevel = toGoogleThinkingLevel(resolvedLevel); + return { thinkingLevel: toGoogleSdkThinkingLevel(apiLevel) }; +} +/** + * Determines whether a streamed Gemini `Part` should be treated as "thinking". + * + * Protocol note (Gemini / Vertex AI thought signatures): + * - `thought: true` is the definitive marker for thinking content (thought summaries). + * - `thoughtSignature` is an encrypted representation of the model's internal thought process + * used to preserve reasoning context across multi-turn interactions. + * - `thoughtSignature` can appear on ANY part type (text, functionCall, etc.) - it does NOT + * indicate the part itself is thinking content. + * - For non-functionCall responses, the signature appears on the last part for context replay. + * - When persisting/replaying model outputs, signature-bearing parts must be preserved as-is; + * do not merge/move signatures across parts. + * + * See: https://ai.google.dev/gemini-api/docs/thought-signatures + */ +function isThinkingPart(part) { + return part.thought === true; +} +/** + * Retain thought signatures during streaming. + * + * Some backends only send `thoughtSignature` on the first delta for a given part/block; later deltas may omit it. + * This helper preserves the last non-empty signature for the current block. + * + * Note: this does NOT merge or move signatures across distinct response parts. It only prevents + * a signature from being overwritten with `undefined` within the same streamed block. + */ +function retainThoughtSignature(existing, incoming) { + if (typeof incoming === "string" && incoming.length > 0) + return incoming; + return existing; +} +// Thought signatures must be base64 for Google APIs (TYPE_BYTES). +const base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/; +function isValidThoughtSignature(signature) { + if (!signature) + return false; + if (signature.length % 4 !== 0) + return false; + return base64SignaturePattern.test(signature); +} +/** + * Only keep signatures from the same provider/model and with valid base64. + */ +function resolveThoughtSignature(isSameProviderAndModel, signature) { + return isSameProviderAndModel && isValidThoughtSignature(signature) ? signature : undefined; +} +/** + * Models via Google APIs that require explicit tool call IDs in function calls/responses. + */ +function requiresToolCallId(modelId) { + const geminiMajorVersion = getGeminiMajorVersion(modelId); + return (modelId.startsWith("claude-") || + modelId.startsWith("gpt-oss-") || + (geminiMajorVersion !== undefined && geminiMajorVersion >= 3)); +} +function getGeminiMajorVersion(modelId) { + const match = modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/); + if (!match) + return undefined; + return Number.parseInt(match[1], 10); +} +function supportsMultimodalFunctionResponse(modelId) { + const geminiMajorVersion = getGeminiMajorVersion(modelId); + if (geminiMajorVersion !== undefined) { + return geminiMajorVersion >= 3; + } + return true; +} +/** + * Convert internal messages to Gemini Content[] format. + */ +function convertMessages(model, context) { + // Gemini has no mid-conversation system messages; the leading prompt is sent as systemInstruction. + const conversation = (0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__/* .withoutInitialSystemMessage */ .rg)((0,_utils_transcript_js__WEBPACK_IMPORTED_MODULE_2__/* .collapseSystemMessages */ .zI)(context).messages); + const contents = []; + const normalizeToolCallId = (id) => { + if (!requiresToolCallId(model.id)) + return id; + return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64); + }; + const transformedMessages = (0,_transform_messages_js__WEBPACK_IMPORTED_MODULE_3__/* .transformMessages */ .b)(conversation, model, normalizeToolCallId); + for (const msg of transformedMessages) { + if (msg.role === "user") { + if (typeof msg.content === "string") { + contents.push({ + role: "user", + parts: [{ text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(msg.content) }], + }); + } + else { + const parts = msg.content.map((item) => { + if (item.type === "text") { + return { text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(item.text) }; + } + else { + return { + inlineData: { + mimeType: item.mimeType, + data: item.data, + }, + }; + } + }); + if (parts.length === 0) + continue; + contents.push({ + role: "user", + parts, + }); + } + } + else if (msg.role === "assistant") { + const parts = []; + // Check if message is from same provider and model - only then keep thinking blocks + const isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id; + for (const block of msg.content) { + if (block.type === "text") { + const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.textSignature); + // Skip empty text blocks — unless they carry a thought signature. Gemini can attach + // the signature to a part whose visible text is empty and requires it echoed back; + // dropping it breaks the reasoning chain and the model intermittently ends mid-task + // turns with a thought-only STOP (empty completion, no tool call). + if ((!block.text || block.text.trim() === "") && !thoughtSignature) + continue; + parts.push({ + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(block.text), + ...(thoughtSignature && { thoughtSignature }), + }); + } + else if (block.type === "thinking") { + // Only keep as thinking block if same provider AND same model + // Otherwise convert to plain text (no tags to avoid model mimicking them) + if (isSameProviderAndModel) { + const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thinkingSignature); + // Same rule as text blocks: an empty thinking block is dropped only when it + // carries no signature (mirrors the anthropic converter's handling). + if ((!block.thinking || block.thinking.trim() === "") && !thoughtSignature) + continue; + parts.push({ + thought: true, + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(block.thinking), + ...(thoughtSignature && { thoughtSignature }), + }); + } + else { + // Cross-provider/model: the signature is unusable, empty blocks stay dropped. + if (!block.thinking || block.thinking.trim() === "") + continue; + parts.push({ + text: (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(block.thinking), + }); + } + } + else if (block.type === "toolCall") { + const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.thoughtSignature); + const part = { + functionCall: { + name: block.name, + args: block.arguments ?? {}, + ...(requiresToolCallId(model.id) ? { id: block.id } : {}), + }, + ...(thoughtSignature && { thoughtSignature }), + }; + parts.push(part); + } + } + if (parts.length === 0) + continue; + contents.push({ + role: "model", + parts, + }); + } + else if (msg.role === "toolResult") { + // Extract text and image content + const textContent = msg.content.filter((c) => c.type === "text"); + const textResult = textContent.map((c) => c.text).join("\n"); + const imageContent = model.input.includes("image") + ? msg.content.filter((c) => c.type === "image") + : []; + const hasText = textResult.length > 0; + const hasImages = imageContent.length > 0; + // Gemini 3+ models support multimodal function responses with images nested inside + // functionResponse.parts. Claude and other non-Gemini models behind Cloud Code Assist / + // Gemini < 3 still needs a separate user image turn. + const modelSupportsMultimodalFunctionResponse = supportsMultimodalFunctionResponse(model.id); + // Use "output" key for success, "error" key for errors as per SDK documentation + const responseValue = hasText ? (0,_utils_sanitize_unicode_js__WEBPACK_IMPORTED_MODULE_4__/* .sanitizeSurrogates */ .J)(textResult) : hasImages ? "(see attached image)" : ""; + const imageParts = imageContent.map((imageBlock) => ({ + inlineData: { + mimeType: imageBlock.mimeType, + data: imageBlock.data, + }, + })); + const includeId = requiresToolCallId(model.id); + const functionResponsePart = { + functionResponse: { + name: msg.toolName, + response: msg.isError ? { error: responseValue } : { output: responseValue }, + ...(hasImages && modelSupportsMultimodalFunctionResponse && { parts: imageParts }), + ...(includeId ? { id: msg.toolCallId } : {}), + }, + }; + // Cloud Code Assist API requires all function responses to be in a single user turn. + // Check if the last content is already a user turn with function responses and merge. + const lastContent = contents[contents.length - 1]; + if (lastContent?.role === "user" && lastContent.parts?.some((p) => p.functionResponse)) { + lastContent.parts.push(functionResponsePart); + } + else { + contents.push({ + role: "user", + parts: [functionResponsePart], + }); + } + // For Gemini < 3, add images in a separate user message + if (hasImages && !modelSupportsMultimodalFunctionResponse) { + contents.push({ + role: "user", + parts: [{ text: "Tool result image:" }, ...imageParts], + }); + } + } + } + return contents; +} +const JSON_SCHEMA_META_DECLARATIONS = new Set([ + "$schema", + "$id", + "$anchor", + "$dynamicAnchor", + "$vocabulary", + "$comment", + "$defs", + "definitions", // pre-draft-2019-09 equivalent of $defs +]); +/** + * Strip meta-declarations from a schema obj + */ +function sanitizeForOpenApi(schema) { + if (typeof schema !== "object" || schema === null || Array.isArray(schema)) { + return schema; + } + const result = {}; + for (const [key, value] of Object.entries(schema)) { + if (JSON_SCHEMA_META_DECLARATIONS.has(key)) + continue; + result[key] = sanitizeForOpenApi(value); + } + return result; +} +/** + * Convert tools to Gemini function declarations format. + * + * By default uses `parametersJsonSchema` which supports full JSON Schema (including + * anyOf, oneOf, const, etc.). Set `useParameters` to true to use the legacy `parameters` + * field instead (OpenAPI 3.03 Schema). This is needed for Cloud Code Assist with Claude + * models, where the API translates `parameters` into Anthropic's `input_schema`. + */ +function convertTools(tools, useParameters = false, supportsStrictMode = true) { + if (tools.length === 0) + return undefined; + return [ + { + functionDeclarations: tools.map((tool) => { + const strict = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__/* .resolveJsonSchemaStrictSampling */ ._F)(tool, supportsStrictMode); + const parameters = (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__/* .getJsonSchemaToolParameters */ .Km)(tool, strict); + return { + name: tool.name, + description: tool.description, + ...(useParameters + ? { parameters: sanitizeForOpenApi(parameters) } + : { parametersJsonSchema: parameters }), + }; + }), + }, + ]; +} +/** Gemini 3+ enforces required function parameters in validated tool-calling modes. */ +function supportsGoogleStrictToolSampling(modelId) { + const majorVersion = getGeminiMajorVersion(modelId); + return majorVersion !== undefined && majorVersion >= 3; +} +/** Map tool choice string to Gemini FunctionCallingConfigMode. */ +function mapToolChoice(choice) { + switch (choice) { + case "auto": + return _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FunctionCallingConfigMode */ .ce.AUTO; + case "none": + return _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FunctionCallingConfigMode */ .ce.NONE; + case "any": + return _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FunctionCallingConfigMode */ .ce.ANY; + default: + return _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FunctionCallingConfigMode */ .ce.AUTO; + } +} +function resolveGoogleFunctionCallingMode(tools, toolChoice, supportsStrictMode) { + const useStrictMode = tools.some((tool) => (0,_constrained_sampling_js__WEBPACK_IMPORTED_MODULE_5__/* .resolveJsonSchemaStrictSampling */ ._F)(tool, supportsStrictMode) === true); + if (toolChoice === "none" || toolChoice === "any") { + return mapToolChoice(toolChoice); + } + if (useStrictMode) { + return _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FunctionCallingConfigMode */ .ce.VALIDATED; + } + return toolChoice ? mapToolChoice(toolChoice) : undefined; +} +/** + * Map Gemini FinishReason to our StopReason. + */ +function mapStopReason(reason) { + switch (reason) { + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.STOP: + return "stop"; + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.MAX_TOKENS: + return "length"; + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.BLOCKLIST: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.PROHIBITED_CONTENT: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.SPII: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.SAFETY: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.IMAGE_SAFETY: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.IMAGE_PROHIBITED_CONTENT: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.IMAGE_RECITATION: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.IMAGE_OTHER: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.RECITATION: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.FINISH_REASON_UNSPECIFIED: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.OTHER: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.LANGUAGE: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.MALFORMED_FUNCTION_CALL: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.UNEXPECTED_TOOL_CALL: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.TOO_MANY_TOOL_CALLS: + case _google_genai__WEBPACK_IMPORTED_MODULE_0__/* .FinishReason */ .eD.NO_IMAGE: + return "error"; + default: { + const _exhaustive = reason; + throw new Error(`Unhandled stop reason: ${_exhaustive}`); + } + } +} +/** + * Map string finish reason to our StopReason (for raw API responses). + */ +function mapStopReasonString(reason) { + switch (reason) { + case "STOP": + return "stop"; + case "MAX_TOKENS": + return "length"; + default: + return "error"; + } +} +/** + * Run a Google GenAI SDK request with the shared provider retry policy + * (408/409/429/5xx with backoff, honoring retry-after), mirroring how the + * Anthropic and OpenAI adapters wrap their initial request in + * retryProviderRequest. The SDK's ApiError has a `status` property but no + * `headers` property, and retryProviderRequest only retries errors that carry + * both, so normalize the error by adding the missing `headers` before + * rethrowing. + */ +function retryGoogleRequest(request, options) { + return (0,_utils_provider_retry_js__WEBPACK_IMPORTED_MODULE_6__/* .retryProviderRequest */ .T)(async () => { + try { + return await request(); + } + catch (error) { + if (error instanceof Error && "status" in error && !("headers" in error)) { + error.headers = undefined; + } + throw error; + } + }, { + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + signal: options?.signal, + }); +} +//# sourceMappingURL=google-shared.js.map + +/***/ }), + +/***/ 20372: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Jo: () => (/* binding */ normalizeProviderError), +/* harmony export */ lR: () => (/* binding */ formatProviderError) +/* harmony export */ }); +/* unused harmony exports MAX_PROVIDER_ERROR_BODY_CHARS, truncateErrorText, safeJsonStringify */ +// Shared normalization for provider HTTP error objects. +// +// Endpoints behind a proxy / gateway may return a non-2xx response whose body +// the provider SDK cannot fold into `error.message`. The SDK error object still +// carries the HTTP status and the raw/parsed body, but under SDK-specific field +// names. Provider catch blocks that read only `error.message` therefore drop +// the body and surface opaque messages like `"403 status code (no body)"` or +// collapse to `"Unknown: UnknownError"`. +// +// `normalizeProviderError` probes the known SDK field shapes (Mistral, +// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider +// composes into its display string. The `messageCarriesBody` flag captures the +// Anthropic / `@google/genai` happy path where the SDK already folded the body +// into the message, so providers can preserve it without double-printing. +const MAX_PROVIDER_ERROR_BODY_CHARS = 4000; +function normalizeProviderError(error) { + if (!(error instanceof Error)) { + return { message: safeJsonStringify(error), messageCarriesBody: false }; + } + const sdkError = error; + const status = extractStatus(sdkError); + const body = extractBody(sdkError); + const messageCarriesBody = body === undefined || error.message.includes(body); + return { + status, + body, + message: error.message, + messageCarriesBody, + }; +} +/** + * Probe the HTTP status, first numeric hit wins, in SDK-field order: + * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) → + * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock). + */ +function extractStatus(error) { + if (typeof error.statusCode === "number") + return error.statusCode; + if (typeof error.status === "number") + return error.status; + if (typeof error.$metadata?.httpStatusCode === "number") + return error.$metadata.httpStatusCode; + if (typeof error.$response?.statusCode === "number") + return error.$response.statusCode; + return undefined; +} +/** + * Probe the raw body reason, first usable hit wins, in SDK-field order: + * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's + * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response + * streams are treated as no body so they do not surface as `"{}"` or serialized + * stream internals. The chosen body is truncated to the cap. + */ +function extractBody(error) { + const bodyText = pickBodyText(error); + if (bodyText === undefined) + return undefined; + const trimmed = bodyText.trim(); + if (trimmed.length === 0) + return undefined; + return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS); +} +function pickBodyText(error) { + if (typeof error.body === "string") + return error.body; + if (isPlainNonEmptyObject(error.error)) + return safeJsonStringify(error.error); + const responseBody = error.$response?.body; + if (typeof responseBody === "string") + return responseBody; + if (isReadableStreamLike(responseBody)) + return undefined; + if (isPlainNonEmptyObject(responseBody)) + return safeJsonStringify(responseBody); + return undefined; +} +function isReadableStreamLike(value) { + return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function"; +} +/** + * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class + * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an + * HTTP stream/response wrapper object, and stringifying one produced garbage + * like `{"_events":...}` as the "body", which then REPLACED `error.message` + * in the composed display string. `error.message` is where the SDK puts the + * real deserialized exception text ("Input is too long...", schema validation + * details, ...), so the one useful string was discarded for noise. A class + * instance yields no body, `messageCarriesBody` stays true, and the real + * message survives. Complements the `pipe` sniffing above: web + * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper + * classes fail the prototype check, while parsed JSON bodies (plain objects + * by construction) still pass. + */ +function isPlainNonEmptyObject(value) { + if (typeof value !== "object" || value === null) + return false; + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + return false; + return Object.keys(value).length > 0; +} +/** + * Compose a display string from a normalized error. When the message already + * carries the body (Anthropic / `@google/genai` happy path) or no body/status + * was extracted, the message is returned unchanged. Otherwise the status and + * body are surfaced, with an optional provider prefix. + * + * - no prefix: `": "` + * - prefix: `" (): "` + */ +function formatProviderError(norm, prefix) { + if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) { + return prefix !== undefined && norm.status !== undefined + ? `${prefix} (${norm.status}): ${norm.message}` + : norm.message; + } + return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`; +} +function truncateErrorText(text, maxChars) { + if (text.length <= maxChars) + return text; + return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`; +} +function safeJsonStringify(value) { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? String(value) : serialized; + } + catch { + return String(value); + } +} +//# sourceMappingURL=error-body.js.map + +/***/ }), + +/***/ 55278: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ w: () => (/* binding */ getPiUserAgent) +/* harmony export */ }); +function loadNodeOs() { + if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) { + return null; + } + return process.getBuiltinModule?.("node:os") ?? null; +} +// Keep runtime OS loading browser-safe. A top-level runtime import of node:os breaks browser/Vite builds. +const nodeOs = loadNodeOs(); +function getPiUserAgent() { + return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)"; +} +//# sourceMappingURL=pi-user-agent.js.map + +/***/ }), + +/***/ 46863: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ retryProviderRequest) +/* harmony export */ }); +const DEFAULT_MAX_RETRY_DELAY_MS = 60_000; +function isProviderError(error) { + if (!(error instanceof Error) || !("status" in error) || !("headers" in error)) + return false; + return ((error.status === undefined || typeof error.status === "number") && + (error.headers === undefined || error.headers instanceof Headers)); +} +/** Mirrors the pinned OpenAI/Anthropic SDK retry policy; review when either SDK is upgraded. */ +function isRetryableProviderError(error) { + const shouldRetry = error.headers?.get("x-should-retry"); + if (shouldRetry === "true") + return true; + if (shouldRetry === "false") + return false; + if (error.status === undefined) + return true; + return (error.status === 408 || + error.status === 409 || + error.status === 429 || + (typeof error.status === "number" && error.status >= 500)); +} +function validateServerRetryDelayMs(delayMs, maxRetryDelayMs, providerErrorMessage) { + const maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS; + if (maxDelayMs > 0 && delayMs > maxDelayMs) { + throw new Error(`Server requested ${Math.ceil(delayMs / 1000)}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${providerErrorMessage}`); + } + return delayMs; +} +function getRetryDelayMs(error, retryIndex, maxRetryDelayMs) { + const retryAfterMs = error.headers?.get("retry-after-ms"); + if (retryAfterMs) { + const value = Number.parseFloat(retryAfterMs); + if (!Number.isNaN(value)) + return validateServerRetryDelayMs(value, maxRetryDelayMs, error.message); + } + const retryAfter = error.headers?.get("retry-after"); + if (retryAfter) { + const seconds = Number.parseFloat(retryAfter); + const delayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1000; + return validateServerRetryDelayMs(delayMs, maxRetryDelayMs, error.message); + } + const exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1000; + return exponentialDelay * (1 - Math.random() * 0.25); +} +function createAbortError() { + const error = new Error("Request aborted"); + error.name = "AbortError"; + return error; +} +function abortableSleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(createAbortError()); + return; + } + const onAbort = () => { + clearTimeout(timeout); + reject(createAbortError()); + }; + const timeout = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, Math.max(0, ms)); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** + * Reproduce the retry behavior used by the OpenAI and Anthropic SDKs while making + * their backoff sleep interruptible. Their built-in retry timers ignore the + * request AbortSignal, so callers must invoke the SDK with `maxRetries: 0` and + * wrap the request with this helper. Provider-requested delays above + * `maxRetryDelayMs` fail immediately (60 seconds by default); set it to zero to + * disable the limit. + */ +async function retryProviderRequest(request, options = {}) { + const maxRetries = options.maxRetries ?? 0; + let retriesRemaining = maxRetries; + for (;;) { + try { + // Each retry is a fresh SDK request, so X-Stainless-Retry-Count remains zero. + return await request(); + } + catch (error) { + if (options.signal?.aborted) + throw createAbortError(); + if (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error)) + throw error; + const retryIndex = maxRetries - retriesRemaining; + retriesRemaining--; + await abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal); + } + } +} +//# sourceMappingURL=provider-retry.js.map + +/***/ }), + +/***/ 74751: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + eD: () => (/* binding */ FinishReason), + ce: () => (/* binding */ FunctionCallingConfigMode), + M4: () => (/* binding */ GoogleGenAI), + r: () => (/* binding */ ResourceScope), + HL: () => (/* binding */ ThinkingLevel) +}); + +// UNUSED EXPORTS: ActivityHandling, AdapterSize, AggregationMetric, ApiError, ApiSpec, AspectRatio, AudioResponseFormat, AudioTranscriptionConfigMode, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, Delivery, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EmbeddingApiType, EndSensitivity, Environment, EvaluateDatasetResponse, FeatureSelectionPreference, FileSource, FileState, Files, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImageResizeMode, ImageResponseFormat, ImageSize, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, InteractionStatus, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MatchOperation, MediaModality, MediaProcessing, MediaResolution, Modality, ModelStage, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PairwiseChoice, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, ProminentPeople, RawReferenceImage, RecontextImageResponse, RegisterFilesResponse, ReinforcementTuningAutoraterScorerParsedResponseConversionScorer, ReinforcementTuningParseResponseConfig, ReinforcementTuningThinkingLevel, ReplayResponse, ResponseFormat, ResponseParseType, SafetyFilterLevel, SafetyPolicy, Scale, SegmentImageResponse, SegmentMode, ServiceTier, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, TextResponseFormat, Tokens, ToolResponse, ToolType, TrafficType, TuningJobState, TuningMethod, TuningMode, TuningSpeed, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VadSignalType, ValidateRewardResponse, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, VideoOrientation, VideoResponseFormat, VoiceActivityType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls + +// EXTERNAL MODULE: ../../node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js +var p_retry = __webpack_require__(37301); +// EXTERNAL MODULE: ../../node_modules/.pnpm/google-auth-library@10.9.1/node_modules/google-auth-library/build/src/index.js +var src = __webpack_require__(17220); +// EXTERNAL MODULE: external "fs" +var external_fs_ = __webpack_require__(79896); +// EXTERNAL MODULE: external "fs/promises" +var promises_ = __webpack_require__(91943); +// EXTERNAL MODULE: external "node:stream" +var external_node_stream_ = __webpack_require__(57075); +// EXTERNAL MODULE: external "node:stream/promises" +var external_node_stream_promises_ = __webpack_require__(46466); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/stream.js +var stream = __webpack_require__(62509); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/extension.js +var extension = __webpack_require__(98904); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/permessage-deflate.js +var permessage_deflate = __webpack_require__(61613); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/receiver.js +var receiver = __webpack_require__(37620); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/sender.js +var sender = __webpack_require__(18604); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/subprotocol.js +var subprotocol = __webpack_require__(1643); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket.js +var websocket = __webpack_require__(16126); +// EXTERNAL MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js +var websocket_server = __webpack_require__(96264); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/wrapper.mjs + + + + + + + + + + + +/* harmony default export */ const wrapper = ((/* unused pure expression or super */ null && (WebSocket))); + +// EXTERNAL MODULE: external "path" +var external_path_ = __webpack_require__(16928); +;// CONCATENATED MODULE: ../../node_modules/.pnpm/@google+genai@2.21.0_@modelcontextprotocol+sdk@1.32.1_zod@4.6.7_/node_modules/@google/genai/dist/node/index.mjs + + + + + + + + + + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + if (keyToSet === '_self' && + typeof value === 'object' && + value !== null && + !Array.isArray(value)) { + const valueAsRecord = value; + Object.assign(data, valueAsRecord); + } + else { + data[keyToSet] = value; + } + } +} +function getValueByPath(data, keys, defaultValue = undefined) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return defaultValue; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return defaultValue; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1), defaultValue)); + } + else { + return defaultValue; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return defaultValue; + } + throw error; + } +} +/** + * Moves values from source paths to destination paths. + * + * Examples: + * moveValueByPath( + * {'requests': [{'content': v1}, {'content': v2}]}, + * {'requests[].*': 'requests[].request.*'} + * ) + * -> {'requests': [{'request': {'content': v1}}, {'request': {'content': v2}}]} + */ +function moveValueByPath(data, paths) { + for (const [sourcePath, destPath] of Object.entries(paths)) { + const sourceKeys = sourcePath.split('.'); + const destKeys = destPath.split('.'); + // Determine keys to exclude from wildcard to avoid cyclic references + const excludeKeys = new Set(); + let wildcardIdx = -1; + for (let i = 0; i < sourceKeys.length; i++) { + if (sourceKeys[i] === '*') { + wildcardIdx = i; + break; + } + } + if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) { + // Extract the intermediate key between source and dest paths + // Example: source=['requests[]', '*'], dest=['requests[]', 'request', '*'] + // We want to exclude 'request' + for (let i = wildcardIdx; i < destKeys.length; i++) { + const key = destKeys[i]; + if (key !== '*' && !key.endsWith('[]') && !key.endsWith('[0]')) { + excludeKeys.add(key); + } + } + } + _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys); + } +} +/** + * Recursively moves values from source path to destination path. + */ +function _moveValueRecursive(data, sourceKeys, destKeys, keyIdx, excludeKeys) { + if (keyIdx >= sourceKeys.length) { + return; + } + if (typeof data !== 'object' || data === null) { + return; + } + const key = sourceKeys[keyIdx]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + const dataRecord = data; + if (keyName in dataRecord && Array.isArray(dataRecord[keyName])) { + for (const item of dataRecord[keyName]) { + _moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } + } + else if (key === '*') { + // wildcard - move all fields + if (typeof data === 'object' && data !== null && !Array.isArray(data)) { + const dataRecord = data; + const keysToMove = Object.keys(dataRecord).filter((k) => !k.startsWith('_') && !excludeKeys.has(k)); + const valuesToMove = {}; + for (const k of keysToMove) { + valuesToMove[k] = dataRecord[k]; + } + // Set values at destination + for (const [k, v] of Object.entries(valuesToMove)) { + const newDestKeys = []; + for (const dk of destKeys.slice(keyIdx)) { + if (dk === '*') { + newDestKeys.push(k); + } + else { + newDestKeys.push(dk); + } + } + setValueByPath(dataRecord, newDestKeys, v); + } + for (const k of keysToMove) { + delete dataRecord[k]; + } + } + } + else { + // Navigate to next level + const dataRecord = data; + if (key in dataRecord) { + _moveValueRecursive(dataRecord[key], sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + return toObject; +} +function generateVideosOperationFromMldev$1(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev$1(fromResponse)); + } + return toObject; +} +function generateVideosOperationFromVertex$1(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex$1(fromResponse)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev$1(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosResponseFromVertex$1(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex$1(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generatedVideoFromMldev$1(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev$1(fromVideo)); + } + return toObject; +} +function generatedVideoFromVertex$1(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex$1(fromVideo)); + } + return toObject; +} +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + return toObject; +} +function importFileOperationFromMldev$1(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], importFileResponseFromMldev$1(fromResponse)); + } + return toObject; +} +function importFileResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + setValueByPath(toObject, ['parent'], fromParent); + } + const fromDocumentName = getValueByPath(fromObject, ['documentName']); + if (fromDocumentName != null) { + setValueByPath(toObject, ['documentName'], fromDocumentName); + } + return toObject; +} +function uploadToFileSearchStoreOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], uploadToFileSearchStoreResponseFromMldev(fromResponse)); + } + return toObject; +} +function uploadToFileSearchStoreResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + setValueByPath(toObject, ['parent'], fromParent); + } + const fromDocumentName = getValueByPath(fromObject, ['documentName']); + if (fromDocumentName != null) { + setValueByPath(toObject, ['documentName'], fromDocumentName); + } + return toObject; +} +function videoFromMldev$1(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['encodedVideo']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes$1(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoFromVertex$1(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes$1(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. `output` contains the stdout, if any. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution failed. `output` contains the stderr and stdout, if any. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial `output` present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Data type of the schema field. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Type of auth scheme. This enum is not supported in Gemini API. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The location of the API key. This enum is not supported in Gemini API. */ +var HttpElementLocation; +(function (HttpElementLocation) { + HttpElementLocation["HTTP_IN_UNSPECIFIED"] = "HTTP_IN_UNSPECIFIED"; + /** + * Element is in the HTTP request query. + */ + HttpElementLocation["HTTP_IN_QUERY"] = "HTTP_IN_QUERY"; + /** + * Element is in the HTTP request header. + */ + HttpElementLocation["HTTP_IN_HEADER"] = "HTTP_IN_HEADER"; + /** + * Element is in the HTTP request path. + */ + HttpElementLocation["HTTP_IN_PATH"] = "HTTP_IN_PATH"; + /** + * Element is in the HTTP request body. + */ + HttpElementLocation["HTTP_IN_BODY"] = "HTTP_IN_BODY"; + /** + * Element is in the HTTP request cookie. + */ + HttpElementLocation["HTTP_IN_COOKIE"] = "HTTP_IN_COOKIE"; +})(HttpElementLocation || (HttpElementLocation = {})); +/** The API spec that the external API implements. This enum is not supported in Gemini API. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; + /** + * Operates in a mobile environment. + */ + Environment["ENVIRONMENT_MOBILE"] = "ENVIRONMENT_MOBILE"; + /** + * Operates in a desktop environment. + */ + Environment["ENVIRONMENT_DESKTOP"] = "ENVIRONMENT_DESKTOP"; +})(Environment || (Environment = {})); +/** SafetyPolicy */ +var SafetyPolicy; +(function (SafetyPolicy) { + /** + * Unspecified safety policy. + */ + SafetyPolicy["SAFETY_POLICY_UNSPECIFIED"] = "SAFETY_POLICY_UNSPECIFIED"; + /** + * Safety policy for financial transactions. + */ + SafetyPolicy["FINANCIAL_TRANSACTIONS"] = "FINANCIAL_TRANSACTIONS"; + /** + * Safety policy for sensitive data modification. + */ + SafetyPolicy["SENSITIVE_DATA_MODIFICATION"] = "SENSITIVE_DATA_MODIFICATION"; + /** + * Safety policy for communication tools (e.g. Gmail, Chat, Meet). + */ + SafetyPolicy["COMMUNICATION_TOOL"] = "COMMUNICATION_TOOL"; + /** + * Safety policy for account creation. + */ + SafetyPolicy["ACCOUNT_CREATION"] = "ACCOUNT_CREATION"; + /** + * Safety policy for data modification. + */ + SafetyPolicy["DATA_MODIFICATION"] = "DATA_MODIFICATION"; + /** + * Safety policy for user consent management. + */ + SafetyPolicy["USER_CONSENT_MANAGEMENT"] = "USER_CONSENT_MANAGEMENT"; + /** + * Safety policy for legal terms and agreements. + */ + SafetyPolicy["LEGAL_TERMS_AND_AGREEMENTS"] = "LEGAL_TERMS_AND_AGREEMENTS"; +})(SafetyPolicy || (SafetyPolicy = {})); +/** Sites with confidence level chosen & above this value will be blocked from the search results. This enum is not supported in Gemini API. */ +var PhishBlockThreshold; +(function (PhishBlockThreshold) { + /** + * Defaults to unspecified. + */ + PhishBlockThreshold["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"] = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Blocks Low and above confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Blocks Medium and above confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Blocks High and above confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_HIGH_AND_ABOVE"] = "BLOCK_HIGH_AND_ABOVE"; + /** + * Blocks Higher and above confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_HIGHER_AND_ABOVE"] = "BLOCK_HIGHER_AND_ABOVE"; + /** + * Blocks Very high and above confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_VERY_HIGH_AND_ABOVE"] = "BLOCK_VERY_HIGH_AND_ABOVE"; + /** + * Blocks Extremely high confidence URL that is risky. + */ + PhishBlockThreshold["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH"; +})(PhishBlockThreshold || (PhishBlockThreshold = {})); +/** Specifies the function Behavior. If not specified, the system keeps the current function call behavior. This field is currently only supported by the BidiGenerateContent method. */ +var Behavior; +(function (Behavior) { + /** + * This value is unspecified. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The number of thoughts tokens that the model should generate. */ +var ThinkingLevel; +(function (ThinkingLevel) { + /** + * Unspecified thinking level. + */ + ThinkingLevel["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED"; + /** + * MINIMAL thinking level. + */ + ThinkingLevel["MINIMAL"] = "MINIMAL"; + /** + * Low thinking level. + */ + ThinkingLevel["LOW"] = "LOW"; + /** + * Medium thinking level. + */ + ThinkingLevel["MEDIUM"] = "MEDIUM"; + /** + * High thinking level. + */ + ThinkingLevel["HIGH"] = "HIGH"; +})(ThinkingLevel || (ThinkingLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Controls whether prominent people (celebrities) generation is allowed. If used with personGeneration, personGeneration enum would take precedence. For instance, if ALLOW_NONE is set, all person generation would be blocked. If this field is unspecified, the default behavior is to allow prominent people. This enum is not supported in Gemini API. */ +var ProminentPeople; +(function (ProminentPeople) { + /** + * Unspecified value. The model will proceed with the default behavior, which is to allow generation of prominent people. + */ + ProminentPeople["PROMINENT_PEOPLE_UNSPECIFIED"] = "PROMINENT_PEOPLE_UNSPECIFIED"; + /** + * Allows the model to generate images of prominent people. + */ + ProminentPeople["ALLOW_PROMINENT_PEOPLE"] = "ALLOW_PROMINENT_PEOPLE"; + /** + * Prevents the model from generating images of prominent people. + */ + ProminentPeople["BLOCK_PROMINENT_PEOPLE"] = "BLOCK_PROMINENT_PEOPLE"; +})(ProminentPeople || (ProminentPeople = {})); +/** The harm category to be blocked. */ +var HarmCategory; +(function (HarmCategory) { + /** + * Default value. This value is unused. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * Abusive, threatening, or content intended to bully, torment, or ridicule. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * Content that promotes violence or incites hatred against individuals or groups based on certain attributes. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * Content that contains sexually explicit material. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Content that promotes, facilitates, or enables dangerous activities. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * Prompts designed to bypass safety filters. + */ + HarmCategory["HARM_CATEGORY_JAILBREAK"] = "HARM_CATEGORY_JAILBREAK"; + /** + * Images that contain hate speech. This enum value is not supported in Gemini API. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * Images that contain dangerous content. This enum value is not supported in Gemini API. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * Images that contain harassment. This enum value is not supported in Gemini API. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * Images that contain sexually explicit content. This enum value is not supported in Gemini API. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** The method for blocking content. If not specified, the default behavior is to use the probability score. This enum is not supported in Gemini API. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** The threshold for blocking content. If the harm probability exceeds this threshold, the content will be blocked. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * The harm block threshold is unspecified. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block content with a low harm probability or higher. + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block content with a medium harm probability or higher. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block content with a high harm probability. + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Do not block any content, regardless of its harm probability. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter entirely. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** Function calling mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * Unspecified function calling mode. This value should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model is constrained to predict either function calls or natural language response. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Output only. The reason why the model stopped generating tokens. + +If empty, the model has not stopped generating the tokens. */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; + /** + * Model called too many tools consecutively, thus the system exited execution. + */ + FinishReason["TOO_MANY_TOOL_CALLS"] = "TOO_MANY_TOOL_CALLS"; + /** + * Image generation stopped because the generated images have prohibited content. + */ + FinishReason["IMAGE_PROHIBITED_CONTENT"] = "IMAGE_PROHIBITED_CONTENT"; + /** + * The model was expected to generate an image, but none was generated. + */ + FinishReason["NO_IMAGE"] = "NO_IMAGE"; + /** + * Image generation stopped because the generated image may be a recitation from a source. + */ + FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION"; + /** + * Image generation stopped for a reason not otherwise specified. + */ + FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER"; +})(FinishReason || (FinishReason = {})); +/** Output only. The probability of harm for this category. */ +var HarmProbability; +(function (HarmProbability) { + /** + * The harm probability is unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * The harm probability is negligible. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * The harm probability is low. + */ + HarmProbability["LOW"] = "LOW"; + /** + * The harm probability is medium. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * The harm probability is high. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. The severity of harm for this category. This enum is not supported in Gemini API. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * The harm severity is unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * The harm severity is negligible. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * The harm severity is low. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * The harm severity is medium. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * The harm severity is high. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** The status of the URL retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * The URL was retrieved successfully. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * The URL retrieval failed. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. This enum value is not supported in Vertex AI. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. This enum value is not supported in Vertex AI. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the prompt was blocked. */ +var BlockedReason; +(function (BlockedReason) { + /** + * The blocked reason is unspecified. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * The prompt was blocked for safety reasons. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * The prompt was blocked for other reasons. For example, it may be due to the prompt's language, or because it contains other harmful content. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * The prompt was blocked because it contains a term from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * The prompt was blocked because it contains prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * The prompt was blocked because it contains content that is unsafe for image generation. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The prompt was blocked by Model Armor. This enum value is not supported in Gemini API. + */ + BlockedReason["MODEL_ARMOR"] = "MODEL_ARMOR"; + /** + * The prompt was blocked as a jailbreak attempt. This enum value is not supported in Gemini API. + */ + BlockedReason["JAILBREAK"] = "JAILBREAK"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. The traffic type for this request. This enum is not supported in Gemini API. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * The request was processed using Pay-As-You-Go quota. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Priority Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND_PRIORITY"] = "ON_DEMAND_PRIORITY"; + /** + * Type for Flex traffic. + */ + TrafficType["ON_DEMAND_FLEX"] = "ON_DEMAND_FLEX"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** The modality that this token count applies to. */ +var MediaModality; +(function (MediaModality) { + /** + * When a modality is not specified, it is treated as `TEXT`. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * The `Part` contains plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * The `Part` contains an image. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * The `Part` contains a video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * The `Part` contains audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * The `Part` contains a document, such as a PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** The stage of the underlying model. This enum is not supported in Vertex AI. */ +var ModelStage; +(function (ModelStage) { + /** + * Unspecified model stage. + */ + ModelStage["MODEL_STAGE_UNSPECIFIED"] = "MODEL_STAGE_UNSPECIFIED"; + /** + * The underlying model is subject to lots of tunings. + */ + ModelStage["UNSTABLE_EXPERIMENTAL"] = "UNSTABLE_EXPERIMENTAL"; + /** + * Models in this stage are for experimental purposes only. + */ + ModelStage["EXPERIMENTAL"] = "EXPERIMENTAL"; + /** + * Models in this stage are more mature than experimental models. + */ + ModelStage["PREVIEW"] = "PREVIEW"; + /** + * Models in this stage are considered stable and ready for production use. + */ + ModelStage["STABLE"] = "STABLE"; + /** + * If the model is on this stage, it means that this model is on the path to deprecation in near future. Only existing customers can use this model. + */ + ModelStage["LEGACY"] = "LEGACY"; + /** + * Models in this stage are deprecated. These models cannot be used. + */ + ModelStage["DEPRECATED"] = "DEPRECATED"; + /** + * Models in this stage are retired. These models cannot be used. + */ + ModelStage["RETIRED"] = "RETIRED"; +})(ModelStage || (ModelStage = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; + /** + * Indicates the model should return video. + */ + Modality["VIDEO"] = "VIDEO"; +})(Modality || (Modality = {})); +/** Delivery mode for the generated content. */ +var Delivery; +(function (Delivery) { + /** + * Default value. This value is unused. + */ + Delivery["DELIVERY_UNSPECIFIED"] = "DELIVERY_UNSPECIFIED"; + /** + * Generated bytes are returned inline in the response. + */ + Delivery["INLINE"] = "INLINE"; + /** + * Generated content is stored and a URI is returned. + */ + Delivery["URI"] = "URI"; +})(Delivery || (Delivery = {})); +/** The aspect ratio for the image output. */ +var AspectRatio; +(function (AspectRatio) { + /** + * Default value. This value is unused. + */ + AspectRatio["ASPECT_RATIO_UNSPECIFIED"] = "ASPECT_RATIO_UNSPECIFIED"; + /** + * 1:1 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_ONE_BY_ONE"] = "ASPECT_RATIO_ONE_BY_ONE"; + /** + * 2:3 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_TWO_BY_THREE"] = "ASPECT_RATIO_TWO_BY_THREE"; + /** + * 3:2 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_THREE_BY_TWO"] = "ASPECT_RATIO_THREE_BY_TWO"; + /** + * 3:4 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_THREE_BY_FOUR"] = "ASPECT_RATIO_THREE_BY_FOUR"; + /** + * 4:3 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_FOUR_BY_THREE"] = "ASPECT_RATIO_FOUR_BY_THREE"; + /** + * 4:5 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_FOUR_BY_FIVE"] = "ASPECT_RATIO_FOUR_BY_FIVE"; + /** + * 5:4 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_FIVE_BY_FOUR"] = "ASPECT_RATIO_FIVE_BY_FOUR"; + /** + * 9:16 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_NINE_BY_SIXTEEN"] = "ASPECT_RATIO_NINE_BY_SIXTEEN"; + /** + * 16:9 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_SIXTEEN_BY_NINE"] = "ASPECT_RATIO_SIXTEEN_BY_NINE"; + /** + * 21:9 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_TWENTY_ONE_BY_NINE"] = "ASPECT_RATIO_TWENTY_ONE_BY_NINE"; + /** + * 1:8 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_ONE_BY_EIGHT"] = "ASPECT_RATIO_ONE_BY_EIGHT"; + /** + * 8:1 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_EIGHT_BY_ONE"] = "ASPECT_RATIO_EIGHT_BY_ONE"; + /** + * 1:4 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_ONE_BY_FOUR"] = "ASPECT_RATIO_ONE_BY_FOUR"; + /** + * 4:1 aspect ratio. + */ + AspectRatio["ASPECT_RATIO_FOUR_BY_ONE"] = "ASPECT_RATIO_FOUR_BY_ONE"; +})(AspectRatio || (AspectRatio = {})); +/** The size of the image output. */ +var ImageSize; +(function (ImageSize) { + /** + * Default value. This value is unused. + */ + ImageSize["IMAGE_SIZE_UNSPECIFIED"] = "IMAGE_SIZE_UNSPECIFIED"; + /** + * 512px image size. + */ + ImageSize["IMAGE_SIZE_FIVE_TWELVE"] = "IMAGE_SIZE_FIVE_TWELVE"; + /** + * 1K image size. + */ + ImageSize["IMAGE_SIZE_ONE_K"] = "IMAGE_SIZE_ONE_K"; + /** + * 2K image size. + */ + ImageSize["IMAGE_SIZE_TWO_K"] = "IMAGE_SIZE_TWO_K"; + /** + * 4K image size. + */ + ImageSize["IMAGE_SIZE_FOUR_K"] = "IMAGE_SIZE_FOUR_K"; +})(ImageSize || (ImageSize = {})); +/** Tuning mode. This enum is not supported in Gemini API. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Adapter size for tuning. This enum is not supported in Gemini API. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Defines the type for parsing sample response. This enum is not supported in Gemini API. */ +var ResponseParseType; +(function (ResponseParseType) { + /** + * Default value. Fallback to IDENTITY + */ + ResponseParseType["RESPONSE_PARSE_TYPE_UNSPECIFIED"] = "RESPONSE_PARSE_TYPE_UNSPECIFIED"; + /** + * Returns the sample response as is. + */ + ResponseParseType["IDENTITY"] = "IDENTITY"; + /** + * Uses regex to extract the important part of sample response. Similar to [GoogleSQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_extract) `REGEX_EXTRACT(response, regex_extract_expression)`, but different in that if there are multiple matches, the last match will be returned. + */ + ResponseParseType["REGEX_EXTRACT"] = "REGEX_EXTRACT"; +})(ResponseParseType || (ResponseParseType = {})); +/** Match operation to use for evaluating rewards. This enum is not supported in Gemini API. */ +var MatchOperation; +(function (MatchOperation) { + /** + * Default value. A user error will be returned if not set. + */ + MatchOperation["MATCH_OPERATION_UNSPECIFIED"] = "MATCH_OPERATION_UNSPECIFIED"; + /** + * Equivalent to [GoogleSQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_contains) `REGEX_CONTAINS(target, expression)`. + */ + MatchOperation["REGEX_CONTAINS"] = "REGEX_CONTAINS"; + /** + * The match operation returns `true` if expression is a substring of the target. + */ + MatchOperation["PARTIAL_MATCH"] = "PARTIAL_MATCH"; + /** + * The match operation returns `true` expression is an exact match of the target. + */ + MatchOperation["EXACT_MATCH"] = "EXACT_MATCH"; +})(MatchOperation || (MatchOperation = {})); +/** Represents how much to think for the tuning job. */ +var ReinforcementTuningThinkingLevel; +(function (ReinforcementTuningThinkingLevel) { + /** + * Unspecified thinking level. + */ + ReinforcementTuningThinkingLevel["REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED"] = "REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED"; + /** + * Little to no thinking. + */ + ReinforcementTuningThinkingLevel["MINIMAL"] = "MINIMAL"; + /** + * High thinking level. + */ + ReinforcementTuningThinkingLevel["HIGH"] = "HIGH"; +})(ReinforcementTuningThinkingLevel || (ReinforcementTuningThinkingLevel = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Output only. The detail state of the tuning job (while the overall `JobState` is running). This enum is not supported in Gemini API. */ +var TuningJobState; +(function (TuningJobState) { + /** + * Default tuning job state. + */ + TuningJobState["TUNING_JOB_STATE_UNSPECIFIED"] = "TUNING_JOB_STATE_UNSPECIFIED"; + /** + * Tuning job is waiting for job quota. + */ + TuningJobState["TUNING_JOB_STATE_WAITING_FOR_QUOTA"] = "TUNING_JOB_STATE_WAITING_FOR_QUOTA"; + /** + * Tuning job is validating the dataset. + */ + TuningJobState["TUNING_JOB_STATE_PROCESSING_DATASET"] = "TUNING_JOB_STATE_PROCESSING_DATASET"; + /** + * Tuning job is waiting for hardware capacity. + */ + TuningJobState["TUNING_JOB_STATE_WAITING_FOR_CAPACITY"] = "TUNING_JOB_STATE_WAITING_FOR_CAPACITY"; + /** + * Tuning job is running. + */ + TuningJobState["TUNING_JOB_STATE_TUNING"] = "TUNING_JOB_STATE_TUNING"; + /** + * Tuning job is doing some post processing steps. + */ + TuningJobState["TUNING_JOB_STATE_POST_PROCESSING"] = "TUNING_JOB_STATE_POST_PROCESSING"; +})(TuningJobState || (TuningJobState = {})); +/** Aggregation metric. This enum is not supported in Gemini API. */ +var AggregationMetric; +(function (AggregationMetric) { + /** + * Unspecified aggregation metric. + */ + AggregationMetric["AGGREGATION_METRIC_UNSPECIFIED"] = "AGGREGATION_METRIC_UNSPECIFIED"; + /** + * Average aggregation metric. Not supported for Pairwise metric. + */ + AggregationMetric["AVERAGE"] = "AVERAGE"; + /** + * Mode aggregation metric. + */ + AggregationMetric["MODE"] = "MODE"; + /** + * Standard deviation aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["STANDARD_DEVIATION"] = "STANDARD_DEVIATION"; + /** + * Variance aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["VARIANCE"] = "VARIANCE"; + /** + * Minimum aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["MINIMUM"] = "MINIMUM"; + /** + * Maximum aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["MAXIMUM"] = "MAXIMUM"; + /** + * Median aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["MEDIAN"] = "MEDIAN"; + /** + * 90th percentile aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["PERCENTILE_P90"] = "PERCENTILE_P90"; + /** + * 95th percentile aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["PERCENTILE_P95"] = "PERCENTILE_P95"; + /** + * 99th percentile aggregation metric. Not supported for pairwise metric. + */ + AggregationMetric["PERCENTILE_P99"] = "PERCENTILE_P99"; +})(AggregationMetric || (AggregationMetric = {})); +/** Output only. Pairwise metric choice. This enum is not supported in Gemini API. */ +var PairwiseChoice; +(function (PairwiseChoice) { + /** + * Unspecified prediction choice. + */ + PairwiseChoice["PAIRWISE_CHOICE_UNSPECIFIED"] = "PAIRWISE_CHOICE_UNSPECIFIED"; + /** + * Baseline prediction wins + */ + PairwiseChoice["BASELINE"] = "BASELINE"; + /** + * Candidate prediction wins + */ + PairwiseChoice["CANDIDATE"] = "CANDIDATE"; + /** + * Winner cannot be determined + */ + PairwiseChoice["TIE"] = "TIE"; +})(PairwiseChoice || (PairwiseChoice = {})); +/** The orientation of the video. Defaults to LANDSCAPE. This enum is not supported in Gemini API. */ +var VideoOrientation; +(function (VideoOrientation) { + /** + * Unspecified video orientation. Defaults to landscape. + */ + VideoOrientation["VIDEO_ORIENTATION_UNSPECIFIED"] = "VIDEO_ORIENTATION_UNSPECIFIED"; + /** + * Landscape orientation (e.g. 16:9, 1280x720). + */ + VideoOrientation["LANDSCAPE"] = "LANDSCAPE"; + /** + * Portrait orientation (e.g. 9:16, 720x1280). + */ + VideoOrientation["PORTRAIT"] = "PORTRAIT"; +})(VideoOrientation || (VideoOrientation = {})); +/** The speed of the tuning job. Only supported for Veo 3.0 models. This enum is not supported in Gemini API. */ +var TuningSpeed; +(function (TuningSpeed) { + /** + * The default / unset value. For Veo 3.0 models, this defaults to FAST. + */ + TuningSpeed["TUNING_SPEED_UNSPECIFIED"] = "TUNING_SPEED_UNSPECIFIED"; + /** + * Regular tuning speed. + */ + TuningSpeed["REGULAR"] = "REGULAR"; + /** + * Fast tuning speed. + */ + TuningSpeed["FAST"] = "FAST"; +})(TuningSpeed || (TuningSpeed = {})); +/** The tuning task for Veo. This enum is not supported in Gemini API. */ +var TuningTask; +(function (TuningTask) { + /** + * Default value. This value is unused. + */ + TuningTask["TUNING_TASK_UNSPECIFIED"] = "TUNING_TASK_UNSPECIFIED"; + /** + * Tuning task for image to video. + */ + TuningTask["TUNING_TASK_I2V"] = "TUNING_TASK_I2V"; + /** + * Tuning task for text to video. + */ + TuningTask["TUNING_TASK_T2V"] = "TUNING_TASK_T2V"; + /** + * Tuning task for reference to video. + */ + TuningTask["TUNING_TASK_R2V"] = "TUNING_TASK_R2V"; +})(TuningTask || (TuningTask = {})); +/** Output only. Current state of the `Document`. This enum is not supported in Vertex AI. */ +var DocumentState; +(function (DocumentState) { + /** + * The default value. This value is used if the state is omitted. + */ + DocumentState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + /** + * Some `Chunks` of the `Document` are being processed (embedding and vector storage). + */ + DocumentState["STATE_PENDING"] = "STATE_PENDING"; + /** + * All `Chunks` of the `Document` is processed and available for querying. + */ + DocumentState["STATE_ACTIVE"] = "STATE_ACTIVE"; + /** + * Some `Chunks` of the `Document` failed processing. + */ + DocumentState["STATE_FAILED"] = "STATE_FAILED"; +})(DocumentState || (DocumentState = {})); +/** Pricing and performance service tier. */ +var ServiceTier; +(function (ServiceTier) { + /** + * Default service tier, which is standard. + */ + ServiceTier["UNSPECIFIED"] = "unspecified"; + /** + * Flex service tier. + */ + ServiceTier["FLEX"] = "flex"; + /** + * Standard service tier. + */ + ServiceTier["STANDARD"] = "standard"; + /** + * Priority service tier. + */ + ServiceTier["PRIORITY"] = "priority"; +})(ServiceTier || (ServiceTier = {})); +/** How the model processes input media for understanding. */ +var MediaProcessing; +(function (MediaProcessing) { + /** + * Default. Uses model-specific processing + */ + MediaProcessing["MEDIA_PROCESSING_UNSPECIFIED"] = "MEDIA_PROCESSING_UNSPECIFIED"; + /** + * Fixed-rate frame extraction. All frames placed in context. + */ + MediaProcessing["STATIC"] = "STATIC"; + /** + * Model-driven dynamic navigation. Recommended for most use cases. + */ + MediaProcessing["AGENTIC"] = "AGENTIC"; +})(MediaProcessing || (MediaProcessing = {})); +/** The tokenization quality used for given media. */ +var PartMediaResolutionLevel; +(function (PartMediaResolutionLevel) { + /** + * Media resolution has not been set. + */ + PartMediaResolutionLevel["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low. + */ + PartMediaResolutionLevel["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium. + */ + PartMediaResolutionLevel["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high. + */ + PartMediaResolutionLevel["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; + /** + * Media resolution set to ultra high. + */ + PartMediaResolutionLevel["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH"; +})(PartMediaResolutionLevel || (PartMediaResolutionLevel = {})); +/** The type of tool in the function call. */ +var ToolType; +(function (ToolType) { + /** + * Unspecified tool type. + */ + ToolType["TOOL_TYPE_UNSPECIFIED"] = "TOOL_TYPE_UNSPECIFIED"; + /** + * Google search tool, maps to Tool.google_search.search_types.web_search. + */ + ToolType["GOOGLE_SEARCH_WEB"] = "GOOGLE_SEARCH_WEB"; + /** + * Image search tool, maps to Tool.google_search.search_types.image_search. + */ + ToolType["GOOGLE_SEARCH_IMAGE"] = "GOOGLE_SEARCH_IMAGE"; + /** + * URL context tool, maps to Tool.url_context. + */ + ToolType["URL_CONTEXT"] = "URL_CONTEXT"; + /** + * Google maps tool, maps to Tool.google_maps. + */ + ToolType["GOOGLE_MAPS"] = "GOOGLE_MAPS"; + /** + * File search tool, maps to Tool.file_search. + */ + ToolType["FILE_SEARCH"] = "FILE_SEARCH"; + /** + * Media processing tool. + */ + ToolType["MEDIA_PROCESSING"] = "MEDIA_PROCESSING"; +})(ToolType || (ToolType = {})); +/** Resource scope. */ +var ResourceScope; +(function (ResourceScope) { + /** + * When setting base_url, this value configures resource scope to be the collection. + The resource name will not include api version, project, or location. + For example, if base_url is set to "https://aiplatform.googleapis.com", + then the resource name for a Model would be + "https://aiplatform.googleapis.com/publishers/google/models/gemini-3-pro-preview + */ + ResourceScope["COLLECTION"] = "COLLECTION"; +})(ResourceScope || (ResourceScope = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Enum representing the Gemini Enterprise Agent Platform embedding API to use. */ +var EmbeddingApiType; +(function (EmbeddingApiType) { + /** + * predict API endpoint (default) + */ + EmbeddingApiType["PREDICT"] = "PREDICT"; + /** + * embedContent API Endpoint + */ + EmbeddingApiType["EMBED_CONTENT"] = "EMBED_CONTENT"; +})(EmbeddingApiType || (EmbeddingApiType = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +var VideoGenerationReferenceType; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {})); +/** Enum for the mask mode of a video generation mask. */ +var VideoGenerationMaskMode; +(function (VideoGenerationMaskMode) { + /** + * The image mask contains a masked rectangular region which is + applied on the first frame of the input video. The object described in + the prompt is inserted into this region and will appear in subsequent + frames. + */ + VideoGenerationMaskMode["INSERT"] = "INSERT"; + /** + * The image mask is used to determine an object in the + first video frame to track. This object is removed from the video. + */ + VideoGenerationMaskMode["REMOVE"] = "REMOVE"; + /** + * The image mask is used to determine a region in the + video. Objects in this region will be removed. + */ + VideoGenerationMaskMode["REMOVE_STATIC"] = "REMOVE_STATIC"; + /** + * The image mask contains a masked rectangular region where + the input video will go. The remaining area will be generated. Video + masks are not supported. + */ + VideoGenerationMaskMode["OUTPAINT"] = "OUTPAINT"; +})(VideoGenerationMaskMode || (VideoGenerationMaskMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** Resize mode for the image input for video generation. */ +var ImageResizeMode; +(function (ImageResizeMode) { + /** + * Crop the image to fit the correct aspect ratio (so we lose parts + of the image in the process). + */ + ImageResizeMode["CROP"] = "CROP"; + /** + * Pad the image to fit the correct aspect ratio (so we don't lose + any parts of the image in the process). + */ + ImageResizeMode["PAD"] = "PAD"; +})(ImageResizeMode || (ImageResizeMode = {})); +/** Enum representing the tuning method. */ +var TuningMethod; +(function (TuningMethod) { + /** + * Supervised fine tuning. + */ + TuningMethod["SUPERVISED_FINE_TUNING"] = "SUPERVISED_FINE_TUNING"; + /** + * Preference optimization tuning. + */ + TuningMethod["PREFERENCE_TUNING"] = "PREFERENCE_TUNING"; + /** + * Distillation tuning. + */ + TuningMethod["DISTILLATION"] = "DISTILLATION"; + /** + * Reinforcement tuning. + */ + TuningMethod["REINFORCEMENT_TUNING"] = "REINFORCEMENT_TUNING"; +})(TuningMethod || (TuningMethod = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; + FileSource["REGISTERED"] = "REGISTERED"; +})(FileSource || (FileSource = {})); +/** The reason why the turn is complete. */ +var TurnCompleteReason; +(function (TurnCompleteReason) { + /** + * Default value. Reason is unspecified. + */ + TurnCompleteReason["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED"; + /** + * The function call generated by the model is invalid. + */ + TurnCompleteReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * The response is rejected by the model. + */ + TurnCompleteReason["RESPONSE_REJECTED"] = "RESPONSE_REJECTED"; + /** + * Needs more input from the user. + */ + TurnCompleteReason["NEED_MORE_INPUT"] = "NEED_MORE_INPUT"; + /** + * Input content is prohibited. + */ + TurnCompleteReason["PROHIBITED_INPUT_CONTENT"] = "PROHIBITED_INPUT_CONTENT"; + /** + * Input image contains prohibited content. + */ + TurnCompleteReason["IMAGE_PROHIBITED_INPUT_CONTENT"] = "IMAGE_PROHIBITED_INPUT_CONTENT"; + /** + * Input text contains prominent person reference. + */ + TurnCompleteReason["INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED"] = "INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED"; + /** + * Input image contains celebrity. + */ + TurnCompleteReason["INPUT_IMAGE_CELEBRITY"] = "INPUT_IMAGE_CELEBRITY"; + /** + * Input image contains photo realistic child. + */ + TurnCompleteReason["INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED"] = "INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED"; + /** + * Input text contains NCII content. + */ + TurnCompleteReason["INPUT_TEXT_NCII_PROHIBITED"] = "INPUT_TEXT_NCII_PROHIBITED"; + /** + * Other input safety issue. + */ + TurnCompleteReason["INPUT_OTHER"] = "INPUT_OTHER"; + /** + * Input contains IP violation. + */ + TurnCompleteReason["INPUT_IP_PROHIBITED"] = "INPUT_IP_PROHIBITED"; + /** + * Input matched blocklist. + */ + TurnCompleteReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Input is unsafe for image generation. + */ + TurnCompleteReason["UNSAFE_PROMPT_FOR_IMAGE_GENERATION"] = "UNSAFE_PROMPT_FOR_IMAGE_GENERATION"; + /** + * Generated image failed safety check. + */ + TurnCompleteReason["GENERATED_IMAGE_SAFETY"] = "GENERATED_IMAGE_SAFETY"; + /** + * Generated content failed safety check. + */ + TurnCompleteReason["GENERATED_CONTENT_SAFETY"] = "GENERATED_CONTENT_SAFETY"; + /** + * Generated audio failed safety check. + */ + TurnCompleteReason["GENERATED_AUDIO_SAFETY"] = "GENERATED_AUDIO_SAFETY"; + /** + * Generated video failed safety check. + */ + TurnCompleteReason["GENERATED_VIDEO_SAFETY"] = "GENERATED_VIDEO_SAFETY"; + /** + * Generated content is prohibited. + */ + TurnCompleteReason["GENERATED_CONTENT_PROHIBITED"] = "GENERATED_CONTENT_PROHIBITED"; + /** + * Generated content matched blocklist. + */ + TurnCompleteReason["GENERATED_CONTENT_BLOCKLIST"] = "GENERATED_CONTENT_BLOCKLIST"; + /** + * Generated image is prohibited. + */ + TurnCompleteReason["GENERATED_IMAGE_PROHIBITED"] = "GENERATED_IMAGE_PROHIBITED"; + /** + * Generated image contains celebrity. + */ + TurnCompleteReason["GENERATED_IMAGE_CELEBRITY"] = "GENERATED_IMAGE_CELEBRITY"; + /** + * Generated image contains prominent people detected by rewriter. + */ + TurnCompleteReason["GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER"] = "GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER"; + /** + * Generated image contains identifiable people. + */ + TurnCompleteReason["GENERATED_IMAGE_IDENTIFIABLE_PEOPLE"] = "GENERATED_IMAGE_IDENTIFIABLE_PEOPLE"; + /** + * Generated image contains minors. + */ + TurnCompleteReason["GENERATED_IMAGE_MINORS"] = "GENERATED_IMAGE_MINORS"; + /** + * Generated image contains IP violation. + */ + TurnCompleteReason["OUTPUT_IMAGE_IP_PROHIBITED"] = "OUTPUT_IMAGE_IP_PROHIBITED"; + /** + * Other generated content issue. + */ + TurnCompleteReason["GENERATED_OTHER"] = "GENERATED_OTHER"; + /** + * Max regeneration attempts reached. + */ + TurnCompleteReason["MAX_REGENERATION_REACHED"] = "MAX_REGENERATION_REACHED"; +})(TurnCompleteReason || (TurnCompleteReason = {})); +/** The different activity states of the live session. */ +var InteractionStatus; +(function (InteractionStatus) { + /** + * Unspecified interaction status. + */ + InteractionStatus["INTERACTION_STATUS_UNSPECIFIED"] = "INTERACTION_STATUS_UNSPECIFIED"; + /** + * The server is still actively processing user input or running background reasoning. More model output may follow. + */ + InteractionStatus["IN_PROGRESS"] = "IN_PROGRESS"; + /** + * Deprecated: Use IDLE instead. + */ + InteractionStatus["REQUIRES_ACTION"] = "REQUIRES_ACTION"; + /** + * The server has completed all processing and background reasoning. + */ + InteractionStatus["IDLE"] = "IDLE"; +})(InteractionStatus || (InteractionStatus = {})); +/** The type of the VAD signal. */ +var VadSignalType; +(function (VadSignalType) { + /** + * The default is VAD_SIGNAL_TYPE_UNSPECIFIED. + */ + VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED"; + /** + * Start of sentence signal. + */ + VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS"; + /** + * End of sentence signal. + */ + VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS"; +})(VadSignalType || (VadSignalType = {})); +/** The type of the voice activity signal. */ +var VoiceActivityType; +(function (VoiceActivityType) { + /** + * The default is VOICE_ACTIVITY_TYPE_UNSPECIFIED. + */ + VoiceActivityType["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * Start of sentence signal. + */ + VoiceActivityType["ACTIVITY_START"] = "ACTIVITY_START"; + /** + * End of sentence signal. + */ + VoiceActivityType["ACTIVITY_END"] = "ACTIVITY_END"; +})(VoiceActivityType || (VoiceActivityType = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW for Gemini Enterprise Agent Platform and START_SENSITIVITY_HIGH for Gemini Live. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW for Gemini Enterprise Agent Platform and END_SENSITIVITY_HIGH for Gemini Live. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; + /** + * Includes audio activity and all video since the last turn. With automatic activity detection, audio activity means speech and excludes silence. + */ + TurnCoverage["TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"] = "TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"; +})(TurnCoverage || (TurnCoverage = {})); +/** Transcription mode. */ +var AudioTranscriptionConfigMode; +(function (AudioTranscriptionConfigMode) { + /** + * Unspecified transcription mode. + */ + AudioTranscriptionConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Verbatim transcription mode. + */ + AudioTranscriptionConfigMode["VERBATIM"] = "VERBATIM"; + /** + * Smart transcription mode. + */ + AudioTranscriptionConfigMode["SMART"] = "SMART"; +})(AudioTranscriptionConfigMode || (AudioTranscriptionConfigMode = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** The output from a server-side `ToolCall` execution. + +This message contains the results of a tool invocation that was initiated by a +`ToolCall` from the model. The client should pass this `ToolResponse` back to +the API in a subsequent turn within a `Content` message, along with the +corresponding `ToolCall`. */ +class ToolResponse { +} +/** URI based data for function response. This data type is not supported in Gemini API. */ +class FunctionResponseFileData { +} +/** Raw media bytes for function response. Text should not be sent as raw bytes, use the 'text' field. */ +class FunctionResponseBlob { +} +/** A datatype containing media that is part of a `FunctionResponse` message. A `FunctionResponsePart` consists of data which has an associated datatype. A `FunctionResponsePart` can only contain one of the accepted types in `FunctionResponsePart.data`. A `FunctionResponsePart` must have a fixed IANA MIME type identifying the type and subtype of the media if the `inline_data` field is filled with raw bytes. */ +class FunctionResponsePart { +} +/** + * Creates a `FunctionResponsePart` object from a `base64` encoded `string`. + */ +function createFunctionResponsePartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `FunctionResponsePart` object from a `URI` string. + */ +function createFunctionResponsePartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** The result output from a FunctionCall that contains a string representing the FunctionDeclaration.name and a structured JSON object containing any output from the function is used as context to the model. This should contain the result of a `FunctionCall` made based on model prediction. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType, mediaResolution) { + return Object.assign({ fileData: { + fileUri: uri, + mimeType: mimeType, + } }, (mediaResolution && { mediaResolution: { level: mediaResolution } })); +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response, parts = []) { + return { + functionResponse: Object.assign({ id: id, name: name, response: response }, (parts.length > 0 && { parts })), + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType, mediaResolution) { + return Object.assign({ inlineData: { + data: data, + mimeType: mimeType, + } }, (mediaResolution && { mediaResolution: { level: mediaResolution } })); +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. Note: This is sent only in the first stream chunk and only if no candidates were generated due to content violations. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about the content generation request and response. This message provides a detailed breakdown of token usage and other relevant metrics. This data type is not supported in Gemini API. */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldName !== 'thoughtSignature' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Configuration for audio-specific output formatting. */ +class AudioResponseFormat { +} +/** Configuration for image-specific output formatting. */ +class ImageResponseFormat { +} +/** Configuration for text-specific output formatting. */ +class TextResponseFormat { +} +/** Configuration for video-specific output formatting. This data type is not supported in Gemini API. */ +class VideoResponseFormat { +} +/** Configuration for the model to configure output formatting and delivery. This data type is not supported in Gemini API. */ +class ResponseFormat { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + */ + _fromAPIResponse({ apiResponse, _isVertexAI, }) { + const operation = new GenerateVideosOperation(); + let response; + const op = apiResponse; + if (_isVertexAI) { + response = generateVideosOperationFromVertex$1(op); + } + else { + response = generateVideosOperationFromMldev$1(op); + } + Object.assign(operation, response); + return operation; + } +} +/** Defines how to parse sample response config for reinforcement tuning. The parsed response (i.e., substring) will be passed to the reward functions. For example, the input prompt might be: > "Perform step-by-step thoughts first to problem A, finally output answer in the block." The sample response from the model under tuning might look like: > "Yes" Here, users can define the following parse config: ``` { "parseType": "REGEX_EXTRACT", "regexExtractExpression": ".*(.*?)" } ``` The resulting parsed response would be `"Yes"` and will be passed to the reward functions for evaluating rewards. This data type is not supported in Gemini API. */ +class ReinforcementTuningParseResponseConfig { +} +/** Scores responses by directly converting the parsed autorater response to a float reward. Note: Reward is clipped to be within `[-1, 1]`, i.e., `reward = max(min(reward, 1.0), -1.0)`. This data type is not supported in Gemini API. */ +class ReinforcementTuningAutoraterScorerParsedResponseConversionScorer { +} +/** The results from an evaluation run performed by the EvaluationService. This data type is not supported in Gemini API. */ +class EvaluateDatasetResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for tunings.cancel method. */ +class CancelTuningJobResponse { +} +/** Response for the validate_reward method. + +Contains the computed reward for a reinforcement tuning reward +configuration. */ +class ValidateRewardResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Config for documents.list return value. */ +class ListDocumentsResponse { +} +/** Config for file_search_stores.list return value. */ +class ListFileSearchStoresResponse { +} +/** Response for the resumable upload method. */ +class UploadToFileSearchStoreResumableResponse { +} +/** Response for ImportFile to import a File API file with a file search store. */ +class ImportFileResponse { +} +/** Long-running operation for importing a file to a FileSearchStore. */ +class ImportFileOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + */ + _fromAPIResponse({ apiResponse, _isVertexAI, }) { + const operation = new ImportFileOperation(); + const op = apiResponse; + const response = importFileOperationFromMldev$1(op); + Object.assign(operation, response); + return operation; + } +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Response for the _register file method. */ +class RegisterFilesResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for `response` parameter. */ +class SingleEmbedContentResponse { +} +/** Config for `inlined_embedding_responses` parameter. */ +class InlinedEmbedContentResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + +A raw reference image represents the base image to edit, provided by the user. +It can optionally be provided in addition to a mask reference image or +a style reference image. */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + +This encapsulates either a mask image provided by the user and configs for +the user provided mask, or only config parameters for the model to generate +a mask. + +A mask image is an image whose non-zero values indicate where to edit the base +image. If the user provides a mask image, the mask must be in the same +dimensions as the raw image. */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + +The image of the control reference image is either a control image provided +by the user, or a regular image which the backend will use to generate a +control image of. In the case of the latter, the +enable_control_image_computation field in the config should be set to True. + +A control image is an image that represents a sketch image of areas for the +model to fill in based on the prompt. */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + +This encapsulates a style reference image provided by the user, and +additionally optional config parameters for the style reference image. + +A raw reference image can also be provided as a destination for the style to +be applied to. */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + +This encapsulates a subject reference image provided by the user, and +additionally optional config parameters for the subject reference image. + +A raw reference image can also be provided as a destination for the subject to +be applied to. */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A content reference image. + +A content reference image represents a subject to reference (ex. person, +product, animal) provided by the user. It can optionally be provided in +addition to a style reference image (ex. background, style reference). */ +class ContentReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTENT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + +Individual `FunctionResponse` objects are matched to the respective +`FunctionCall` objects by the `id` field. + +Note that in the unary and server-streaming GenerateContent APIs function +calling happens by exchanging the `Content` parts, while in the bidi +GenerateContent APIs function calling happens over this dedicated set of +messages. */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} +/** The response when long-running operation for uploading a file to a FileSearchStore complete. */ +class UploadToFileSearchStoreResponse { +} +/** Long-running operation for uploading a file to a FileSearchStore. */ +class UploadToFileSearchStoreOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + */ + _fromAPIResponse({ apiResponse, _isVertexAI, }) { + const operation = new UploadToFileSearchStoreOperation(); + const op = apiResponse; + const response = uploadToFileSearchStoreOperationFromMldev(op); + Object.assign(operation, response); + return operation; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (model.includes('..') || model.includes('?') || model.includes('&')) { + throw new Error('invalid model parameter'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tJsonSchema(schema) { + return schema; +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(client, src) { + let sourceObj; + if (typeof src === 'string') { + if (client.isVertexAI()) { + if (src.startsWith('gs://')) { + sourceObj = { format: 'jsonl', gcsUri: [src] }; + } + else if (src.startsWith('bq://')) { + sourceObj = { format: 'bigquery', bigqueryUri: src }; + } + else if (/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(src)) { + sourceObj = { format: 'vertex-dataset', vertexDatasetName: src }; + } + else { + throw new Error(`Unsupported string source for Vertex AI: ${src}`); + } + } + else { + // MLDEV + if (src.startsWith('files/')) { + sourceObj = { fileName: src }; // Default to fileName for string input + } + else { + throw new Error(`Unsupported string source for Gemini API: ${src}`); + } + } + } + else if (Array.isArray(src)) { + if (client.isVertexAI()) { + throw new Error('InlinedRequest[] is not supported in Vertex AI.'); + } + sourceObj = { inlinedRequests: src }; + } + else { + // It's already a BatchJobSource object + sourceObj = src; + } + // Validation logic + const vertexSourcesCount = [ + sourceObj.gcsUri, + sourceObj.bigqueryUri, + sourceObj.vertexDatasetName, + ].filter(Boolean).length; + const mldevSourcesCount = [ + sourceObj.inlinedRequests, + sourceObj.fileName, + ].filter(Boolean).length; + if (client.isVertexAI()) { + if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) { + throw new Error('Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.'); + } + } + else { + // MLDEV + if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) { + throw new Error('Exactly one of `inlinedRequests`, `fileName`, ' + + 'must be set for Gemini API.'); + } + } + return sourceObj; +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tRecvBatchJobDestination(dest) { + // Ensure dest is a non-null object before proceeding. + if (typeof dest !== 'object' || dest === null) { + // If the input is not an object, it cannot be a valid BatchJobDestination + // based on the operations performed. Return it cast, or handle as an error. + // Casting an empty object might be a safe default. + return {}; + } + // Cast to Record to allow string property access. + const obj = dest; + // Safely access nested properties. + const inlineResponsesVal = obj['inlinedResponses']; + if (typeof inlineResponsesVal !== 'object' || inlineResponsesVal === null) { + return dest; + } + const inlineResponsesObj = inlineResponsesVal; + const responsesArray = inlineResponsesObj['inlinedResponses']; + if (!Array.isArray(responsesArray) || responsesArray.length === 0) { + return dest; + } + // Check if any response has the 'embedding' property. + let hasEmbedding = false; + for (const responseItem of responsesArray) { + if (typeof responseItem !== 'object' || responseItem === null) { + continue; + } + const responseItemObj = responseItem; + const responseVal = responseItemObj['response']; + if (typeof responseVal !== 'object' || responseVal === null) { + continue; + } + const responseObj = responseVal; + // Check for the existence of the 'embedding' key. + if (responseObj['embedding'] !== undefined) { + hasEmbedding = true; + break; + } + } + // Perform the transformation if an embedding was found. + if (hasEmbedding) { + obj['inlinedEmbedContentResponses'] = obj['inlinedResponses']; + delete obj['inlinedResponses']; + } + // Cast the (potentially) modified object to the target type. + return dest; +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_RUNNING') { + return 'JOB_STATE_RUNNING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else if (stateString === 'BATCH_STATE_EXPIRED') { + return 'JOB_STATE_EXPIRED'; + } + else { + return stateString; + } +} +function tIsVertexEmbedContentModel(model) { + return ((model.includes('gemini') && model !== 'gemini-embedding-001') || + model.includes('maas')); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function authConfigToMldev$4(fromObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject, ['apiKey']); + if (fromApiKey != null) { + setValueByPath(toObject, ['apiKey'], fromApiKey); + } + if (getValueByPath(fromObject, ['apiKeyConfig']) !== undefined) { + throw new Error('apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['authType']) !== undefined) { + throw new Error('authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['googleServiceAccountConfig']) !== + undefined) { + throw new Error('googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['httpBasicAuthConfig']) !== undefined) { + throw new Error('httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oauthConfig']) !== undefined) { + throw new Error('oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oidcConfig']) !== undefined) { + throw new Error('oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + const fromInlinedEmbedContentResponses = getValueByPath(fromObject, [ + 'inlinedEmbedContentResponses', + 'inlinedResponses', + ]); + if (fromInlinedEmbedContentResponses != null) { + let transformedList = fromInlinedEmbedContentResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['inlinedEmbedContentResponses'], transformedList); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + const fromVertexDataset = getValueByPath(fromObject, [ + 'vertexMultimodalDatasetDestination', + ]); + if (fromVertexDataset != null) { + setValueByPath(toObject, ['vertexDataset'], vertexMultimodalDatasetDestinationFromVertex(fromVertexDataset)); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + const fromVertexDataset = getValueByPath(fromObject, [ + 'vertexDataset', + ]); + if (fromVertexDataset != null) { + setValueByPath(toObject, ['vertexMultimodalDatasetDestination'], vertexMultimodalDatasetDestinationToVertex(fromVertexDataset)); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['inlinedEmbedContentResponses']) !== + undefined) { + throw new Error('inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest))); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest))); + } + const fromOutputInfo = getValueByPath(fromObject, ['outputInfo']); + if (fromOutputInfo != null) { + setValueByPath(toObject, ['outputInfo'], fromOutputInfo); + } + const fromCompletionStats = getValueByPath(fromObject, [ + 'completionStats', + ]); + if (fromCompletionStats != null) { + setValueByPath(toObject, ['completionStats'], fromCompletionStats); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + const fromVertexDatasetName = getValueByPath(fromObject, [ + 'vertexMultimodalDatasetSource', + 'datasetName', + ]); + if (fromVertexDatasetName != null) { + setValueByPath(toObject, ['vertexDatasetName'], fromVertexDatasetName); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['vertexDatasetName']) !== undefined) { + throw new Error('vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + const fromVertexDatasetName = getValueByPath(fromObject, [ + 'vertexDatasetName', + ]); + if (fromVertexDatasetName != null) { + setValueByPath(toObject, ['vertexMultimodalDatasetSource', 'datasetName'], fromVertexDatasetName); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], fromContent); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + let transformedList = fromSafetyRatings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['safetyRatings'], transformedList); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], fromUrlContextMetadata); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + let transformedList = fromCitations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['citations'], transformedList); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromWebhookConfig = getValueByPath(fromObject, [ + 'webhookConfig', + ]); + if (parentObject !== undefined && fromWebhookConfig != null) { + setValueByPath(parentObject, ['batch', 'webhookConfig'], fromWebhookConfig); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + if (getValueByPath(fromObject, ['webhookConfig']) !== undefined) { + throw new Error('webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createBatchJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createBatchJobConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function createEmbeddingsBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + return toObject; +} +function createEmbeddingsBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], embeddingsBatchJobSourceToMldev(apiClient, fromSrc)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function embedContentBatchToMldev(apiClient, fromObject) { + const toObject = {}; + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['requests[]', 'request', 'content'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['_self'], embedContentConfigToMldev$1(fromConfig, toObject)); + moveValueByPath(toObject, { 'requests[].*': 'requests[].request.*' }); + } + return toObject; +} +function embedContentConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['documentOcr']) !== undefined) { + throw new Error('documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['audioTrackExtraction']) !== undefined) { + throw new Error('audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function embeddingsBatchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['file_name'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + setValueByPath(toObject, ['requests'], embedContentBatchToMldev(apiClient, fromInlinedRequests)); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function functionCallToMldev$4(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + if (getValueByPath(fromObject, ['partialArgs']) !== undefined) { + throw new Error('partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['willContinue']) !== undefined) { + throw new Error('willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + if (getValueByPath(fromObject, ['streamFunctionCallArguments']) !== + undefined) { + throw new Error('streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromServiceTier = getValueByPath(fromObject, ['serviceTier']); + if (parentObject !== undefined && fromServiceTier != null) { + setValueByPath(parentObject, ['serviceTier'], fromServiceTier); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$3(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], tSpeechConfig(fromSpeechConfig)); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromImageConfig = getValueByPath(fromObject, ['imageConfig']); + if (fromImageConfig != null) { + setValueByPath(toObject, ['imageConfig'], imageConfigToMldev$1(fromImageConfig)); + } + const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [ + 'enableEnhancedCivicAnswers', + ]); + if (fromEnableEnhancedCivicAnswers != null) { + setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers); + } + if (getValueByPath(fromObject, ['modelArmorConfig']) !== undefined) { + throw new Error('modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + const fromModelStatus = getValueByPath(fromObject, ['modelStatus']); + if (fromModelStatus != null) { + setValueByPath(toObject, ['modelStatus'], fromModelStatus); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function googleMapsToMldev$4(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToMldev$4(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject, ['enableWidget']); + if (fromEnableWidget != null) { + setValueByPath(toObject, ['enableWidget'], fromEnableWidget); + } + if (getValueByPath(fromObject, ['groundingTypes']) !== undefined) { + throw new Error('groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['blockingConfidence']) !== undefined) { + throw new Error('blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSearchTypes = getValueByPath(fromObject, ['searchTypes']); + if (fromSearchTypes != null) { + setValueByPath(toObject, ['searchTypes'], fromSearchTypes); + } + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter); + } + return toObject; +} +function imageConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (fromAspectRatio != null) { + setValueByPath(toObject, ['aspectRatio'], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (fromImageSize != null) { + setValueByPath(toObject, ['imageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['personGeneration']) !== undefined) { + throw new Error('personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['outputMimeType']) !== undefined) { + throw new Error('outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['outputCompressionQuality']) !== + undefined) { + throw new Error('outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['imageOutputOptions']) !== undefined) { + throw new Error('imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['prominentPeople']) !== undefined) { + throw new Error('prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, getValueByPath(toObject, ['request'], {}))); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listBatchJobsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listBatchJobsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolResponse = getValueByPath(fromObject, ['toolResponse']); + if (fromToolResponse != null) { + setValueByPath(toObject, ['toolResponse'], fromToolResponse); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], functionCallToMldev$4(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromPartMetadata = getValueByPath(fromObject, ['partMetadata']); + if (fromPartMetadata != null) { + setValueByPath(toObject, ['partMetadata'], fromPartMetadata); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function safetySettingToMldev$3(fromObject) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig); + } + const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, ['includeServerSideToolInvocations']); + if (fromIncludeServerSideToolInvocations != null) { + setValueByPath(toObject, ['includeServerSideToolInvocations'], fromIncludeServerSideToolInvocations); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToMldev$4(fromGoogleMaps)); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], fromComputerUse); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['exaAiSearch']) !== undefined) { + throw new Error('exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject, ['parallelAiSearch']) !== undefined) { + throw new Error('parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + const fromFileSearch = getValueByPath(fromObject, ['fileSearch']); + if (fromFileSearch != null) { + setValueByPath(toObject, ['fileSearch'], fromFileSearch); + } + return toObject; +} +function vertexMultimodalDatasetDestinationFromVertex(fromObject) { + const toObject = {}; + const fromBigqueryDestination = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryDestination != null) { + setValueByPath(toObject, ['bigqueryDestination'], fromBigqueryDestination); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + return toObject; +} +function vertexMultimodalDatasetDestinationToVertex(fromObject) { + const toObject = {}; + const fromBigqueryDestination = getValueByPath(fromObject, [ + 'bigqueryDestination', + ]); + if (fromBigqueryDestination != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryDestination); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; + PagedItem["PAGED_ITEM_FILE_SEARCH_STORES"] = "fileSearchStores"; + PagedItem["PAGED_ITEM_DOCUMENTS"] = "documents"; + PagedItem["PAGED_ITEM_SKILLS"] = "skills"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists batch jobs. + * + * @param params - The parameters for the list request. + * @return - A pager of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + // Format destination if not provided + // Cast params.src as Vertex AI path does not handle InlinedRequest[] + params.config = this.formatDestination(params.src, params.config); + } + return this.createInternal(params); + }; + /** + * **Experimental** Creates an embedding batch job. + * + * @param params - The parameters for create embedding batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.createEmbeddings({ + * model: 'text-embedding-004', + * src: {fileName: 'files/my_embedding_input'}, + * }); + * console.log(response); + * ``` + */ + this.createEmbeddings = async (params) => { + console.warn('batches.createEmbeddings() is experimental and may change without notice.'); + if (this.apiClient.isVertexAI()) { + throw new Error('Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.'); + } + return this.createEmbeddingsInternal(params); + }; + } + // Helper function to handle inlined generate content requests + createInlinedGenerateContentRequest(params) { + const body = createBatchJobParametersToMldev(this.apiClient, // Use instance apiClient + params); + const urlParams = body['_url']; + const path = formatMap('{model}:batchGenerateContent', urlParams); + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = Object.assign({}, request); // Clone + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + return { path, body }; + } + // Helper function to get the first GCS URI + getGcsUri(src) { + if (typeof src === 'string') { + return src.startsWith('gs://') ? src : undefined; + } + if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) { + return src.gcsUri[0]; + } + return undefined; + } + // Helper function to get the BigQuery URI + getBigqueryUri(src) { + if (typeof src === 'string') { + return src.startsWith('bq://') ? src : undefined; + } + if (!Array.isArray(src)) { + return src.bigqueryUri; + } + return undefined; + } + // Function to format the destination configuration for Vertex AI + formatDestination(src, config) { + const newConfig = config ? Object.assign({}, config) : {}; + const timestampStr = Date.now().toString(); + if (!newConfig.displayName) { + newConfig.displayName = `genaiBatchJob_${timestampStr}`; + } + if (newConfig.dest === undefined) { + const gcsUri = this.getGcsUri(src); + const bigqueryUri = this.getBigqueryUri(src); + if (gcsUri) { + if (gcsUri.endsWith('.jsonl')) { + // For .jsonl files, remove suffix and add /dest + newConfig.dest = `${gcsUri.slice(0, -6)}/dest`; + } + else { + // Fallback for other GCS URIs + newConfig.dest = `${gcsUri}_dest_${timestampStr}`; + } + } + else if (bigqueryUri) { + newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.'); + } + } + return newConfig; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createEmbeddingsInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:asyncBatchEmbedContent', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function authConfigToMldev$3(fromObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject, ['apiKey']); + if (fromApiKey != null) { + setValueByPath(toObject, ['apiKey'], fromApiKey); + } + if (getValueByPath(fromObject, ['apiKeyConfig']) !== undefined) { + throw new Error('apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['authType']) !== undefined) { + throw new Error('authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['googleServiceAccountConfig']) !== + undefined) { + throw new Error('googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['httpBasicAuthConfig']) !== undefined) { + throw new Error('httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oauthConfig']) !== undefined) { + throw new Error('oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oidcConfig']) !== undefined) { + throw new Error('oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function computerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnablePromptInjectionDetection = getValueByPath(fromObject, [ + 'enablePromptInjectionDetection', + ]); + if (fromEnablePromptInjectionDetection != null) { + setValueByPath(toObject, ['enablePromptInjectionDetection'], fromEnablePromptInjectionDetection); + } + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + 'excludedPredefinedFunctions', + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath(toObject, ['excludedPredefinedFunctions'], fromExcludedPredefinedFunctions); + } + if (getValueByPath(fromObject, ['disabledSafetyPolicies']) !== undefined) { + throw new Error('disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function contentToVertex$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createCachedContentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createCachedContentConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function functionCallToMldev$3(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + if (getValueByPath(fromObject, ['partialArgs']) !== undefined) { + throw new Error('partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['willContinue']) !== undefined) { + throw new Error('willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + if (getValueByPath(fromObject, ['streamFunctionCallArguments']) !== + undefined) { + throw new Error('streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function googleMapsToMldev$3(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToMldev$3(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject, ['enableWidget']); + if (fromEnableWidget != null) { + setValueByPath(toObject, ['enableWidget'], fromEnableWidget); + } + if (getValueByPath(fromObject, ['groundingTypes']) !== undefined) { + throw new Error('groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['blockingConfidence']) !== undefined) { + throw new Error('blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSearchTypes = getValueByPath(fromObject, ['searchTypes']); + if (fromSearchTypes != null) { + setValueByPath(toObject, ['searchTypes'], fromSearchTypes); + } + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listCachedContentsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listCachedContentsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function mcpServerToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['name']) !== undefined) { + throw new Error('name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['streamableHttpTransport']) !== undefined) { + throw new Error('streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolResponse = getValueByPath(fromObject, ['toolResponse']); + if (fromToolResponse != null) { + setValueByPath(toObject, ['toolResponse'], fromToolResponse); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], functionCallToMldev$3(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromPartMetadata = getValueByPath(fromObject, ['partMetadata']); + if (fromPartMetadata != null) { + setValueByPath(toObject, ['partMetadata'], fromPartMetadata); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function partToVertex$3(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + if (getValueByPath(fromObject, ['toolCall']) !== undefined) { + throw new Error('toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['toolResponse']) !== undefined) { + throw new Error('toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fromFileData); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], fromInlineData); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + if (getValueByPath(fromObject, ['partMetadata']) !== undefined) { + throw new Error('partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig); + } + const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, ['includeServerSideToolInvocations']); + if (fromIncludeServerSideToolInvocations != null) { + setValueByPath(toObject, ['includeServerSideToolInvocations'], fromIncludeServerSideToolInvocations); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], fromFunctionCallingConfig); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig); + } + if (getValueByPath(fromObject, ['includeServerSideToolInvocations']) !== + undefined) { + throw new Error('includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToMldev$3(fromGoogleMaps)); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], fromComputerUse); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['exaAiSearch']) !== undefined) { + throw new Error('exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject, ['parallelAiSearch']) !== undefined) { + throw new Error('parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + const fromFileSearch = getValueByPath(fromObject, ['fileSearch']); + if (fromFileSearch != null) { + setValueByPath(toObject, ['fileSearch'], fromFileSearch); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], fromGoogleMaps); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return mcpServerToVertex$2(item); + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], computerUseToVertex$2(fromComputerUse)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], fromEnterpriseWebSearch); + } + const fromExaAiSearch = getValueByPath(fromObject, ['exaAiSearch']); + if (fromExaAiSearch != null) { + setValueByPath(toObject, ['exaAiSearch'], fromExaAiSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], fromGoogleSearch); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject, [ + 'parallelAiSearch', + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ['parallelAiSearch'], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + if (getValueByPath(fromObject, ['fileSearch']) !== undefined) { + throw new Error('fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + updateCachedContentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + updateCachedContentConfigToVertex(fromConfig, toObject); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached contents. + * + * @param params - The parameters for the list request. + * @return - A pager of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Gemini Enterprise Agent Platform reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _a, e_1, _b, _c; + var _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _a = streamResponse_1_1.done, !_a; _f = true) { + _c = streamResponse_1_1.value; + _f = false; + const chunk = _c; + if (isValidResponse(chunk)) { + const content = (_e = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_a && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fromFile); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + return toObject; +} +function internalRegisterFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromUris = getValueByPath(fromObject, ['uris']); + if (fromUris != null) { + setValueByPath(toObject, ['uris'], fromUris); + } + return toObject; +} +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listFilesConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function registerFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let Files$1 = class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists files. + * + * @param params - The parameters for the list request. + * @return - A pager of files. + * + * @example + * ```ts + * const files = await ai.files.list({config: {'pageSize': 2}}); + * for await (const file of files) { + * console.log(file); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Gemini Enterprise Agent Platform (previously known as Vertex AI). + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Some examples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Gemini Enterprise Agent Platform (previously known as Vertex AI) client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((resp) => { + return resp; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + /** + * Registers Google Cloud Storage files for use with the API. + * This method is only available in Node.js environments. + */ + async registerFiles(params) { + throw new Error('registerFiles is only supported in Node.js environments.'); + } + async _registerFiles(params) { + return this.registerFilesInternal(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async registerFilesInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = internalRegisterFilesParametersToMldev(params); + path = formatMap('files:register', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = registerFilesResponseFromMldev(apiResponse); + const typedResp = new RegisterFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function authConfigToMldev$2(fromObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject, ['apiKey']); + if (fromApiKey != null) { + setValueByPath(toObject, ['apiKey'], fromApiKey); + } + if (getValueByPath(fromObject, ['apiKeyConfig']) !== undefined) { + throw new Error('apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['authType']) !== undefined) { + throw new Error('authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['googleServiceAccountConfig']) !== + undefined) { + throw new Error('googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['httpBasicAuthConfig']) !== undefined) { + throw new Error('httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oauthConfig']) !== undefined) { + throw new Error('oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oidcConfig']) !== undefined) { + throw new Error('oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function computerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnablePromptInjectionDetection = getValueByPath(fromObject, [ + 'enablePromptInjectionDetection', + ]); + if (fromEnablePromptInjectionDetection != null) { + setValueByPath(toObject, ['enablePromptInjectionDetection'], fromEnablePromptInjectionDetection); + } + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + 'excludedPredefinedFunctions', + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath(toObject, ['excludedPredefinedFunctions'], fromExcludedPredefinedFunctions); + } + if (getValueByPath(fromObject, ['disabledSafetyPolicies']) !== undefined) { + throw new Error('disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function functionCallToMldev$2(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + if (getValueByPath(fromObject, ['partialArgs']) !== undefined) { + throw new Error('partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['willContinue']) !== undefined) { + throw new Error('willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generationConfigToVertex$1(fromObject) { + const toObject = {}; + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (fromEnableAffectiveDialog != null) { + setValueByPath(toObject, ['enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromResponseFormat = getValueByPath(fromObject, [ + 'responseFormat', + ]); + if (fromResponseFormat != null) { + let transformedList = fromResponseFormat; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['responseFormat'], transformedList); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], fromResponseSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex$1(fromSpeechConfig)); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + if (getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !== + undefined) { + throw new Error('enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['translationConfig']) !== undefined) { + throw new Error('translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function googleMapsToMldev$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToMldev$2(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject, ['enableWidget']); + if (fromEnableWidget != null) { + setValueByPath(toObject, ['enableWidget'], fromEnableWidget); + } + if (getValueByPath(fromObject, ['groundingTypes']) !== undefined) { + throw new Error('groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['blockingConfidence']) !== undefined) { + throw new Error('blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSearchTypes = getValueByPath(fromObject, ['searchTypes']); + if (fromSearchTypes != null) { + setValueByPath(toObject, ['searchTypes'], fromSearchTypes); + } + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], tLiveSpeechConfig(fromSpeechConfig)); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (parentObject !== undefined && fromThinkingConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'thinkingConfig'], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], fromInputAudioTranscription); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], fromOutputAudioTranscription); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity); + } + if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) { + throw new Error('explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromAvatarConfig = getValueByPath(fromObject, ['avatarConfig']); + if (parentObject !== undefined && fromAvatarConfig != null) { + setValueByPath(parentObject, ['setup', 'avatarConfig'], fromAvatarConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$2(item); + }); + } + setValueByPath(parentObject, ['setup', 'safetySettings'], transformedList); + } + const fromTranslationConfig = getValueByPath(fromObject, [ + 'translationConfig', + ]); + if (parentObject !== undefined && fromTranslationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'translationConfig'], fromTranslationConfig); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], generationConfigToVertex$1(fromGenerationConfig)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (parentObject !== undefined && fromThinkingConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'thinkingConfig'], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], fromSessionResumption); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], fromInputAudioTranscription); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], fromOutputAudioTranscription); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity); + } + const fromExplicitVadSignal = getValueByPath(fromObject, [ + 'explicitVadSignal', + ]); + if (parentObject !== undefined && fromExplicitVadSignal != null) { + setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal); + } + const fromAvatarConfig = getValueByPath(fromObject, ['avatarConfig']); + if (parentObject !== undefined && fromAvatarConfig != null) { + setValueByPath(parentObject, ['setup', 'avatarConfig'], fromAvatarConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ['setup', 'safetySettings'], transformedList); + } + const fromTranslationConfig = getValueByPath(fromObject, [ + 'translationConfig', + ]); + if (parentObject !== undefined && fromTranslationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'translationConfig'], fromTranslationConfig); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], fromMusicGenerationConfig); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + let transformedList = tBlobs(fromMedia); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return blobToMldev$2(item); + }); + } + setValueByPath(toObject, ['mediaChunks'], transformedList); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], blobToMldev$2(tAudioBlob(fromAudio))); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], blobToMldev$2(tImageBlob(fromVideo))); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], fromActivityStart); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], fromActivityEnd); + } + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + let transformedList = tBlobs(fromMedia); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mediaChunks'], transformedList); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], fromActivityStart); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], fromActivityEnd); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], fromServerContent); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], fromToolCallCancellation); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], fromGoAway); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate); + } + const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [ + 'voiceActivityDetectionSignal', + ]); + if (fromVoiceActivityDetectionSignal != null) { + setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal); + } + const fromVoiceActivity = getValueByPath(fromObject, [ + 'voiceActivity', + ]); + if (fromVoiceActivity != null) { + setValueByPath(toObject, ['voiceActivity'], voiceActivityFromVertex(fromVoiceActivity)); + } + return toObject; +} +function mcpServerToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['name']) !== undefined) { + throw new Error('name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['streamableHttpTransport']) !== undefined) { + throw new Error('streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function multiSpeakerVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToVertex$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolResponse = getValueByPath(fromObject, ['toolResponse']); + if (fromToolResponse != null) { + setValueByPath(toObject, ['toolResponse'], fromToolResponse); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], functionCallToMldev$2(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromPartMetadata = getValueByPath(fromObject, ['partMetadata']); + if (fromPartMetadata != null) { + setValueByPath(toObject, ['partMetadata'], fromPartMetadata); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + if (getValueByPath(fromObject, ['toolCall']) !== undefined) { + throw new Error('toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['toolResponse']) !== undefined) { + throw new Error('toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fromFileData); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], fromInlineData); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + if (getValueByPath(fromObject, ['partMetadata']) !== undefined) { + throw new Error('partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function replicatedVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromVoiceSampleAudio = getValueByPath(fromObject, [ + 'voiceSampleAudio', + ]); + if (fromVoiceSampleAudio != null) { + setValueByPath(toObject, ['voiceSampleAudio'], fromVoiceSampleAudio); + } + if (getValueByPath(fromObject, ['consentAudio']) !== undefined) { + throw new Error('consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['voiceConsentSignature']) !== undefined) { + throw new Error('voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function safetySettingToMldev$2(fromObject) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function speakerVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToVertex$1(fromMultiSpeakerVoiceConfig)); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToMldev$2(fromGoogleMaps)); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], fromComputerUse); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['exaAiSearch']) !== undefined) { + throw new Error('exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject, ['parallelAiSearch']) !== undefined) { + throw new Error('parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + const fromFileSearch = getValueByPath(fromObject, ['fileSearch']); + if (fromFileSearch != null) { + setValueByPath(toObject, ['fileSearch'], fromFileSearch); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], fromGoogleMaps); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return mcpServerToVertex$1(item); + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], computerUseToVertex$1(fromComputerUse)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], fromEnterpriseWebSearch); + } + const fromExaAiSearch = getValueByPath(fromObject, ['exaAiSearch']); + if (fromExaAiSearch != null) { + setValueByPath(toObject, ['exaAiSearch'], fromExaAiSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], fromGoogleSearch); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject, [ + 'parallelAiSearch', + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ['parallelAiSearch'], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + if (getValueByPath(fromObject, ['fileSearch']) !== undefined) { + throw new Error('fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function voiceActivityFromVertex(fromObject) { + const toObject = {}; + const fromVoiceActivityType = getValueByPath(fromObject, ['type']); + if (fromVoiceActivityType != null) { + setValueByPath(toObject, ['voiceActivityType'], fromVoiceActivityType); + } + const fromAudioOffset = getValueByPath(fromObject, ['audioOffset']); + if (fromAudioOffset != null) { + setValueByPath(toObject, ['audioOffset'], fromAudioOffset); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromReplicatedVoiceConfig = getValueByPath(fromObject, [ + 'replicatedVoiceConfig', + ]); + if (fromReplicatedVoiceConfig != null) { + setValueByPath(toObject, ['replicatedVoiceConfig'], replicatedVoiceConfigToVertex$1(fromReplicatedVoiceConfig)); + } + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], fromPrebuiltVoiceConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function authConfigToMldev$1(fromObject, _rootObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject, ['apiKey']); + if (fromApiKey != null) { + setValueByPath(toObject, ['apiKey'], fromApiKey); + } + if (getValueByPath(fromObject, ['apiKeyConfig']) !== undefined) { + throw new Error('apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['authType']) !== undefined) { + throw new Error('authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['googleServiceAccountConfig']) !== + undefined) { + throw new Error('googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['httpBasicAuthConfig']) !== undefined) { + throw new Error('httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oauthConfig']) !== undefined) { + throw new Error('oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oidcConfig']) !== undefined) { + throw new Error('oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function blobToMldev$1(fromObject, _rootObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function candidateFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], fromContent); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + let transformedList = fromSafetyRatings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['safetyRatings'], transformedList); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], fromUrlContextMetadata); + } + return toObject; +} +function citationMetadataFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + let transformedList = fromCitations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['citations'], transformedList); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + let transformedList = fromTokensInfo; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['tokensInfo'], transformedList); + } + return toObject; +} +function computerUseToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromEnablePromptInjectionDetection = getValueByPath(fromObject, [ + 'enablePromptInjectionDetection', + ]); + if (fromEnablePromptInjectionDetection != null) { + setValueByPath(toObject, ['enablePromptInjectionDetection'], fromEnablePromptInjectionDetection); + } + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + 'excludedPredefinedFunctions', + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath(toObject, ['excludedPredefinedFunctions'], fromExcludedPredefinedFunctions); + } + if (getValueByPath(fromObject, ['disabledSafetyPolicies']) !== undefined) { + throw new Error('disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromTokensDetails = getValueByPath(fromObject, [ + 'tokensDetails', + ]); + if (fromTokensDetails != null) { + let transformedList = fromTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['tokensDetails'], transformedList); + } + return toObject; +} +function contentToMldev$1(fromObject, rootObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function contentToVertex$1(fromObject, rootObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function countTokensConfigToMldev(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], generationConfigToVertex(fromGenerationConfig)); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + countTokensConfigToMldev(fromConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + countTokensConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + editImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function editImageResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['documentOcr']) !== undefined) { + throw new Error('documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['audioTrackExtraction']) !== undefined) { + throw new Error('audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + let discriminatorTaskType = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorTaskType === undefined) { + discriminatorTaskType = 'PREDICT'; + } + if (discriminatorTaskType === 'PREDICT') { + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + } + else if (discriminatorTaskType === 'EMBED_CONTENT') { + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['embedContentConfig', 'taskType'], fromTaskType); + } + } + let discriminatorTitle = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorTitle === undefined) { + discriminatorTitle = 'PREDICT'; + } + if (discriminatorTitle === 'PREDICT') { + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + } + else if (discriminatorTitle === 'EMBED_CONTENT') { + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['embedContentConfig', 'title'], fromTitle); + } + } + let discriminatorOutputDimensionality = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorOutputDimensionality === undefined) { + discriminatorOutputDimensionality = 'PREDICT'; + } + if (discriminatorOutputDimensionality === 'PREDICT') { + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + } + else if (discriminatorOutputDimensionality === 'EMBED_CONTENT') { + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['embedContentConfig', 'outputDimensionality'], fromOutputDimensionality); + } + } + let discriminatorMimeType = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorMimeType === undefined) { + discriminatorMimeType = 'PREDICT'; + } + if (discriminatorMimeType === 'PREDICT') { + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + } + let discriminatorAutoTruncate = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorAutoTruncate === undefined) { + discriminatorAutoTruncate = 'PREDICT'; + } + if (discriminatorAutoTruncate === 'PREDICT') { + const fromAutoTruncate = getValueByPath(fromObject, [ + 'autoTruncate', + ]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + } + else if (discriminatorAutoTruncate === 'EMBED_CONTENT') { + const fromAutoTruncate = getValueByPath(fromObject, [ + 'autoTruncate', + ]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['embedContentConfig', 'autoTruncate'], fromAutoTruncate); + } + } + let discriminatorDocumentOcr = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorDocumentOcr === undefined) { + discriminatorDocumentOcr = 'PREDICT'; + } + if (discriminatorDocumentOcr === 'EMBED_CONTENT') { + const fromDocumentOcr = getValueByPath(fromObject, ['documentOcr']); + if (parentObject !== undefined && fromDocumentOcr != null) { + setValueByPath(parentObject, ['embedContentConfig', 'documentOcr'], fromDocumentOcr); + } + } + let discriminatorAudioTrackExtraction = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorAudioTrackExtraction === undefined) { + discriminatorAudioTrackExtraction = 'PREDICT'; + } + if (discriminatorAudioTrackExtraction === 'EMBED_CONTENT') { + const fromAudioTrackExtraction = getValueByPath(fromObject, [ + 'audioTrackExtraction', + ]); + if (parentObject !== undefined && fromAudioTrackExtraction != null) { + setValueByPath(parentObject, ['embedContentConfig', 'audioTrackExtraction'], fromAudioTrackExtraction); + } + } + return toObject; +} +function embedContentParametersPrivateToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['requests[]', 'content'], transformedList); + } + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + contentToMldev$1(tContent(fromContent)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + embedContentConfigToMldev(fromConfig, toObject); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function embedContentParametersPrivateToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + let discriminatorContents = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorContents === undefined) { + discriminatorContents = 'PREDICT'; + } + if (discriminatorContents === 'PREDICT') { + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['instances[]', 'content'], transformedList); + } + } + let discriminatorContent = getValueByPath(rootObject, [ + 'embeddingApiType', + ]); + if (discriminatorContent === undefined) { + discriminatorContent = 'PREDICT'; + } + if (discriminatorContent === 'EMBED_CONTENT') { + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentToVertex$1(tContent(fromContent))); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + embedContentConfigToVertex(fromConfig, toObject, rootObject); + } + return toObject; +} +function embedContentResponseFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + if (rootObject && + getValueByPath(rootObject, ['embeddingApiType']) === 'EMBED_CONTENT') { + const embedding = getValueByPath(fromObject, ['embedding']); + const usageMetadata = getValueByPath(fromObject, ['usageMetadata']); + const truncated = getValueByPath(fromObject, ['truncated']); + if (embedding) { + const stats = {}; + if (usageMetadata && + usageMetadata['promptTokenCount']) { + stats.tokenCount = usageMetadata['promptTokenCount']; + } + if (usageMetadata && + usageMetadata['promptTokensDetails']) { + stats.tokensDetails = usageMetadata['promptTokensDetails']; + } + if (truncated) { + stats.truncated = truncated; + } + embedding.statistics = stats; + setValueByPath(toObject, ['embeddings'], [embedding]); + } + } + return toObject; +} +function endpointFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function fileDataToMldev$1(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function functionCallToMldev$1(fromObject, _rootObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + if (getValueByPath(fromObject, ['partialArgs']) !== undefined) { + throw new Error('partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['willContinue']) !== undefined) { + throw new Error('willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject, _rootObject) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + if (getValueByPath(fromObject, ['streamFunctionCallArguments']) !== + undefined) { + throw new Error('streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject, rootObject) { + const toObject = {}; + const fromServiceTier = getValueByPath(fromObject, ['serviceTier']); + if (parentObject !== undefined && fromServiceTier != null) { + setValueByPath(parentObject, ['serviceTier'], fromServiceTier); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], tSpeechConfig(fromSpeechConfig)); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromImageConfig = getValueByPath(fromObject, ['imageConfig']); + if (fromImageConfig != null) { + setValueByPath(toObject, ['imageConfig'], imageConfigToMldev(fromImageConfig)); + } + const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [ + 'enableEnhancedCivicAnswers', + ]); + if (fromEnableEnhancedCivicAnswers != null) { + setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers); + } + if (getValueByPath(fromObject, ['modelArmorConfig']) !== undefined) { + throw new Error('modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject, rootObject) { + const toObject = {}; + const fromServiceTier = getValueByPath(fromObject, ['serviceTier']); + if (parentObject !== undefined && fromServiceTier != null) { + setValueByPath(parentObject, ['serviceTier'], fromServiceTier); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromImageConfig = getValueByPath(fromObject, ['imageConfig']); + if (fromImageConfig != null) { + setValueByPath(toObject, ['imageConfig'], imageConfigToVertex(fromImageConfig)); + } + if (getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !== + undefined) { + throw new Error('enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromModelArmorConfig = getValueByPath(fromObject, [ + 'modelArmorConfig', + ]); + if (parentObject !== undefined && fromModelArmorConfig != null) { + setValueByPath(parentObject, ['modelArmorConfig'], fromModelArmorConfig); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + const fromModelStatus = getValueByPath(fromObject, ['modelStatus']); + if (fromModelStatus != null) { + setValueByPath(toObject, ['modelStatus'], fromModelStatus); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + generateImagesConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToMldev(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToMldev(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + if (getValueByPath(fromObject, ['mask']) !== undefined) { + throw new Error('mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromWebhookConfig = getValueByPath(fromObject, [ + 'webhookConfig', + ]); + if (parentObject !== undefined && fromWebhookConfig != null) { + setValueByPath(parentObject, ['webhookConfig'], fromWebhookConfig); + } + if (getValueByPath(fromObject, ['resizeMode']) !== undefined) { + throw new Error('resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromMask = getValueByPath(fromObject, ['mask']); + if (parentObject !== undefined && fromMask != null) { + setValueByPath(parentObject, ['instances[0]', 'mask'], videoGenerationMaskToVertex(fromMask)); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + if (getValueByPath(fromObject, ['webhookConfig']) !== undefined) { + throw new Error('webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromResizeMode = getValueByPath(fromObject, ['resizeMode']); + if (parentObject !== undefined && fromResizeMode != null) { + setValueByPath(parentObject, ['parameters', 'resizeMode'], fromResizeMode); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToMldev(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + generateVideosSourceToMldev(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + generateVideosConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + generateVideosSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + generateVideosConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToMldev(fromVideo)); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function generatedImageFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function generatedVideoFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generatedVideoFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generationConfigToVertex(fromObject, rootObject) { + const toObject = {}; + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (fromEnableAffectiveDialog != null) { + setValueByPath(toObject, ['enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromResponseFormat = getValueByPath(fromObject, [ + 'responseFormat', + ]); + if (fromResponseFormat != null) { + let transformedList = fromResponseFormat; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['responseFormat'], transformedList); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], fromResponseSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(fromSpeechConfig)); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + if (getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !== + undefined) { + throw new Error('enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['translationConfig']) !== undefined) { + throw new Error('translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + return toObject; +} +function googleMapsToMldev$1(fromObject, rootObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToMldev$1(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject, ['enableWidget']); + if (fromEnableWidget != null) { + setValueByPath(toObject, ['enableWidget'], fromEnableWidget); + } + if (getValueByPath(fromObject, ['groundingTypes']) !== undefined) { + throw new Error('groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleSearchToMldev$1(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['blockingConfidence']) !== undefined) { + throw new Error('blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSearchTypes = getValueByPath(fromObject, ['searchTypes']); + if (fromSearchTypes != null) { + setValueByPath(toObject, ['searchTypes'], fromSearchTypes); + } + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter); + } + return toObject; +} +function imageConfigToMldev(fromObject, _rootObject) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (fromAspectRatio != null) { + setValueByPath(toObject, ['aspectRatio'], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (fromImageSize != null) { + setValueByPath(toObject, ['imageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['personGeneration']) !== undefined) { + throw new Error('personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['outputMimeType']) !== undefined) { + throw new Error('outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['outputCompressionQuality']) !== + undefined) { + throw new Error('outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['imageOutputOptions']) !== undefined) { + throw new Error('imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['prominentPeople']) !== undefined) { + throw new Error('prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function imageConfigToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (fromAspectRatio != null) { + setValueByPath(toObject, ['aspectRatio'], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (fromImageSize != null) { + setValueByPath(toObject, ['imageSize'], fromImageSize); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (fromPersonGeneration != null) { + setValueByPath(toObject, ['personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (fromOutputMimeType != null) { + setValueByPath(toObject, ['imageOutputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (fromOutputCompressionQuality != null) { + setValueByPath(toObject, ['imageOutputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromImageOutputOptions = getValueByPath(fromObject, [ + 'imageOutputOptions', + ]); + if (fromImageOutputOptions != null) { + setValueByPath(toObject, ['imageOutputOptions'], fromImageOutputOptions); + } + const fromProminentPeople = getValueByPath(fromObject, [ + 'prominentPeople', + ]); + if (fromProminentPeople != null) { + setValueByPath(toObject, ['prominentPeople'], fromProminentPeople); + } + return toObject; +} +function imageFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function imageToMldev(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function imageToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listModelsConfigToMldev(apiClient, fromConfig, toObject); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listModelsConfigToVertex(apiClient, fromConfig, toObject); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function mcpServerToVertex(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['name']) !== undefined) { + throw new Error('name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['streamableHttpTransport']) !== undefined) { + throw new Error('streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function modelFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromMaxTemperature = getValueByPath(fromObject, [ + 'maxTemperature', + ]); + if (fromMaxTemperature != null) { + setValueByPath(toObject, ['maxTemperature'], fromMaxTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromThinking = getValueByPath(fromObject, ['thinking']); + if (fromThinking != null) { + setValueByPath(toObject, ['thinking'], fromThinking); + } + return toObject; +} +function modelFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function multiSpeakerVoiceConfigToVertex(fromObject, rootObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToVertex(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function partToMldev$1(fromObject, rootObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolResponse = getValueByPath(fromObject, ['toolResponse']); + if (fromToolResponse != null) { + setValueByPath(toObject, ['toolResponse'], fromToolResponse); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], functionCallToMldev$1(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromPartMetadata = getValueByPath(fromObject, ['partMetadata']); + if (fromPartMetadata != null) { + setValueByPath(toObject, ['partMetadata'], fromPartMetadata); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function partToVertex$1(fromObject, _rootObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + if (getValueByPath(fromObject, ['toolCall']) !== undefined) { + throw new Error('toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['toolResponse']) !== undefined) { + throw new Error('toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fromFileData); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], fromInlineData); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + if (getValueByPath(fromObject, ['partMetadata']) !== undefined) { + throw new Error('partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function productImageToVertex(fromObject, rootObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + recontextImageSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + recontextImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject, rootObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], fromStyleImageConfig); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], fromSubjectImageConfig); + } + return toObject; +} +function replicatedVoiceConfigToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromVoiceSampleAudio = getValueByPath(fromObject, [ + 'voiceSampleAudio', + ]); + if (fromVoiceSampleAudio != null) { + setValueByPath(toObject, ['voiceSampleAudio'], fromVoiceSampleAudio); + } + if (getValueByPath(fromObject, ['consentAudio']) !== undefined) { + throw new Error('consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['voiceConsentSignature']) !== undefined) { + throw new Error('voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject, _rootObject) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function scribbleImageToVertex(fromObject, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + segmentImageSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + segmentImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function speakerVoiceConfigToVertex(fromObject, rootObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject, rootObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)); + } + return toObject; +} +function toolConfigToMldev(fromObject, rootObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig); + } + const fromIncludeServerSideToolInvocations = getValueByPath(fromObject, ['includeServerSideToolInvocations']); + if (fromIncludeServerSideToolInvocations != null) { + setValueByPath(toObject, ['includeServerSideToolInvocations'], fromIncludeServerSideToolInvocations); + } + return toObject; +} +function toolConfigToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], fromFunctionCallingConfig); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig); + } + if (getValueByPath(fromObject, ['includeServerSideToolInvocations']) !== + undefined) { + throw new Error('includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function toolToMldev$1(fromObject, rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToMldev$1(fromGoogleMaps)); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], fromComputerUse); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['exaAiSearch']) !== undefined) { + throw new Error('exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject, ['parallelAiSearch']) !== undefined) { + throw new Error('parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + const fromFileSearch = getValueByPath(fromObject, ['fileSearch']); + if (fromFileSearch != null) { + setValueByPath(toObject, ['fileSearch'], fromFileSearch); + } + return toObject; +} +function toolToVertex(fromObject, rootObject) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], fromGoogleMaps); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return mcpServerToVertex(item); + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], computerUseToVertex(fromComputerUse)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], fromEnterpriseWebSearch); + } + const fromExaAiSearch = getValueByPath(fromObject, ['exaAiSearch']); + if (fromExaAiSearch != null) { + setValueByPath(toObject, ['exaAiSearch'], fromExaAiSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], fromGoogleSearch); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject, [ + 'parallelAiSearch', + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ['parallelAiSearch'], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + if (getValueByPath(fromObject, ['fileSearch']) !== undefined) { + throw new Error('fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + updateModelConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + updateModelConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function videoFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['encodedVideo']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationMaskToVertex(fromObject, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['_self'], imageToVertex(fromImage)); + } + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + return toObject; +} +function videoGenerationReferenceImageToMldev(fromObject, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToMldev(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function videoToMldev(fromObject, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['encodedVideo'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['encoding'], fromMimeType); + } + return toObject; +} +function videoToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function voiceConfigToVertex(fromObject, rootObject) { + const toObject = {}; + const fromReplicatedVoiceConfig = getValueByPath(fromObject, [ + 'replicatedVoiceConfig', + ]); + if (fromReplicatedVoiceConfig != null) { + setValueByPath(toObject, ['replicatedVoiceConfig'], replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig)); + } + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], fromPrebuiltVoiceConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function createFileSearchStoreConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromEmbeddingModel = getValueByPath(fromObject, [ + 'embeddingModel', + ]); + if (parentObject !== undefined && fromEmbeddingModel != null) { + setValueByPath(parentObject, ['embeddingModel'], tModel(apiClient, fromEmbeddingModel)); + } + return toObject; +} +function createFileSearchStoreParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createFileSearchStoreConfigToMldev(apiClient, fromConfig, toObject); + } + return toObject; +} +function deleteFileSearchStoreConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromForce = getValueByPath(fromObject, ['force']); + if (parentObject !== undefined && fromForce != null) { + setValueByPath(parentObject, ['_query', 'force'], fromForce); + } + return toObject; +} +function deleteFileSearchStoreParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + deleteFileSearchStoreConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function getFileSearchStoreParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function importFileConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromCustomMetadata = getValueByPath(fromObject, [ + 'customMetadata', + ]); + if (parentObject !== undefined && fromCustomMetadata != null) { + let transformedList = fromCustomMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ['customMetadata'], transformedList); + } + const fromChunkingConfig = getValueByPath(fromObject, [ + 'chunkingConfig', + ]); + if (parentObject !== undefined && fromChunkingConfig != null) { + setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig); + } + return toObject; +} +function importFileOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], importFileResponseFromMldev(fromResponse)); + } + return toObject; +} +function importFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFileSearchStoreName = getValueByPath(fromObject, [ + 'fileSearchStoreName', + ]); + if (fromFileSearchStoreName != null) { + setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + importFileConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function importFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + setValueByPath(toObject, ['parent'], fromParent); + } + const fromDocumentName = getValueByPath(fromObject, ['documentName']); + if (fromDocumentName != null) { + setValueByPath(toObject, ['documentName'], fromDocumentName); + } + return toObject; +} +function listFileSearchStoresConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFileSearchStoresParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listFileSearchStoresConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listFileSearchStoresResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFileSearchStores = getValueByPath(fromObject, [ + 'fileSearchStores', + ]); + if (fromFileSearchStores != null) { + let transformedList = fromFileSearchStores; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['fileSearchStores'], transformedList); + } + return toObject; +} +function uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['mimeType'], fromMimeType); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromCustomMetadata = getValueByPath(fromObject, [ + 'customMetadata', + ]); + if (parentObject !== undefined && fromCustomMetadata != null) { + let transformedList = fromCustomMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ['customMetadata'], transformedList); + } + const fromChunkingConfig = getValueByPath(fromObject, [ + 'chunkingConfig', + ]); + if (parentObject !== undefined && fromChunkingConfig != null) { + setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig); + } + return toObject; +} +function uploadToFileSearchStoreParametersToMldev(fromObject) { + const toObject = {}; + const fromFileSearchStoreName = getValueByPath(fromObject, [ + 'fileSearchStoreName', + ]); + if (fromFileSearchStoreName != null) { + setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + uploadToFileSearchStoreConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function uploadToFileSearchStoreResumableResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '2.21.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const MULTI_REGIONAL_LOCATIONS = new Set(['us', 'eu']); +/** + * Raises Undici's internal header/body timeouts to at least `timeout` ms. + * + * In Node > 18 the built-in fetch is backed by Undici, which sets a global + * dispatcher tracking its own headersTimeout and bodyTimeout via Symbol + * properties. Those would otherwise fire before a longer caller-supplied + * timeout. + */ +function raiseUndiciTimeouts(timeout) { + const dispatcherSymbol = Symbol.for('undici.globalDispatcher.1'); + const globalDispatcher = globalThis[dispatcherSymbol]; + if (!globalDispatcher) { + return; + } + for (const sym of Object.getOwnPropertySymbols(globalDispatcher)) { + const desc = sym.description; + if ((desc === null || desc === void 0 ? void 0 : desc.includes('headers timeout')) || (desc === null || desc === void 0 ? void 0 : desc.includes('body timeout'))) { + const currentTimeout = globalDispatcher[sym]; + if (typeof currentTimeout === 'number') { + globalDispatcher[sym] = Math.max(currentTimeout, timeout); + } + } + } +} +/** + * Creates the abort plumbing for one attempt. + * + * A fresh signal per attempt is what makes `HttpOptions.timeout` a per-attempt + * deadline rather than a budget shared across every retry and backoff. + */ +function createAttemptSignal(timeout, callerSignal) { + const noop = () => { }; + if (!(timeout && timeout > 0) && !callerSignal) { + return { signal: undefined, dispose: noop }; + } + const controller = new AbortController(); + let timeoutHandle; + if (timeout && timeout > 0) { + timeoutHandle = setTimeout(() => controller.abort(), timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + const onCallerAbort = () => controller.abort(); + if (callerSignal) { + if (callerSignal.aborted) { + controller.abort(); + } + else { + callerSignal.addEventListener('abort', onCallerAbort); + } + } + return { + signal: controller.signal, + dispose: () => { + if (timeoutHandle !== undefined) { + clearTimeout(timeoutHandle); + } + callerSignal === null || callerSignal === void 0 ? void 0 : callerSignal.removeEventListener('abort', onCallerAbort); + }, + }; +} +// Default retry options. +// The config is based on https://cloud.google.com/storage/docs/retry-strategy. +// LINT.IfChange +const DEFAULT_RETRY_ATTEMPTS = 5; // Including the initial call +const DEFAULT_RETRY_INITIAL_DELAY = 1.0; // seconds +const DEFAULT_RETRY_MAX_DELAY = 60.0; // seconds +const DEFAULT_RETRY_EXP_BASE = 2; +const DEFAULT_RETRY_JITTER = 1; +const DEFAULT_RETRY_HTTP_STATUS_CODES = [ + 408, // Request timeout + 429, // Too many requests + 500, // Internal server error + 502, // Bad gateway + 503, // Service unavailable + 504, // Gateway timeout +]; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + * + * WARNING: This is an internal API and may change without notice. Direct usage + * is not supported and may break your application. + */ +class ApiClient { + constructor(opts) { + var _a, _b, _c; + this.clientOptions = Object.assign({}, opts); + this.customBaseUrl = (_a = opts.httpOptions) === null || _a === void 0 ? void 0 : _a.baseUrl; + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + if (!this.clientOptions.location && + !this.clientOptions.apiKey && + !this.customBaseUrl) { + this.clientOptions.location = 'global'; + } + const hasSufficientAuth = (this.clientOptions.project && this.clientOptions.location) || + this.clientOptions.apiKey; + if (!hasSufficientAuth && !this.customBaseUrl) { + throw new Error('Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.'); + } + const hasConstructorAuth = (opts.project && opts.location) || !!opts.apiKey; + if (this.customBaseUrl && !hasConstructorAuth) { + initHttpOptions.baseUrl = this.customBaseUrl; + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + else if ((this.clientOptions.apiKey && !this.clientOptions.project) || + this.clientOptions.location === 'global') { + // Vertex Express or global endpoint case. + initHttpOptions.baseUrl = 'https://aiplatform.googleapis.com/'; + } + else if (this.clientOptions.project && + this.clientOptions.location && + MULTI_REGIONAL_LOCATIONS.has(this.clientOptions.location)) { + initHttpOptions.baseUrl = `https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`; + } + else if (this.clientOptions.project && this.clientOptions.location) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : VERTEX_AI_API_DEFAULT_VERSION; + } + else { + // Gemini API + if (!this.clientOptions.apiKey) { + console.warn('API key should be set when using the Gemini API.'); + } + initHttpOptions.apiVersion = + (_c = this.clientOptions.apiVersion) !== null && _c !== void 0 ? _c : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getCustomBaseUrl() { + return this.customBaseUrl; + } + async getAuthHeaders() { + const headers = new Headers(); + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request, httpOptions) { + if (httpOptions.baseUrl && + httpOptions.baseUrlResourceScope === ResourceScope.COLLECTION) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (!this.clientOptions.project || !this.clientOptions.location) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString()); + return this.unaryApiCall(url, requestInit, request.httpMethod, patchedHttpOptions.retryOptions, patchedHttpOptions.timeout, request.abortSignal); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString()); + return this.streamApiCall(url, requestInit, request.httpMethod, patchedHttpOptions.retryOptions, patchedHttpOptions.timeout, request.abortSignal); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url) { + if ((httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) && httpOptions.timeout > 0) { + raiseUndiciTimeouts(httpOptions.timeout); + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions, url); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod, retryOptions, timeout, abortSignal) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }), retryOptions, timeout, abortSignal) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(`exception ${e} sending request`, { cause: e }); + } + }); + } + async streamApiCall(url, requestInit, httpMethod, retryOptions, timeout, abortSignal) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }), retryOptions, timeout, abortSignal) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(`exception ${e} sending request`, { cause: e }); + } + }); + } + processStreamResponse(response) { + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _a; + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + const dataPrefix = 'data:'; + const delimiters = ['\n\n', '\r\r', '\r\n\r\n']; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let delimiterIndex = -1; + let delimiterLength = 0; + while (true) { + delimiterIndex = -1; + delimiterLength = 0; + for (const delimiter of delimiters) { + const index = buffer.indexOf(delimiter); + if (index !== -1 && + (delimiterIndex === -1 || index < delimiterIndex)) { + delimiterIndex = index; + delimiterLength = delimiter.length; + } + } + if (delimiterIndex === -1) { + break; // No complete event in buffer + } + const eventString = buffer.substring(0, delimiterIndex); + buffer = buffer.substring(delimiterIndex + delimiterLength); + const trimmedEvent = eventString.trim(); + if (trimmedEvent.startsWith(dataPrefix)) { + const processedChunkString = trimmedEvent + .substring(dataPrefix.length) + .trim(); + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit, retryOptions, timeout, abortSignal) { + var _a, _b, _c, _d, _e, _f; + const retryableStatusCodes = (_a = retryOptions === null || retryOptions === void 0 ? void 0 : retryOptions.httpStatusCodes) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_HTTP_STATUS_CODES; + const runFetch = async () => { + // A fresh signal per attempt, so that `timeout` bounds this attempt + // rather than the whole retry sequence. + const attempt = createAttemptSignal(timeout, abortSignal); + let response; + try { + response = await fetch(url, Object.assign(Object.assign({}, requestInit), { signal: attempt.signal })); + } + catch (e) { + attempt.dispose(); + throw e; + } + if (!retryOptions || + response.ok || + !retryableStatusCodes.includes(response.status)) { + // Either a success, or a failure that must not be retried. + // + // The attempt is deliberately not disposed: ownership of the response + // passes to the caller, and the timeout must stay armed while the body + // is consumed. + return response; + } + // Retryable failure, and this response is about to be discarded, so the + // attempt's timeout is no longer needed. + try { + // Throw the typed `ApiError` so that callers can still rely on + // `error.status` once the retries are exhausted. + await throwErrorIfNotOK(response); + } + finally { + attempt.dispose(); + } + // Unreachable: throwErrorIfNotOK always throws for a non-ok response. + return response; + }; + if (!retryOptions) { + return runFetch(); + } + // `attempts` counts the initial call, so p-retry gets one less. + const attempts = Math.max(1, (_b = retryOptions.attempts) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_ATTEMPTS); + const minTimeout = Math.round(((_c = retryOptions.initialDelay) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_INITIAL_DELAY) * 1000); + const maxTimeout = Math.max(minTimeout, Math.round(((_d = retryOptions.maxDelay) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_MAX_DELAY) * 1000)); + return p_retry(runFetch, { + retries: attempts - 1, + factor: (_e = retryOptions.expBase) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_EXP_BASE, + minTimeout, + maxTimeout, + randomize: ((_f = retryOptions.jitter) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_JITTER) > 0, + onFailedAttempt: (info) => { + var _a; + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + throw (_a = info.error) !== null && _a !== void 0 ? _a : info; + } + }, + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions, url) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + // NOTE: This is intentionally outside the httpOptions.headers guard above + // so that the X-Server-Timeout header is always sent whenever a timeout + // is configured, even if the caller did not supply any custom headers. + if ((httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + await this.clientOptions.auth.addAuthHeaders(headers, url); + return headers; + } + getFileName(file) { + var _a; + let fileName = ''; + if (typeof file === 'string') { + fileName = file.replace(/[/\\]+$/, ''); + fileName = (_a = fileName.split(/[/\\]/).pop()) !== null && _a !== void 0 ? _a : ''; + } + return fileName; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link types.UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const body = { + file: fileToUpload, + }; + const fileName = this.getFileName(file); + const path = formatMap('upload/v1beta/files', body['_url']); + const uploadUrl = await this.fetchUploadUrl(path, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions); + return uploader.upload(file, uploadUrl, this); + } + /** + * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param fileSearchStoreName The name of the file search store to upload the file to. + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFileToFileSearchStore(fileSearchStoreName, file, config) { + var _a; + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + const sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + const path = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`; + const fileName = this.getFileName(file); + const body = {}; + if (config != null) { + uploadToFileSearchStoreConfigToMldev(config, body); + } + const uploadUrl = await this.fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions); + return uploader.uploadToFileSearchStore(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * types.DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, configHttpOptions) { + var _a; + let httpOptions = {}; + if (configHttpOptions) { + httpOptions = configHttpOptions; + } + else { + httpOptions = { + apiVersion: '', // api-version is set in the path. + headers: Object.assign({ 'Content-Type': 'application/json', 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': `${sizeBytes}`, 'X-Goog-Upload-Header-Content-Type': `${mimeType}` }, (fileName ? { 'X-Goog-Upload-File-Name': fileName } : {})), + }; + } + const httpResponse = await this.request({ + path, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient_1) { + return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + Object.assign(serverMessage, data); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = { model }; + const clientMessage = { setup }; + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const clientContent = liveMusicSetWeightedPromptsParametersToMldev(params); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + this.conn.send(JSON.stringify(setConfigParameters)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = { playbackControl }; + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = data; + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + const apiKey = this.apiClient.getApiKey(); + const hasStandardAuth = (!!project && !!location) || !!apiKey; + if (this.apiClient.getCustomBaseUrl() && !hasStandardAuth) { + // Custom base URL without standard auth (e.g., proxy). + url = websocketBaseUrl; + // Auth headers are assumed to be in `clientHeaders` from httpOptions. + } + else { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers, url); + } + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + let sessionResolved = false; + const messageQueue = []; + let setupCompleteResolve = () => { }; + const setupCompletePromise = new Promise((resolve) => { + setupCompleteResolve = resolve; + }); + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, (msg) => { + if (msg['setupComplete'] && !session.setupComplete) { + session.setupComplete = msg['setupComplete']; + setupCompleteResolve({}); + } + if (sessionResolved) { + callbacks.onmessage(msg); + } + else { + messageQueue.push(msg); + } + }, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + if (project && location) { + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + const session = new Session(conn, this.apiClient); + conn.send(JSON.stringify(clientMessage)); + await setupCompletePromise; + sessionResolved = true; + for (const msg of messageQueue) { + callbacks.onmessage(msg); + } + return session; + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (!apiClient.isVertexAI()) { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { 'functionResponses': functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns the indexes of the tools that are not compatible with AFC. + */ +function findAfcIncompatibleToolIndexes(params) { + var _a; + // Use number[] for an array of numbers in TypeScript + const afcIncompatibleToolIndexes = []; + if (!((_a = params === null || params === void 0 ? void 0 : params.config) === null || _a === void 0 ? void 0 : _a.tools)) { + return afcIncompatibleToolIndexes; + } + params.config.tools.forEach((tool, index) => { + if (isCallableTool(tool)) { + return; + } + const geminiTool = tool; + if (geminiTool.functionDeclarations && + geminiTool.functionDeclarations.length > 0) { + afcIncompatibleToolIndexes.push(index); + } + }); + return afcIncompatibleToolIndexes; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Calculates embeddings for the given contents. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + this.embedContent = async (params) => { + if (!this.apiClient.isVertexAI()) { + const isGeminiEmbedding2Model = params.model.includes('gemini-embedding-2'); + if (isGeminiEmbedding2Model) { + params.contents = tContents(params.contents); + } + return await this.embedContentInternal(params); + } + const isVertexEmbedContentModel = (params.model.includes('gemini') && + params.model !== 'gemini-embedding-001') || + params.model.includes('maas'); + if (isVertexEmbedContentModel) { + const contents = tContents(params.contents); + if (contents.length > 1) { + throw new Error('The embedContent API for this model only supports one content at a time.'); + } + const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: EmbeddingApiType.EMBED_CONTENT }); + return await this.embedContentInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: EmbeddingApiType.PREDICT }); + return await this.embedContentInternal(paramsPrivate); + } + }; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Gemini Enterprise Agent Platform API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchema(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params); + if (incompatibleToolIndexes.length > 0) { + const formattedIndexes = incompatibleToolIndexes + .map((index) => `tools[${index}]`) + .join(', '); + throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Gemini Enterprise Agent Platform API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + var _a, _b, _c, _d, _e; + this.maybeMoveToResponseJsonSchema(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params); + if (incompatibleToolIndexes.length > 0) { + const formattedIndexes = incompatibleToolIndexes + .map((index) => `tools[${index}]`) + .join(', '); + throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`); + } + // With tool compatibility confirmed, validate that the configuration are + // compatible with each other and raise an error if invalid. + const streamFunctionCall = (_c = (_b = (_a = params === null || params === void 0 ? void 0 : params.config) === null || _a === void 0 ? void 0 : _a.toolConfig) === null || _b === void 0 ? void 0 : _b.functionCallingConfig) === null || _c === void 0 ? void 0 : _c.streamFunctionCallArguments; + const disableAfc = (_e = (_d = params === null || params === void 0 ? void 0 : params.config) === null || _d === void 0 ? void 0 : _d.automaticFunctionCalling) === null || _e === void 0 ? void 0 : _e.disable; + if (streamFunctionCall && !disableAfc) { + throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, " + + 'this feature is not compatible with automatic function calling (AFC). ' + + "Please set 'config.automaticFunctionCalling.disable' to true to disable AFC " + + "or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' " + + 'to be undefined or set to false to disable streaming function call arguments feature.'); + } + return await this.processAfcStream(params); + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-4.0-generate-001', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + if (!Models.loggedGenerateImagesWarning) { + Models.loggedGenerateImagesWarning = true; + console.warn('The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images'); + } + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + if (!Models.loggedEditImageWarning) { + Models.loggedEditImageWarning = true; + console.warn('The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image'); + } + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Gemini Enterprise Agent Platform currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-4.0-upscale-preview', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + var _a, _b, _c, _d, _e, _f; + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + if (params.prompt || params.image || params.video) { + if (!Models.loggedGenerateVideosWarning) { + Models.loggedGenerateVideosWarning = true; + console.warn('The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead.'); + } + } + // Gemini API does not support video bytes. + if (!this.apiClient.isVertexAI()) { + if (((_a = params.video) === null || _a === void 0 ? void 0 : _a.uri) && ((_b = params.video) === null || _b === void 0 ? void 0 : _b.videoBytes)) { + params.video = { + uri: params.video.uri, + mimeType: params.video.mimeType, + }; + } + else if (((_d = (_c = params.source) === null || _c === void 0 ? void 0 : _c.video) === null || _d === void 0 ? void 0 : _d.uri) && + ((_f = (_e = params.source) === null || _e === void 0 ? void 0 : _e.video) === null || _f === void 0 ? void 0 : _f.videoBytes)) { + params.source.video = { + uri: params.source.video.uri, + mimeType: params.source.video.mimeType, + }; + } + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchema(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _b, _c; + var _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _a = response_1_1.done, !_a; _f = true) { + _c = response_1_1.value; + _f = false; + const chunk = _c; + yield yield __await(chunk); + if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_e = chunk.candidates[0].content.parts) !== null && _e !== void 0 ? _e : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_a && (_b = response_1.return)) yield __await(_b.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json())), params); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersPrivateToVertex(this.apiClient, params, params); + const endpointUrl = tIsVertexEmbedContentModel(params.model) + ? '{model}:embedContent' + : '{model}:predict'; + path = formatMap(endpointUrl, body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse, params); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersPrivateToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Recontextualizes an image. + * + * There is one type of recontextualization currently supported: + * 1) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.recontextImage({ + * model: 'virtual-try-on-001', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} +Models.loggedGenerateImagesWarning = false; +Models.loggedEditImageWarning = false; +Models.loggedGenerateVideosWarning = false; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function authConfigToMldev(fromObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject, ['apiKey']); + if (fromApiKey != null) { + setValueByPath(toObject, ['apiKey'], fromApiKey); + } + if (getValueByPath(fromObject, ['apiKeyConfig']) !== undefined) { + throw new Error('apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['authType']) !== undefined) { + throw new Error('authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['googleServiceAccountConfig']) !== + undefined) { + throw new Error('googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['httpBasicAuthConfig']) !== undefined) { + throw new Error('httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oauthConfig']) !== undefined) { + throw new Error('oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['oidcConfig']) !== undefined) { + throw new Error('oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function functionCallToMldev(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + if (getValueByPath(fromObject, ['partialArgs']) !== undefined) { + throw new Error('partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['willContinue']) !== undefined) { + throw new Error('willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleMapsToMldev(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToMldev(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject, ['enableWidget']); + if (fromEnableWidget != null) { + setValueByPath(toObject, ['enableWidget'], fromEnableWidget); + } + if (getValueByPath(fromObject, ['groundingTypes']) !== undefined) { + throw new Error('groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['blockingConfidence']) !== undefined) { + throw new Error('blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromSearchTypes = getValueByPath(fromObject, ['searchTypes']); + if (fromSearchTypes != null) { + setValueByPath(toObject, ['searchTypes'], fromSearchTypes); + } + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], tLiveSpeechConfig(fromSpeechConfig)); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (parentObject !== undefined && fromThinkingConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'thinkingConfig'], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], fromInputAudioTranscription); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], fromOutputAudioTranscription); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity); + } + if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) { + throw new Error('explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromAvatarConfig = getValueByPath(fromObject, ['avatarConfig']); + if (parentObject !== undefined && fromAvatarConfig != null) { + setValueByPath(parentObject, ['setup', 'avatarConfig'], fromAvatarConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['setup', 'safetySettings'], transformedList); + } + const fromTranslationConfig = getValueByPath(fromObject, [ + 'translationConfig', + ]); + if (parentObject !== undefined && fromTranslationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'translationConfig'], fromTranslationConfig); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], fromToolCall); + } + const fromToolResponse = getValueByPath(fromObject, ['toolResponse']); + if (fromToolResponse != null) { + setValueByPath(toObject, ['toolResponse'], fromToolResponse); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], functionCallToMldev(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromPartMetadata = getValueByPath(fromObject, ['partMetadata']); + if (fromPartMetadata != null) { + setValueByPath(toObject, ['partMetadata'], fromPartMetadata); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToMldev(fromGoogleMaps)); + } + const fromMcpServers = getValueByPath(fromObject, ['mcpServers']); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['mcpServers'], transformedList); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], fromComputerUse); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['exaAiSearch']) !== undefined) { + throw new Error('exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject, ['parallelAiSearch']) !== undefined) { + throw new Error('parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], fromUrlContext); + } + const fromFileSearch = getValueByPath(fromObject, ['fileSearch']); + if (fromFileSearch != null) { + setValueByPath(toObject, ['fileSearch'], fromFileSearch); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function deleteDocumentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromForce = getValueByPath(fromObject, ['force']); + if (parentObject !== undefined && fromForce != null) { + setValueByPath(parentObject, ['_query', 'force'], fromForce); + } + return toObject; +} +function deleteDocumentParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + deleteDocumentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function getDocumentParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function listDocumentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listDocumentsParametersToMldev(fromObject) { + const toObject = {}; + const fromParent = getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + setValueByPath(toObject, ['_url', 'parent'], fromParent); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listDocumentsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listDocumentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromDocuments = getValueByPath(fromObject, ['documents']); + if (fromDocuments != null) { + let transformedList = fromDocuments; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['documents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Documents extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists documents. + * + * @param params - The parameters for the list request. + * @return - A pager of documents. + * + * @example + * ```ts + * const documents = await ai.documents.list({parent:'rag_store_name', config: {'pageSize': 2}}); + * for await (const document of documents) { + * console.log(document); + * } + * ``` + */ + this.list = async (params) => { + return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x) => this.listInternal({ parent: params.parent, config: x.config }), await this.listInternal(params), params); + }; + } + /** + * Gets a Document. + * + * @param params - The parameters for getting a document. + * @return Document. + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getDocumentParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a Document. + * + * @param params - The parameters for deleting a document. + */ + async delete(params) { + var _a, _b; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteDocumentParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listDocumentsParametersToMldev(params); + path = formatMap('{parent}/documents', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listDocumentsResponseFromMldev(apiResponse); + const typedResp = new ListDocumentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class FileSearchStores extends BaseModule { + constructor(apiClient, documents = new Documents(apiClient)) { + super(); + this.apiClient = apiClient; + this.documents = documents; + /** + * Lists file search stores. + * + * @param params - The parameters for the list request. + * @return - A pager of file search stores. + * + * @example + * ```ts + * const fileSearchStores = await ai.fileSearchStores.list({config: {'pageSize': 2}}); + * for await (const fileSearchStore of fileSearchStores) { + * console.log(fileSearchStore); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to a given File Search Store. + * This method is not available in Gemini Enterprise Agent Platform (previously known as Vertex AI). + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadToFileSearchStoreParameters` interface. + * @see {@link types.UploadToFileSearchStoreParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a long running operation. + * @throws An error if called on a Gemini Enterprise Agent Platform (previously known as Vertex AI) client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to a given file search store. + * + * ```ts + * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(operation.name); + * ``` + */ + async uploadToFileSearchStore(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.'); + } + return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config); + } + /** + * Downloads media using a Media ID or URI. + * This method is only supported in the Gemini Developer client. + * + * @param uri - The URI or Media ID of the blob. + * @param config - Optional configuration for the download. + * @returns A promise that resolves to the blob data as a Uint8Array. + */ + async downloadMedia(uri, config) { + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported in the Gemini Developer client.'); + } + const parsedUri = new URL(uri, 'http://dummy.com'); + let pathname = parsedUri.pathname; + if (pathname.startsWith('/')) { + pathname = pathname.slice(1); + } + if (!pathname.includes('/media/')) { + throw new Error(`Invalid uri format: ${uri}. Expected to contain /media/`); + } + const queryParams = {}; + parsedUri.searchParams.forEach((value, key) => { + queryParams[key] = value; + }); + queryParams['alt'] = 'media'; + const httpOptions = Object.assign({}, config === null || config === void 0 ? void 0 : config.httpOptions); + const response = await this.apiClient.request({ + path: pathname, + httpMethod: 'GET', + queryParams: queryParams, + httpOptions: httpOptions, + }); + if (response instanceof HttpResponse) { + const arrayBuffer = await response.responseInternal.arrayBuffer(); + return new Uint8Array(arrayBuffer); + } + else { + throw new Error('Unexpected response type from downloadMedia'); + } + } + /** + * Creates a File Search Store. + * + * @param params - The parameters for creating a File Search Store. + * @return FileSearchStore. + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileSearchStoreParametersToMldev(this.apiClient, params); + path = formatMap('fileSearchStores', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Gets a File Search Store. + * + * @param params - The parameters for getting a File Search Store. + * @return FileSearchStore. + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileSearchStoreParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a File Search Store. + * + * @param params - The parameters for deleting a File Search Store. + */ + async delete(params) { + var _a, _b; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileSearchStoreParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFileSearchStoresParametersToMldev(params); + path = formatMap('fileSearchStores', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFileSearchStoresResponseFromMldev(apiResponse); + const typedResp = new ListFileSearchStoresResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async uploadToFileSearchStoreInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = uploadToFileSearchStoreParametersToMldev(params); + path = formatMap('upload/v1beta/{file_search_store_name}:uploadToFileSearchStore', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse); + const typedResp = new UploadToFileSearchStoreResumableResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Imports a File from File Service to a FileSearchStore. + * + * This is a long-running operation, see aip.dev/151 + * + * @param params - The parameters for importing a file to a file search store. + * @return ImportFileOperation. + */ + async importFile(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = importFileParametersToMldev(params); + path = formatMap('{file_search_store_name}:importFile', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = importFileOperationFromMldev(apiResponse); + const typedResp = new ImportFileOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Checks for the existence of the Deno global object to determine the environment. + * @returns {boolean} True if the runtime is Deno, false otherwise. + */ +function isDeno() { + if ("Deno" in globalThis) { + return true; + } + return false; +} +let envMemo = undefined; +/** + * Reads and validates environment variables. + */ +function env() { + var _a, _b, _c, _d, _e, _f; + if (envMemo) { + return envMemo; + } + const globals = globalThis; + let envObject = {}; + if (isDeno()) { + envObject = (_d = (_c = (_b = (_a = globals.Deno) === null || _a === void 0 ? void 0 : _a.env) === null || _b === void 0 ? void 0 : _b.toObject) === null || _c === void 0 ? void 0 : _c.call(_b)) !== null && _d !== void 0 ? _d : {}; + } + else { + envObject = (_f = (_e = globals.process) === null || _e === void 0 ? void 0 : _e.env) !== null && _f !== void 0 ? _f : {}; + } + envMemo = envObject; + return envMemo; +} +/** + * Populates global parameters with environment variables. + */ +function fillGlobals(options) { + var _a, _b; + const clone = Object.assign({}, options); + const envVars = env(); + if (typeof envVars.GOOGLE_GENAI_API_VERSION !== "undefined") { + (_a = clone.api_version) !== null && _a !== void 0 ? _a : (clone.api_version = envVars.GOOGLE_GENAI_API_VERSION); + } + if (typeof envVars.GOOGLE_GENAI_USER_PROJECT !== "undefined") { + (_b = clone.user_project) !== null && _b !== void 0 ? _b : (clone.user_project = envVars.GOOGLE_GENAI_USER_PROJECT); + } + return clone; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class GoogleGenAISecurityProvider { + constructor(options) { + this.options = options; + } + getDefaultHeaders() { + return this.options.defaultHeaders; + } + async resolveGoogleGenAISecurity(url) { + return securityFromHeaders(await this.options.getAuthHeaders(url)); + } +} +class GoogleGenAIAuthHook { + beforeCreateRequest(_hookCtx, input) { + return Object.assign(Object.assign({}, input), { url: decodeSDKLevelAPIVersionPath(input.url) }); + } + async beforeRequest(hookCtx, request) { + applyDefaultHeaders(request.headers, getStaticDefaultHeaders(hookCtx.security_source)); + applyUserProject(hookCtx, request.headers); + if (hasAuthHeaders(request.headers)) { + return request; + } + const security = await resolveSecurity$1(hookCtx.security_source, request.url); + applyDefaultHeaders(request.headers, security === null || security === void 0 ? void 0 : security.default_headers); + applyAuth(request.headers, security); + return request; + } +} +function decodeSDKLevelAPIVersionPath(url) { + const [, apiVersion, ...rest] = url.pathname.split("/"); + if (!apiVersion) { + return url; + } + const decodedAPIVersion = decodeURIComponent(apiVersion); + if (!decodedAPIVersion.includes("/")) { + return url; + } + const nextURL = new URL(url); + nextURL.pathname = `/${decodedAPIVersion}/${rest.join("/")}`; + return nextURL; +} +async function resolveSecurity$1(securitySource, requestURL) { + if (isSecurityResolver(securitySource)) { + return securitySource.resolveGoogleGenAISecurity(requestURL); + } + const security = typeof securitySource === "function" + ? await securitySource() + : securitySource; + if (isSecurity(security)) { + return withEnvSecurity(security); + } + return withEnvSecurity(undefined); +} +function getStaticDefaultHeaders(securitySource) { + var _a, _b; + if (isSecurityResolver(securitySource)) { + return ((_b = (_a = securitySource.getDefaultHeaders) === null || _a === void 0 ? void 0 : _a.call(securitySource)) !== null && _b !== void 0 ? _b : securitySource.defaultHeaders); + } + if (isSecurity(securitySource)) { + return securitySource.default_headers; + } + return undefined; +} +function withEnvSecurity(security) { + var _a, _b; + const envVars = env(); + const nextSecurity = Object.assign(Object.assign({}, security), { api_key: (_a = security === null || security === void 0 ? void 0 : security.api_key) !== null && _a !== void 0 ? _a : envVars.GOOGLE_GENAI_API_KEY, access_token: (_b = security === null || security === void 0 ? void 0 : security.access_token) !== null && _b !== void 0 ? _b : envVars.GOOGLE_GENAI_ACCESS_TOKEN }); + return hasSecurityValue(nextSecurity) ? nextSecurity : undefined; +} +function securityFromHeaders(headers) { + var _a, _b; + const defaultHeaders = {}; + for (const [key, value] of headers) { + const lowerKey = key.toLowerCase(); + if (lowerKey !== "authorization" && lowerKey !== "x-goog-api-key") { + defaultHeaders[key] = value; + } + } + const security = { + access_token: (_a = headers.get("authorization")) !== null && _a !== void 0 ? _a : undefined, + api_key: (_b = headers.get("x-goog-api-key")) !== null && _b !== void 0 ? _b : undefined, + default_headers: Object.keys(defaultHeaders).length + ? defaultHeaders + : undefined, + }; + return hasSecurityValue(security) ? security : undefined; +} +function applyDefaultHeaders(target, source) { + if (!source) { + return; + } + for (const [key, value] of new Headers(source)) { + if (target.get(key) === null) { + target.set(key, value); + } + } +} +function applyUserProject(hookCtx, headers) { + if (hookCtx.options.user_project !== undefined && + headers.get("x-goog-user-project") === null) { + headers.set("x-goog-user-project", hookCtx.options.user_project); + } +} +function applyAuth(headers, security) { + if (!security) { + return; + } + if (security.api_key) { + headers.set("x-goog-api-key", security.api_key); + return; + } + if (security.access_token) { + headers.set("Authorization", bearer(security.access_token)); + } +} +function hasAuthHeaders(headers) { + return (headers.get("authorization") !== null || + headers.get("x-goog-api-key") !== null); +} +function bearer(token) { + return token.slice(0, 7).toLowerCase() === "bearer " + ? token + : `Bearer ${token}`; +} +function isSecurity(value) { + return typeof value === "object" && value !== null; +} +function isSecurityResolver(value) { + return (typeof value === "object" && + value !== null && + "resolveGoogleGenAISecurity" in value && + typeof value.resolveGoogleGenAISecurity === "function"); +} +function hasSecurityValue(security) { + return (security.api_key !== undefined || + security.access_token !== undefined || + security.default_headers !== undefined); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +/** + * Base class for all HTTP errors. + */ +class HTTPClientError extends Error { + constructor(message, opts) { + let msg = message; + if (opts === null || opts === void 0 ? void 0 : opts.cause) { + msg += `: ${opts.cause}`; + } + super(msg, opts); + this.name = "HTTPClientError"; + // In older runtimes, the cause field would not have been assigned through + // the super() call. + if (typeof this.cause === "undefined") { + this.cause = opts === null || opts === void 0 ? void 0 : opts.cause; + } + } +} +/** + * An error to capture unrecognised or unexpected errors when making HTTP calls. + */ +class UnexpectedClientError extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "UnexpectedClientError"; + } +} +/** + * An error that is raised when any inputs used to create a request are invalid. + */ +class InvalidRequestError extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "InvalidRequestError"; + } +} +/** + * An error that is raised when a HTTP request was aborted by the client error. + */ +class RequestAbortedError extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestAbortedError"; + } +} +/** + * An error that is raised when a HTTP request timed out due to an AbortSignal + * signal timeout. + */ +class RequestTimeoutError extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestTimeoutError"; + } +} +/** + * An error that is raised when a HTTP client is unable to make a request to + * a server. + */ +class ConnectionError extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "ConnectionError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +/** The base class for all HTTP error responses */ +class GoogleGenAiError extends Error { + constructor(message, httpMeta) { + var _a, _b, _c, _d; + super(message); + this.statusCode = (_a = httpMeta === null || httpMeta === void 0 ? void 0 : httpMeta.response) === null || _a === void 0 ? void 0 : _a.status; + this.body = (_b = httpMeta === null || httpMeta === void 0 ? void 0 : httpMeta.body) !== null && _b !== void 0 ? _b : ""; + this.headers = (_c = httpMeta === null || httpMeta === void 0 ? void 0 : httpMeta.response) === null || _c === void 0 ? void 0 : _c.headers; + this.contentType = ((_d = httpMeta === null || httpMeta === void 0 ? void 0 : httpMeta.response) === null || _d === void 0 ? void 0 : _d.headers.get("content-type")) || ""; + this.rawResponse = httpMeta === null || httpMeta === void 0 ? void 0 : httpMeta.response; + this.name = "GoogleGenAiError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class GeminiNextGenAPIClientError extends Error { +} +/** General errors raised by the GenAI API. */ +class APIError extends GeminiNextGenAPIClientError { + constructor(status, error, message, headers) { + super(APIError.makeMessage(status, error, message)); + this.status = status; + this.headers = headers; + this.error = error; + this.statusCode = status; + this.body = stringifyErrorBody(error); + this.contentType = (headers === null || headers === void 0 ? void 0 : headers.get("content-type")) || ""; + this.rawResponse = undefined; + this.cause = undefined; + this.name = this.constructor.name; + Object.setPrototypeOf(this, new.target.prototype); + } + static makeMessage(status, error, message) { + var _a; + const errorMessage = error && isPlainObject$2(error) && typeof error["message"] === "string" + ? error["message"] + : undefined; + const errorBody = stringifyErrorBody(error); + const msg = (_a = errorMessage !== null && errorMessage !== void 0 ? errorMessage : message) !== null && _a !== void 0 ? _a : (errorBody || "An error occurred"); + const statusText = status ? `${status} ` : ""; + return `${statusText}${msg}`; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ + message, + cause: errorResponse instanceof Error ? errorResponse : undefined, + }); + } + if (status === 400) { + return new BadRequestError(status, errorResponse, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, errorResponse, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, errorResponse, message, headers); + } + if (status === 404) { + return new NotFoundError(status, errorResponse, message, headers); + } + if (status === 409) { + return new ConflictError(status, errorResponse, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, errorResponse, message, headers); + } + if (status === 429) { + return new RateLimitError(status, errorResponse, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, errorResponse, message, headers); + } + return new APIError(status, errorResponse, message, headers); + } +} +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || "Request was aborted.", undefined); + } +} +class APIConnectionError extends APIError { + constructor({ message, cause, }) { + super(undefined, undefined, message || "Connection error.", undefined); + this.cause = cause; + } +} +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ + message: message || + "Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options.", + }); + } +} +class BadRequestError extends APIError { +} +class AuthenticationError extends APIError { +} +class PermissionDeniedError extends APIError { +} +class NotFoundError extends APIError { +} +class ConflictError extends APIError { +} +class UnprocessableEntityError extends APIError { +} +class RateLimitError extends APIError { +} +class InternalServerError extends APIError { +} +function wrapSDKError(error) { + if (isCompatAPIErrorInstance(error)) { + return error; + } + if (error instanceof GoogleGenAiError) { + return wrapAPIError(error); + } + if (error instanceof HTTPClientError) { + return wrapHTTPClientError(error); + } + return error; +} +function wrapAPIError(error) { + const errorPayload = getErrorPayload(error); + const wrapped = APIError.generate(error.statusCode, errorPayload, error.message, error.headers); + defineReadonly(wrapped, "body", error.body); + defineReadonly(wrapped, "contentType", error.contentType); + defineReadonly(wrapped, "rawResponse", error.rawResponse); + defineReadonly(wrapped, "statusCode", error.statusCode); + defineReadonly(wrapped, "cause", error); + return wrapped; +} +function wrapHTTPClientError(error) { + if (error instanceof RequestTimeoutError) { + return new APIConnectionTimeoutError({ message: error.message }); + } + if (error instanceof RequestAbortedError) { + return new APIUserAbortError({ message: error.message }); + } + if (error instanceof ConnectionError) { + return new APIConnectionError({ message: error.message, cause: error }); + } + return new APIConnectionError({ message: error.message, cause: error }); +} +function getErrorPayload(error) { + const data = getObjectProperty(error, "data$"); + if (data && typeof data === "object") { + return data; + } + try { + const parsed = JSON.parse(error.body); + if (parsed && typeof parsed === "object") { + return parsed; + } + } + catch (_a) { + // Fall through to generated error.error below. + } + const dataError = getObjectProperty(error, "error"); + return dataError && typeof dataError === "object" + ? dataError + : undefined; +} +function getObjectProperty(value, key) { + return value && typeof value === "object" + ? value[key] + : undefined; +} +function stringifyErrorBody(error) { + if (!error) + return ""; + try { + return JSON.stringify(error); + } + catch (_a) { + return String(error); + } +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function isCompatAPIErrorInstance(value) { + // Avoid instanceof here so this guard never depends on Symbol.hasInstance. + return typeof value === "object" && value !== null + ? APIError.prototype.isPrototypeOf(value) + : false; +} +function defineReadonly(target, key, value) { + Object.defineProperty(target, key, { + configurable: true, + enumerable: true, + value, + writable: false, + }); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * This file is only ever generated once on the first generation and then is free to be modified. + * Any hooks you wish to add should be registered in the initHooks function. Feel free to define them + * in this file or in separate files in the hooks folder. + */ +function initHooks(hooks) { + // Add hooks by calling hooks.register{ClientInit/BeforeCreateRequest/BeforeRequest/AfterSuccess/AfterError}Hook + // with an instance of a hook that implements that specific Hook interface + // Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance + const googleGenAIAuthHook = new GoogleGenAIAuthHook(); + hooks.registerBeforeCreateRequestHook(googleGenAIAuthHook); + hooks.registerBeforeRequestHook(googleGenAIAuthHook); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class SDKHooks { + constructor() { + this.sdkInitHooks = []; + this.beforeCreateRequestHooks = []; + this.beforeRequestHooks = []; + this.afterSuccessHooks = []; + this.afterErrorHooks = []; + const presetHooks = []; + for (const hook of presetHooks) { + if ("sdkInit" in hook) { + this.registerSDKInitHook(hook); + } + if ("beforeCreateRequest" in hook) { + this.registerBeforeCreateRequestHook(hook); + } + if ("beforeRequest" in hook) { + this.registerBeforeRequestHook(hook); + } + if ("afterSuccess" in hook) { + this.registerAfterSuccessHook(hook); + } + if ("afterError" in hook) { + this.registerAfterErrorHook(hook); + } + } + initHooks(this); + } + registerSDKInitHook(hook) { + this.sdkInitHooks.push(hook); + } + registerBeforeCreateRequestHook(hook) { + this.beforeCreateRequestHooks.push(hook); + } + registerBeforeRequestHook(hook) { + this.beforeRequestHooks.push(hook); + } + registerAfterSuccessHook(hook) { + this.afterSuccessHooks.push(hook); + } + registerAfterErrorHook(hook) { + this.afterErrorHooks.push(hook); + } + sdkInit(opts) { + return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + } + beforeCreateRequest(hookCtx, input) { + let inp = input; + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); + } + return inp; + } + async beforeRequest(hookCtx, request) { + let req = request; + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); + } + return req; + } + async afterSuccess(hookCtx, response) { + let res = response; + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); + } + return res; + } + async afterError(hookCtx, response, error) { + let res = response; + let err = error; + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; + } + return { response: res, error: err }; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +function OK(value) { + return { ok: true, value }; +} +function ERR(error) { + return { ok: false, error }; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +function bytesToBase64(u8arr) { + return btoa(String.fromCodePoint(...u8arr)); +} +function stringToBytes(str) { + return new TextEncoder().encode(str); +} +function stringToBase64(str) { + return bytesToBase64(stringToBytes(str)); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +const hasOwn = Object.prototype.hasOwnProperty; +function pathToFunc(pathPattern, options) { + const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; + return function buildURLPath(params = {}) { + return pathPattern + .replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error(`Parameter '${placeholder}' must be a string or number`); + } + return `${value}`; + }) + .replace(/^\/+/, ""); + }; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Contains the list of servers available to the SDK + */ +const ServerList = [ + /** + * Global Endpoint + */ + "https://generativelanguage.googleapis.com", +]; +function serverURLFromOptions(options) { + var _a; + let serverURL = options.server_url; + const params = {}; + if (!serverURL) { + const serverIdx = (_a = options.server_idx) !== null && _a !== void 0 ? _a : 0; + if (serverIdx < 0 || serverIdx >= ServerList.length) { + throw new Error(`Invalid server index ${serverIdx}`); + } + serverURL = ServerList[serverIdx] || ""; + } + const u = pathToFunc(serverURL)(params); + return new URL(u); +} +const SDK_METADATA = { + userAgent: "speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai", +}; + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +function combineSignals(...signals) { + const filtered = []; + for (const signal of signals) { + if (signal) { + filtered.push(signal); + } + } + switch (filtered.length) { + case 0: + case 1: + return filtered[0] || null; + default: + if ("any" in AbortSignal && typeof AbortSignal.any === "function") { + return AbortSignal.any(filtered); + } + return abortSignalAny(filtered); + } +} +function abortSignalAny(signals) { + const controller = new AbortController(); + const result = controller.signal; + if (!signals.length) { + return controller.signal; + } + if (signals.length === 1) { + return signals[0] || controller.signal; + } + for (const signal of signals) { + if (signal.aborted) { + return signal; + } + } + function abort() { + controller.abort(this.reason); + clean(); + } + const signalRefs = []; + function clean() { + for (const signalRef of signalRefs) { + const signal = signalRef.deref(); + if (signal) { + signal.removeEventListener("abort", abort); + } + } + } + for (const signal of signals) { + signalRefs.push(new WeakRef(signal)); + signal.addEventListener("abort", abort); + } + return result; +} +function compactMap(values) { + const out = {}; + for (const [k, v] of Object.entries(values)) { + if (typeof v !== "undefined") { + out[k] = v; + } + } + return out; +} +function isPlainObject$1(value) { + if (value === null || typeof value !== "object") + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null || proto === Object.prototype) + return true; + // cross-realm plain objects (vm contexts, iframes) inherit from a + // different realm's Object.prototype, which itself has a null prototype + try { + return Object.getPrototypeOf(proto) === null; + } + catch (_a) { + return false; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +function formEncoder(sep) { + return (key, value, options) => { + let out = ""; + const pairs = (options === null || options === void 0 ? void 0 : options.explode) + ? explode(key, value) + : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v) => { + return (options === null || options === void 0 ? void 0 : options.charEncoding) === "percent" ? encodeURIComponent(v) : v; + }; + const encodeValue = (v) => encodeString(serializeValue(v)); + const encodedSep = encodeString(sep); + pairs.forEach(([pk, pv]) => { + var _a, _b; + let tmp = ""; + let encValue = null; + if (pv == null) { + return; + } + else if (Array.isArray(pv)) { + encValue = (_a = mapDefined(pv, (v) => `${encodeValue(v)}`)) === null || _a === void 0 ? void 0 : _a.join(encodedSep); + } + else if (isPlainObject$1(pv)) { + encValue = (_b = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + return `${encodeString(k)}${encodedSep}${encodeValue(v)}`; + })) === null || _b === void 0 ? void 0 : _b.join(encodedSep); + } + else { + encValue = `${encodeValue(pv)}`; + } + if (encValue == null) { + return; + } + tmp = `${encodeString(pk)}=${encValue}`; + // If we end up with the nothing then skip forward + if (!tmp || tmp === "=") { + return; + } + out += `&${tmp}`; + }); + return out.slice(1); + }; +} +const encodeForm = formEncoder(","); +function encodeJSON(key, value, options) { + if (typeof value === "undefined") { + return; + } + const encodeString = (v) => { + return (options === null || options === void 0 ? void 0 : options.charEncoding) === "percent" ? encodeURIComponent(v) : v; + }; + const encVal = encodeString(JSON.stringify(value, jsonReplacer)); + return (options === null || options === void 0 ? void 0 : options.explode) ? encVal : `${encodeString(key)}=${encVal}`; +} +const encodeSimple = (key, value, options) => { + let out = ""; + const pairs = (options === null || options === void 0 ? void 0 : options.explode) + ? explode(key, value) + : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v) => { + return (options === null || options === void 0 ? void 0 : options.charEncoding) === "percent" ? encodeURIComponent(v) : v; + }; + const encodeValue = (v) => encodeString(serializeValue(v)); + pairs.forEach(([pk, pv]) => { + var _a; + let tmp = ""; + if (pv == null) { + return; + } + else if (Array.isArray(pv)) { + tmp = (_a = mapDefined(pv, (v) => `${encodeValue(v)}`)) === null || _a === void 0 ? void 0 : _a.join(","); + } + else if (isPlainObject$1(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + return `,${encodeString(k)},${encodeValue(v)}`; + }); + tmp = mapped === null || mapped === void 0 ? void 0 : mapped.join("").slice(1); + } + else { + const k = (options === null || options === void 0 ? void 0 : options.explode) && isPlainObject$1(value) ? `${pk}=` : ""; + tmp = `${k}${encodeValue(pv)}`; + } + out += tmp ? `,${tmp}` : ""; + }); + return out.slice(1); +}; +function explode(key, value) { + if (Array.isArray(value)) { + return value.map((v) => [key, v]); + } + else if (isPlainObject$1(value)) { + const o = value !== null && value !== void 0 ? value : {}; + return Object.entries(o).map(([k, v]) => [k, v]); + } + else { + return [[key, value]]; + } +} +function serializeValue(value) { + if (value == null) { + return ""; + } + else if (value instanceof Date) { + return value.toISOString(); + } + else if (value instanceof Uint8Array) { + return bytesToBase64(value); + } + else if (typeof value === "object") { + return JSON.stringify(value, jsonReplacer); + } + return `${value}`; +} +function jsonReplacer(_, value) { + if (value instanceof Uint8Array) { + return bytesToBase64(value); + } + else { + return value; + } +} +function mapDefined(inp, mapper) { + const res = inp.reduce((acc, v) => { + if (v == null) { + return acc; + } + const m = mapper(v); + if (m == null) { + return acc; + } + acc.push(m); + return acc; + }, []); + return res.length ? res : null; +} +function mapDefinedEntries(inp, mapper) { + const acc = []; + for (const [k, v] of inp) { + if (v == null) { + continue; + } + const m = mapper([k, v]); + if (m == null) { + continue; + } + acc.push(m); + } + return acc.length ? acc : null; +} +function queryJoin(...args) { + return args.filter(Boolean).join("&"); +} +function queryEncoder(f) { + const bulkEncode = function (values, options) { + var _a, _b, _c; + const opts = Object.assign(Object.assign({}, options), { explode: (_a = options === null || options === void 0 ? void 0 : options.explode) !== null && _a !== void 0 ? _a : true, charEncoding: (_b = options === null || options === void 0 ? void 0 : options.charEncoding) !== null && _b !== void 0 ? _b : "percent" }); + const allowEmptySet = new Set((_c = options === null || options === void 0 ? void 0 : options.allowEmptyValue) !== null && _c !== void 0 ? _c : []); + const encoded = Object.entries(values).map(([key, value]) => { + if (allowEmptySet.has(key)) { + if (value === undefined + || value === null + || value === "" + || (Array.isArray(value) && value.length === 0)) { + return `${encodeURIComponent(key)}=`; + } + } + return f(key, value, opts); + }); + return queryJoin(...encoded); + }; + return bulkEncode; +} +const encodeFormQuery = queryEncoder(encodeForm); + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +const DEFAULT_FETCHER = (input, init) => { + // If input is a Request and init is undefined, Bun will discard the method, + // headers, body and other options that were set on the request object. + // Node.js and browers would ignore an undefined init value. This check is + // therefore needed for interop with Bun. + if (init == null) { + return fetch(input); + } + else { + return fetch(input, init); + } +}; +class HTTPClient { + constructor(options = {}) { + this.requestHooks = []; + this.requestErrorHooks = []; + this.responseHooks = []; + this.options = options; + this.fetcher = options.fetcher || DEFAULT_FETCHER; + } + async request(request) { + let req = request; + for (const hook of this.requestHooks) { + const nextRequest = await hook(req); + if (nextRequest) { + req = nextRequest; + } + } + try { + const res = await this.fetcher(req); + for (const hook of this.responseHooks) { + await hook(res, req); + } + return res; + } + catch (err) { + for (const hook of this.requestErrorHooks) { + await hook(err, req); + } + throw err; + } + } + addHook(...args) { + if (args[0] === "beforeRequest") { + this.requestHooks.push(args[1]); + } + else if (args[0] === "requestError") { + this.requestErrorHooks.push(args[1]); + } + else if (args[0] === "response") { + this.responseHooks.push(args[1]); + } + else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + return this; + } + removeHook(...args) { + let target; + if (args[0] === "beforeRequest") { + target = this.requestHooks; + } + else if (args[0] === "requestError") { + target = this.requestErrorHooks; + } + else if (args[0] === "response") { + target = this.responseHooks; + } + else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + const index = target.findIndex((v) => v === args[1]); + if (index >= 0) { + target.splice(index, 1); + } + return this; + } + clone() { + const child = new HTTPClient(this.options); + child.requestHooks = this.requestHooks.slice(); + child.requestErrorHooks = this.requestErrorHooks.slice(); + child.responseHooks = this.responseHooks.slice(); + return child; + } +} +// A semicolon surrounded by optional whitespace characters is used to separate +// segments in a media type string. +const mediaParamSeparator = /\s*;\s*/g; +function matchContentType(response, pattern) { + var _a; + // `*` is a special case which means anything is acceptable. + if (pattern === "*") { + return true; + } + let contentType = ((_a = response.headers.get("content-type")) === null || _a === void 0 ? void 0 : _a.trim()) || "application/octet-stream"; + contentType = contentType.toLowerCase(); + const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); + const [wantType = "", ...wantParams] = wantParts; + if (wantType.split("/").length !== 2) { + return false; + } + const gotParts = contentType.split(mediaParamSeparator); + const [gotType = "", ...gotParams] = gotParts; + const [type = "", subtype = ""] = gotType.split("/"); + if (!type || !subtype) { + return false; + } + if (wantType !== "*/*" && + gotType !== wantType && + `${type}/*` !== wantType && + `*/${subtype}` !== wantType) { + return false; + } + if (gotParams.length < wantParams.length) { + return false; + } + const params = new Set(gotParams); + for (const wantParam of wantParams) { + if (!params.has(wantParam)) { + return false; + } + } + return true; +} +const codeRangeRE$1 = new RegExp("^[0-9]xx$", "i"); +function matchStatusCode(response, codes) { + const actual = `${response.status}`; + const expectedCodes = Array.isArray(codes) ? codes : [codes]; + if (!expectedCodes.length) { + return false; + } + return expectedCodes.some((ec) => { + const code = `${ec}`; + if (code === "default") { + return true; + } + if (!codeRangeRE$1.test(`${code}`)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); +} +function matchResponse(response, code, contentTypePattern) { + return (matchStatusCode(response, code) && + matchContentType(response, contentTypePattern)); +} +/** + * Uses various heurisitics to determine if an error is a connection error. + */ +function isConnectionError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + // Covers fetch in Deno as well + const isBrowserErr = err instanceof TypeError && + err.message.toLowerCase().startsWith("failed to fetch"); + const isNodeErr = err instanceof TypeError && + err.message.toLowerCase().startsWith("fetch failed"); + const isBunErr = "name" in err && err.name === "ConnectionError"; + const isGenericErr = "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnreset"; + return isBrowserErr || isNodeErr || isGenericErr || isBunErr; +} +/** + * Uses various heurisitics to determine if an error is a timeout error. + */ +function isTimeoutError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + // Fetch in browser, Node.js, Bun, Deno + const isNative = "name" in err && err.name === "TimeoutError"; + const isLegacyNative = "code" in err && err.code === 23; + // Node.js HTTP client and Axios + const isGenericErr = "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; +} +/** + * Uses various heurisitics to determine if an error is a abort error. + */ +function isAbortError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + // Fetch in browser, Node.js, Bun, Deno + const isNative = "name" in err && err.name === "AbortError"; + const isLegacyNative = "code" in err && err.code === 20; + // Node.js HTTP client and Axios + const isGenericErr = "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +const defaultBackoff = { + initialInterval: 500, + maxInterval: 60000, + exponent: 1.5, + maxElapsedTime: 3600000, +}; +/** + * PermanentError is an error that is not recoverable. Throwing this error will + * cause a retry loop to terminate. + */ +class PermanentError extends Error { + constructor(message, options) { + let msg = message; + if (options === null || options === void 0 ? void 0 : options.cause) { + msg += `: ${options.cause}`; + } + super(msg, options); + this.name = "PermanentError"; + // In older runtimes, the cause field would not have been assigned through + // the super() call. + if (typeof this.cause === "undefined") { + this.cause = options === null || options === void 0 ? void 0 : options.cause; + } + Object.setPrototypeOf(this, PermanentError.prototype); + } +} +/** + * TemporaryError is an error is used to signal that an HTTP request can be + * retried as part of a retry loop. If retry attempts are exhausted and this + * error is thrown, the response will be returned to the caller. + */ +class TemporaryError extends Error { + constructor(message, response) { + super(message); + this.response = response; + this.name = "TemporaryError"; + Object.setPrototypeOf(this, TemporaryError.prototype); + } +} +async function retry(fetchFn, options) { + var _a; + switch (options.config.strategy) { + case "backoff": + return retryBackoff(wrapFetcher(fetchFn, { + statusCodes: options.statusCodes, + retryConnectionErrors: !!options.config.retryConnectionErrors, + }), (_a = options.config.backoff) !== null && _a !== void 0 ? _a : defaultBackoff); + case "attempt-count-backoff": + return retryAttemptCountBackoff(wrapFetcher(fetchFn, { + statusCodes: options.statusCodes, + retryConnectionErrors: !!options.config.retryConnectionErrors, + }), Object.assign(Object.assign({}, defaultBackoff), options.config.backoff), options.config); + default: + return await fetchFn(0); + } +} +function wrapFetcher(fn, options) { + return async (attempt) => { + try { + const res = await fn(attempt); + if (isRetryableResponse(res, options.statusCodes)) { + throw new TemporaryError("Response failed with retryable status code", res); + } + return res; + } + catch (err) { + if (err instanceof TemporaryError) { + throw err; + } + if (options.retryConnectionErrors && + (isTimeoutError(err) || isConnectionError(err))) { + throw err; + } + throw new PermanentError("Permanent error", { cause: err }); + } + }; +} +const codeRangeRE = new RegExp("^[0-9]xx$", "i"); +function isRetryableResponse(res, statusCodes) { + const actual = `${res.status}`; + return statusCodes.some((code) => { + if (!codeRangeRE.test(code)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); +} +async function retryBackoff(fn, strategy) { + const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy; + const start = Date.now(); + let x = 0; + while (true) { + try { + const res = await fn(x); + return res; + } + catch (err) { + if (err instanceof PermanentError) { + throw err.cause; + } + const elapsed = Date.now() - start; + if (elapsed > maxElapsedTime) { + if (err instanceof TemporaryError) { + return err.response; + } + throw err; + } + let retryInterval = 0; + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); + } + if (retryInterval <= 0) { + retryInterval = + initialInterval * Math.pow(x, exponent) + Math.random() * 1000; + } + const d = Math.min(retryInterval, maxInterval); + await delay(d); + x++; + } + } +} +async function retryAttemptCountBackoff(fn, strategy, config) { + let attempt = 0; + while (true) { + try { + return await fn(attempt); + } + catch (err) { + if (err instanceof PermanentError) { + throw err.cause; + } + if (attempt >= config.maxRetries) { + if (err instanceof TemporaryError) { + return err.response; + } + throw err; + } + let retryInterval = 0; + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); + } + if (retryInterval <= 0) { + retryInterval = + strategy.initialInterval * + Math.pow(strategy.exponent, attempt) * + (1 - Math.random() * 0.25); + } + const d = Math.min(retryInterval, strategy.maxInterval); + await delay(d); + attempt++; + } + } +} +function retryIntervalFromResponse(res) { + const retryAfterMsVal = res.headers.get("retry-after-ms"); + if (retryAfterMsVal) { + const parsedMs = Number(retryAfterMsVal); + if (Number.isFinite(parsedMs) && parsedMs >= 0) { + return parsedMs; + } + } + const retryVal = res.headers.get("retry-after") || ""; + if (!retryVal) { + return 0; + } + const parsedNumber = Number(retryVal); + if (Number.isInteger(parsedNumber)) { + return parsedNumber * 1000; + } + const parsedDate = Date.parse(retryVal); + if (Number.isInteger(parsedDate)) { + const deltaMS = parsedDate - Date.now(); + return deltaMS > 0 ? Math.ceil(deltaMS) : 0; + } + return 0; +} +async function delay(delay) { + return new Promise((resolve) => setTimeout(resolve, delay)); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +const gt = typeof globalThis === "undefined" ? null : globalThis; +const webWorkerLike = typeof gt === "object" + && gt != null + && "importScripts" in gt + && typeof gt["importScripts"] === "function"; +const isBrowserLike = webWorkerLike + || (typeof navigator !== "undefined" && "serviceWorker" in navigator) + || (typeof window === "object" && typeof window.document !== "undefined"); +class ClientSDK { + constructor(options = {}) { + const opt = options; + if (typeof opt === "object" + && opt != null + && "hooks" in opt + && opt.hooks instanceof SDKHooks) { + this._hooks = opt.hooks; + } + else { + this._hooks = new SDKHooks(); + } + const defaultHttpClient = new HTTPClient(); + options.http_client = options.http_client || defaultHttpClient; + options = this._hooks.sdkInit(options); + const url = serverURLFromOptions(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + this._baseURL = url; + this._httpClient = options.http_client || defaultHttpClient; + this._options = Object.assign(Object.assign({}, fillGlobals(options)), { hooks: this._hooks }); + this._logger = this._options.debug_logger; + if (!this._logger && env().GOOGLE_GENAI_DEBUG) { + this._logger = console; + } + } + _createRequest(context, conf, options) { + var _a, _b, _c, _d, _e; + const { method, path, query, headers: opHeaders, security } = conf; + const base = (_a = conf.baseURL) !== null && _a !== void 0 ? _a : this._baseURL; + if (!base) { + return ERR(new InvalidRequestError("No base URL provided for operation")); + } + const baseURL = new URL(base); + let reqURL; + if (path) { + baseURL.pathname = baseURL.pathname.replace(/\/+$/, "") + "/"; + reqURL = new URL(path, baseURL); + if (!reqURL.search && baseURL.search) { + reqURL.search = baseURL.search; + } + } + else { + reqURL = baseURL; + } + reqURL.hash = ""; + // Appends already-encoded query pairs to a query string, replacing any + // existing pairs with the same key so later sources take precedence. + const mergeQuery = (current, additions) => { + if (!additions) { + return current; + } + const additionKeys = new Set(additions + .split("&") + .filter((pair) => pair !== "") + .map((pair) => { var _a; return (_a = pair.split("=")[0]) !== null && _a !== void 0 ? _a : ""; })); + const kept = current.split("&").filter((pair) => { + var _a; + return pair !== "" && !additionKeys.has((_a = pair.split("=")[0]) !== null && _a !== void 0 ? _a : ""); + }); + return [...kept, additions].join("&"); + }; + const encodeQueryRecord = (record) => { + return Object.entries(record) + .map(([k, v]) => { + if (v == null) { + return undefined; + } + const value = isPlainObject$1(v) ? JSON.stringify(v) : v; + return encodeForm(k, value, { + explode: Array.isArray(value), + charEncoding: "percent", + }); + }) + .filter((pair) => typeof pair !== "undefined") + .join("&"); + }; + const finalQuery = [ + query || "", + encodeQueryRecord((options === null || options === void 0 ? void 0 : options.extra_query) || {}), + encodeQueryRecord((security === null || security === void 0 ? void 0 : security.queryParams) || {}), + ].reduce(mergeQuery, reqURL.search.slice(1)); + if (finalQuery) { + reqURL.search = `?${finalQuery}`; + } + const headers = new Headers(opHeaders); + const username = security === null || security === void 0 ? void 0 : security.basic.username; + const password = security === null || security === void 0 ? void 0 : security.basic.password; + if (username != null || password != null) { + const encoded = stringToBase64([username || "", password || ""].join(":")); + headers.set("Authorization", `Basic ${encoded}`); + } + const securityHeaders = new Headers((security === null || security === void 0 ? void 0 : security.headers) || {}); + for (const [k, v] of securityHeaders) { + headers.set(k, v); + } + let cookie = headers.get("cookie") || ""; + for (const [k, v] of Object.entries((security === null || security === void 0 ? void 0 : security.cookies) || {})) { + cookie += `; ${k}=${v}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); + const userHeaders = new Headers((_b = options === null || options === void 0 ? void 0 : options.headers) !== null && _b !== void 0 ? _b : (_c = options === null || options === void 0 ? void 0 : options.fetch_options) === null || _c === void 0 ? void 0 : _c.headers); + for (const [k, v] of userHeaders) { + headers.set(k, v); + } + // Only set user agent header in non-browser-like environments since CORS + // policy disallows setting it in browsers e.g. Chrome throws an error. + if (!isBrowserLike) { + headers.set((_d = conf.uaHeader) !== null && _d !== void 0 ? _d : "user-agent", (_e = conf.userAgent) !== null && _e !== void 0 ? _e : SDK_METADATA.userAgent); + } + let reqBody = conf.body; + const extraBody = Object.fromEntries(Object.entries((options === null || options === void 0 ? void 0 : options.extra_body) || {}).filter(([, v]) => typeof v !== "undefined")); + if (Object.keys(extraBody).length > 0) { + const contentType = new Headers(opHeaders).get("content-type") || ""; + const isJSON = /^(application|text)\/([^+]+\+)*json/.test(contentType); + if (!isJSON || (typeof reqBody !== "string" && reqBody != null)) { + return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies")); + } + let parsedBody; + try { + parsedBody = reqBody ? JSON.parse(reqBody) : {}; + } + catch (err) { + return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies", { cause: err })); + } + if (!isPlainObject$1(parsedBody)) { + return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies")); + } + reqBody = JSON.stringify(Object.assign(Object.assign({}, parsedBody), extraBody)); + headers.delete("content-length"); + } + const fetchOptions = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.fetch_options), options); + if (!(fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions.signal) && conf.timeout_ms != null && conf.timeout_ms > 0) { + context.timeout_ms = conf.timeout_ms; + } + if (conf.body instanceof ReadableStream) { + Object.assign(fetchOptions, { duplex: "half" }); + } + let input; + try { + input = this._hooks.beforeCreateRequest(context, { + url: reqURL, + options: Object.assign(Object.assign({}, fetchOptions), { body: reqBody !== null && reqBody !== void 0 ? reqBody : null, headers, + method }), + }); + } + catch (err) { + return ERR(new UnexpectedClientError("Create request hook failed to execute", { + cause: err, + })); + } + return OK(new Request(input.url, input.options)); + } + async _do(request, options) { + const { context, isErrorStatusCode } = options; + const timeout_ms = context.timeout_ms; + return retry(async () => { + var _a; + const cloned = request.clone(); + let attempt = cloned; + if (timeout_ms != null && timeout_ms > 0) { + const timeoutSignal = AbortSignal.timeout(timeout_ms); + const combined = (_a = combineSignals(cloned.signal, timeoutSignal)) !== null && _a !== void 0 ? _a : timeoutSignal; + attempt = new Request(cloned, { signal: combined }); + } + const req = await this._hooks.beforeRequest(context, attempt); + await logRequest(this._logger, req).catch((e) => { var _a; return (_a = this._logger) === null || _a === void 0 ? void 0 : _a.log("Failed to log request:", e); }); + let response = await this._httpClient.request(req); + try { + if (isErrorStatusCode(response.status)) { + const result = await this._hooks.afterError(context, response, null); + if (result.error) { + throw result.error; + } + response = result.response || response; + } + else { + response = await this._hooks.afterSuccess(context, response); + } + } + finally { + await logResponse(this._logger, response, req) + .catch(e => { var _a; return (_a = this._logger) === null || _a === void 0 ? void 0 : _a.log("Failed to log response:", e); }); + } + return response; + }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r) => OK(r), (err) => { + switch (true) { + case isAbortError(err): + return ERR(new RequestAbortedError("Request aborted by client", { + cause: err, + })); + case isTimeoutError(err): + return ERR(new RequestTimeoutError("Request timed out", { cause: err })); + case isConnectionError(err): + return ERR(new ConnectionError("Unable to make request", { cause: err })); + default: + return ERR(new UnexpectedClientError("Unexpected HTTP client error", { + cause: err, + })); + } + }); + } +} +const jsonLikeContentTypeRE = /^(application|text)\/([^+]+\+)*json.*/; +const jsonlLikeContentTypeRE = /^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/; +async function logRequest(logger, req) { + if (!logger) { + return; + } + const contentType = req.headers.get("content-type"); + const ct = (contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) || ""; + logger.group(`> Request: ${req.method} ${req.url}`); + logger.group("Headers:"); + for (const [k, v] of req.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + logger.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; + } + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); + logger.groupEnd(); +} +async function logResponse(logger, res, req) { + if (!logger) { + return; + } + const contentType = res.headers.get("content-type"); + const ct = (contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) || ""; + logger.group(`< Response: ${req.method} ${req.url}`); + logger.log("Status Code:", res.status, res.statusText); + logger.group("Headers:"); + for (const [k, v] of res.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + logger.group("Body:"); + switch (true) { + case matchContentType(res, "application/json") + || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct): + logger.log(await res.clone().json()); + break; + case matchContentType(res, "application/jsonl") + || jsonlLikeContentTypeRE.test(ct): + case matchContentType(res, "text/event-stream"): + logger.log(`<${contentType}>`); + break; + case matchContentType(res, "text/*"): + logger.log(await res.clone().text()); + break; + case matchContentType(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; + } + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); + logger.groupEnd(); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +/** The fallback error class if no more specific error class is matched */ +class GoogleGenAiDefaultError extends GoogleGenAiError { + constructor(message, httpMeta) { + if (message) { + message += `: `; + } + message += `Status ${httpMeta.response.status}`; + const contentType = httpMeta.response.headers.get("content-type") || `""`; + if (contentType !== "application/json") { + message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`; + } + const body = httpMeta.body || `""`; + message += body.length > 100 ? "\n" : ". "; + let bodyDisplay = body; + if (body.length > 10000) { + const truncated = body.substring(0, 10000); + const remaining = body.length - 10000; + bodyDisplay = `${truncated}...and ${remaining} more chars`; + } + message += `Body: ${bodyDisplay}`; + message = message.trim(); + super(message, httpMeta); + this.name = "GoogleGenAiDefaultError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +function tryParseJson(s) { + try { + return JSON.parse(s); + } + catch (_a) { + return s; + } +} +function wrapEventStreamResponse(body, opts = {}) { + var _a, _b; + const flattened = opts.flattened === true; + const sentinel = (_a = opts.sentinel) !== null && _a !== void 0 ? _a : ""; + return new Stream(body, (rawEvent) => { + if (sentinel !== "" && rawEvent.data === sentinel) { + return { done: true, value: undefined }; + } + if (flattened) { + const data = rawEvent.data == null + ? undefined + : tryParseJson(rawEvent.data); + return { done: false, value: data }; + } + return { + done: false, + value: Object.assign(Object.assign({}, rawEvent), { data: rawEvent.data == null + ? rawEvent.data + : tryParseJson(rawEvent.data) }), + }; + }, { dataRequired: (_b = opts.dataRequired) !== null && _b !== void 0 ? _b : true }); +} +class Stream extends ReadableStream { + constructor(responseBody, parse, opts) { + var _a; + const upstream = responseBody.getReader(); + let buffer = new Uint8Array(4096); + let bufferLen = 0; + let searchStart = 0; + const state = { eventId: undefined }; + const dataRequired = (_a = opts === null || opts === void 0 ? void 0 : opts.dataRequired) !== null && _a !== void 0 ? _a : true; + super({ + async pull(downstream) { + try { + while (true) { + const match = findBoundary(buffer, bufferLen, searchStart); + if (!match) { + // Bytes before the trailing MAX_BOUNDARY_LEN-1 were already + // scanned with full lookahead and cannot start a boundary even + // once more data arrives, so the next scan can skip them. + searchStart = Math.max(0, bufferLen - MAX_BOUNDARY_LEN + 1); + const chunk = await upstream.read(); + if (chunk.done) + return downstream.close(); + if (bufferLen + chunk.value.length > buffer.length) { + const grown = new Uint8Array(Math.max(buffer.length * 2, bufferLen + chunk.value.length)); + grown.set(buffer.subarray(0, bufferLen)); + buffer = grown; + } + buffer.set(chunk.value, bufferLen); + bufferLen += chunk.value.length; + continue; + } + const message = buffer.slice(0, match.index); + buffer.copyWithin(0, match.index + match.length, bufferLen); + bufferLen -= match.index + match.length; + if (buffer.length > 4096 && bufferLen <= buffer.length >> 2) { + // Release oversized capacity retained after an unusually large + // event so long-lived streams do not hold peak memory. + const shrunk = new Uint8Array(Math.max(4096, bufferLen * 2)); + shrunk.set(buffer.subarray(0, bufferLen)); + buffer = shrunk; + } + searchStart = 0; + const item = parseMessage(message, parse, state, dataRequired); + if (item && !item.done) + return downstream.enqueue(item.value); + if (item === null || item === void 0 ? void 0 : item.done) { + await upstream.cancel("done"); + return downstream.close(); + } + } + } + catch (e) { + downstream.error(e); + await upstream.cancel(e); + } + }, + cancel: reason => upstream.cancel(reason), + }); + } + [Symbol.asyncIterator](options) { + const fn = ReadableStream.prototype[Symbol.asyncIterator]; + if (typeof fn === "function") + return fn.call(this, options); + const reader = this.getReader(); + const iterator = { + next: async () => { + const r = await reader.read(); + if (r.done) { + reader.releaseLock(); + return { done: true, value: undefined }; + } + return { done: false, value: r.value }; + }, + throw: async (e) => { + await reader.cancel(e); + reader.releaseLock(); + return { done: true, value: undefined }; + }, + return: async () => { + await reader.cancel("done"); + reader.releaseLock(); + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + const asyncDispose = Symbol.asyncDispose; + if (asyncDispose) { + iterator[asyncDispose] = async () => { + var _a; + await ((_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator)); + }; + } + return iterator; + } + values(options) { + return this[Symbol.asyncIterator](options); + } +} +const CR = 13; +const LF = 10; +const BOUNDARIES = [ + [CR, LF, CR, LF], // \r\n\r\n + [CR, LF, CR], // \r\n\r + [CR, LF, LF], // \r\n\n + [CR, CR, LF], // \r\r\n + [LF, CR, LF], // \n\r\n + [CR, CR], // \r\r + [LF, CR], // \n\r + [LF, LF], // \n\n +]; +const MAX_BOUNDARY_LEN = BOUNDARIES.reduce((m, b) => Math.max(m, b.length), 0); +function findBoundary(buf, len, from) { + for (let i = from; i < len; i++) { + if (buf[i] !== CR && buf[i] !== LF) + continue; + for (const boundary of BOUNDARIES) { + if (i + boundary.length > len) + continue; + let match = true; + for (let j = 0; j < boundary.length; j++) { + if (buf[i + j] !== boundary[j]) { + match = false; + break; + } + } + if (match) + return { index: i, length: boundary.length }; + } + } + return null; +} +function parseMessage(chunk, parse, state, dataRequired) { + const text = new TextDecoder().decode(chunk); + const lines = text.split(/\r\n|\r|\n/); + const dataLines = []; + const ret = {}; + let ignore = true; + for (const line of lines) { + if (!line || line.startsWith(":")) + continue; + ignore = false; + const i = line.indexOf(":"); + let field = line; + let value = ""; + if (i > 0) { + field = line.slice(0, i); + value = line[i + 1] === " " ? line.slice(i + 2) : line.slice(i + 1); + } + if (field === "data") + dataLines.push(value); + else if (field === "event") + ret.event = value; + else if (field === "id" && !value.includes("\0")) + state.eventId = value; + else if (field === "retry" && /^\d+$/.test(value)) { + ret.retry = Number(value); + } + } + if (ignore) + return; + ret.id = state.eventId; + if (dataLines.length) + ret.data = dataLines.join("\n"); + else if (dataRequired) + return; // skip data-less events when data is required + return parse(ret); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +const DEFAULT_CONTENT_TYPES = { + jsonl: "application/jsonl", + json: "application/json", + text: "text/plain", + bytes: "application/octet-stream", + stream: "application/octet-stream", + sse: "text/event-stream", + nil: "*", + fail: "*", +}; +function jsonErr(codes, errorClass, options) { + return Object.assign(Object.assign({}, options), { err: true, enc: "json", codes, errorClass }); +} +function json(codes, options) { + return Object.assign(Object.assign({}, options), { enc: "json", codes }); +} +function sse(codes, sse, options) { + return Object.assign(Object.assign(Object.assign({}, options), { enc: "sse", codes }), (sse ? { sse } : {})); +} +function nil(codes, options) { + return Object.assign(Object.assign({}, options), { enc: "nil", codes }); +} +function fail(codes) { + return { enc: "fail", codes }; +} +function match(...matchers) { + return async function matchFunc(response, request, options) { + let raw; + let matcher; + for (const match of matchers) { + const { codes } = match; + const ctpattern = "ctype" in match + ? match.ctype + : DEFAULT_CONTENT_TYPES[match.enc]; + if (ctpattern && matchResponse(response, codes, ctpattern)) { + matcher = match; + break; + } + else if (!ctpattern && matchStatusCode(response, codes)) { + matcher = match; + break; + } + } + if (!matcher) { + return [{ + ok: false, + error: new GoogleGenAiDefaultError("Unexpected Status or Content-Type", { + response, + request, + body: await response.text().catch(() => ""), + }), + }, raw]; + } + const encoding = matcher.enc; + let body = ""; + switch (encoding) { + case "json": + body = await response.text(); + try { + raw = JSON.parse(body); + } + catch (err) { + // Passthrough for malformed error bodies; success bodies must be valid. + if (!("err" in matcher)) { + throw err; + } + raw = body; + } + break; + case "jsonl": + raw = response.body; + break; + case "bytes": + raw = new Uint8Array(await response.arrayBuffer()); + break; + case "stream": + raw = response.body; + break; + case "text": + body = await response.text(); + raw = body; + break; + case "sse": + if (response.body) { + const sseOpts = ("sse" in matcher && matcher.sse) || {}; + raw = wrapEventStreamResponse(response.body, sseOpts); + } + else { + raw = null; + } + break; + case "nil": + body = await response.text(); + raw = undefined; + break; + case "fail": + body = await response.text(); + raw = body; + break; + default: + throw new Error(`Unsupported response type: ${encoding}`); + } + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new GoogleGenAiDefaultError("API error occurred", { + request, + response, + body, + }), + }, raw]; + } + const resultKey = matcher.key || (options === null || options === void 0 ? void 0 : options.resultKey); + let data; + const headersField = matcher.hdrs + ? { headers: unpackHeaders(response.headers) } + : null; + if ("err" in matcher) { + data = Object.assign(Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.extraFields), headersField), (isPlainObject$1(raw) ? raw : null)); + } + else if (resultKey) { + data = Object.assign(Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.extraFields), headersField), { [resultKey]: raw }); + } + else if (matcher.hdrs) { + data = Object.assign(Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.extraFields), headersField), (isPlainObject$1(raw) ? raw : null)); + } + else { + data = raw; + } + if ("err" in matcher) { + // When the spec error response is a single error class, instantiate + // it with the data + httpMeta. When the spec defines a discriminated + // union of error variants (no class), `errorClass` is undefined and + // we pass the parsed payload through as the error value directly. + const errValue = matcher.errorClass + ? new matcher.errorClass(data, { request, response, body }) + : data; + return [{ ok: false, error: errValue }, raw]; + } + return [{ ok: true, value: data }, raw]; + }; +} +const headerValRE = /, */; +/** + * Iterates over a Headers object and returns an object with all the header + * entries. Values are represented as an array to account for repeated headers. + */ +function unpackHeaders(headers) { + const out = {}; + for (const [k, v] of headers.entries()) { + out[k] = v.split(headerValRE); + } + return out; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +const SecurityErrorCode = { + Incomplete: "incomplete", + UnrecognisedSecurityType: "unrecognized_security_type", +}; +class SecurityError extends Error { + constructor(code, message) { + super(message); + this.code = code; + this.name = "SecurityError"; + } + static incomplete() { + return new SecurityError(SecurityErrorCode.Incomplete, "Security requirements not met in order to perform the operation"); + } + static unrecognizedType(type) { + return new SecurityError(SecurityErrorCode.UnrecognisedSecurityType, `Unrecognised security type: ${type}`); + } +} +function resolveSecurity(...options) { + const state = { + basic: {}, + headers: {}, + queryParams: {}, + cookies: {}, + oauth2: { type: "none" }, + }; + const option = options.find((opts) => { + return opts.every((o) => { + if (o.value == null) { + return false; + } + else if (o.type === "http:basic") { + return o.value.username != null || o.value.password != null; + } + else if (o.type === "http:custom") { + return null; + } + else if (o.type === "oauth2:password") { + return (typeof o.value === "string" && !!o.value); + } + else if (o.type === "oauth2:client_credentials") { + if (typeof o.value == "string") { + return !!o.value; + } + return o.value.client_id != null || o.value.client_secret != null; + } + else if (typeof o.value === "string") { + return !!o.value; + } + else { + throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o + .value})`); + } + }); + }); + if (option == null) { + return null; + } + option.forEach((spec) => { + if (spec.value == null) { + return; + } + const { type } = spec; + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:password": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + throw SecurityError.unrecognizedType((type)); + } + }); + return state; +} +function applyBasic(state, spec) { + if (spec.value == null) { + return; + } + state.basic = spec.value; +} +function applyBearer(state, spec) { + if (typeof spec.value !== "string" || !spec.value) { + return; + } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } + if (spec.fieldName !== undefined) { + state.headers[spec.fieldName] = value; + } +} +function resolveGlobalSecurity(security, allowedFields) { + var _a, _b; + let inputs = [ + [ + { + fieldName: "accessToken", + type: "http:custom", + value: (_a = security === null || security === void 0 ? void 0 : security.access_token) !== null && _a !== void 0 ? _a : env().GOOGLE_GENAI_ACCESS_TOKEN, + }, + { + fieldName: "apiKey", + type: "http:custom", + value: (_b = security === null || security === void 0 ? void 0 : security.api_key) !== null && _b !== void 0 ? _b : env().GOOGLE_GENAI_API_KEY, + }, + { + fieldName: "defaultHeaders", + type: "http:custom", + value: security === null || security === void 0 ? void 0 : security.default_headers, + }, + ], + ]; + return resolveSecurity(...inputs); +} +async function extractSecurity(sec) { + if (sec == null) { + return; + } + return typeof sec === "function" ? sec() : sec; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +var _a; +class APIPromise { + constructor(p, callSource) { + this[_a] = "APIPromise"; + this._promise = p instanceof Promise ? p : Promise.resolve(p); + this._unwrapped = p instanceof Promise ? null : Promise.resolve(p[0]); + this._callSource = callSource !== null && callSource !== void 0 ? callSource : null; + } + _getUnwrapped() { + var _b; + return ((_b = this._unwrapped) !== null && _b !== void 0 ? _b : (this._unwrapped = this._promise.then(([value]) => value))); + } + then(onfulfilled, onrejected) { + return this._promise.then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected); + } + catch(onrejected) { + return this._getUnwrapped().catch(onrejected); + } + finally(onfinally) { + return this._getUnwrapped().finally(onfinally); + } + $inspect() { + return this._promise; + } + asResponse() { + var _b; + const src = ((_b = this._callSource) !== null && _b !== void 0 ? _b : (this._callSource = this._promise.then(([, call]) => call))); + return src.then((call) => { + if (!call.response) { + throw new Error("APIPromise.asResponse: response unavailable"); + } + return call.response; + }); + } + async withResponse() { + const [[data], response] = await Promise.all([ + this._promise, + this.asResponse(), + ]); + return { data, response }; + } + _thenUnwrap(transform) { + var _b; + const data = this._promise.then(([value, call]) => [transform(value), call]); + data.catch(() => { }); + return new APIPromise(data, (_b = this._callSource) !== null && _b !== void 0 ? _b : undefined); + } +} +_a = Symbol.toStringTag; +function unwrapAsAPIPromise(p) { + const inner = p.$inspect(); + const data = inner.then(([r, call]) => { + if (!r.ok) { + throw r.error; + } + return [r.value, call]; + }); + const callSource = inner.then(([r, call]) => { + var _b; + if (!r.ok && !((_b = call.response) === null || _b === void 0 ? void 0 : _b.ok)) { + throw r.error; + } + return call; + }); + data.catch(() => { }); + callSource.catch(() => { }); + return new APIPromise(data, callSource); +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Creates a new Agent (Typed version for SDK). + */ +function agentsCreate(client, body, api_version, options) { + return new APIPromise($do$q(client, body, api_version, options)); +} +async function $do$q(client, body, api_version, options) { + var _a, _b, _c; + const input = { + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/agents")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "CreateAgent", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Deletes an Agent. + */ +function agentsDelete(client, id, api_version, options) { + return new APIPromise($do$p(client, id, api_version, options)); +} +async function $do$p(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/agents/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "DeleteAgent", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Gets a specific Agent. + */ +function agentsGet(client, id, api_version, options) { + return new APIPromise($do$o(client, id, api_version, options)); +} +async function $do$o(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/agents/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "GetAgent", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Lists all Agents. + */ +function agentsList(client, api_version, page_size, page_token, parent, options) { + return new APIPromise($do$n(client, api_version, page_size, page_token, parent, options)); +} +async function $do$n(client, api_version, page_size, page_token, parent, options) { + var _a, _b, _c; + const input = { + api_version: api_version, + page_size: page_size, + page_token: page_token, + parent: parent, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload === null || payload === void 0 ? void 0 : payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/agents")(pathParams); + const query = encodeFormQuery({ + "page_size": payload === null || payload === void 0 ? void 0 : payload.page_size, + "page_token": payload === null || payload === void 0 ? void 0 : payload.page_token, + "parent": payload === null || payload === void 0 ? void 0 : payload.parent, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "ListAgents", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class Agents extends ClientSDK { + /** + * Lists all Agents. + */ + list(params, options) { + return unwrapAsAPIPromise(agentsList(this, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, params === null || params === void 0 ? void 0 : params.parent, options)); + } + /** + * Creates a new Agent (Typed version for SDK). + */ + create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapAsAPIPromise(agentsCreate(this, body, api_version, options)); + } + /** + * Deletes an Agent. + */ + delete(id, params, options) { + return unwrapAsAPIPromise(agentsDelete(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Gets a specific Agent. + */ + get(id, params, options) { + return unwrapAsAPIPromise(agentsGet(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Creates an environment. + */ +function environmentsCreateEnvironment(client, body, api_version, options) { + return new APIPromise($do$m(client, body, api_version, options)); +} +async function $do$m(client, body, api_version, options) { + var _a, _b, _c; + const input = { + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/environments")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "CreateEnvironment", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Deletes an environment. + */ +function environmentsDeleteEnvironment(client, id, api_version, options) { + return new APIPromise($do$l(client, id, api_version, options)); +} +async function $do$l(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/environments/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "DeleteEnvironment", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Gets an environment. + */ +function environmentsGetEnvironment(client, id, api_version, options) { + return new APIPromise($do$k(client, id, api_version, options)); +} +async function $do$k(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/environments/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "GetEnvironment", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Lists environments. + */ +function environmentsListEnvironments(client, api_version, page_size, page_token, options) { + return new APIPromise($do$j(client, api_version, page_size, page_token, options)); +} +async function $do$j(client, api_version, page_size, page_token, options) { + var _a, _b, _c; + const input = { + api_version: api_version, + page_size: page_size, + page_token: page_token, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload === null || payload === void 0 ? void 0 : payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/environments")(pathParams); + const query = encodeFormQuery({ + "page_size": payload === null || payload === void 0 ? void 0 : payload.page_size, + "page_token": payload === null || payload === void 0 ? void 0 : payload.page_token, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "ListEnvironments", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Retrieves file metadata or directory contents from an environment's snapshot. To download file contents directly, pass ?alt=media or use the files.download helper. + */ +function environmentsFilesList(client, environment, path, api_version, page_size, page_token, recursive, options) { + return new APIPromise($do$i(client, environment, path, api_version, page_size, page_token, recursive, options)); +} +async function $do$i(client, environment, path, api_version, page_size, page_token, recursive, options) { + var _a, _b, _c; + const input = { + environment: environment, + path: path, + api_version: api_version, + page_size: page_size, + page_token: page_token, + recursive: recursive, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + environment: encodeSimple("environment", payload.environment, { + explode: false, + charEncoding: "percent", + }), + path: encodeSimple("path", payload.path, { + explode: false, + charEncoding: "percent", + }), + }; + const path$ = pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams); + const query = encodeFormQuery({ + "page_size": payload.page_size, + "page_token": payload.page_token, + "recursive": payload.recursive, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "GetEnvironmentFiles", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path$, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +class Files extends ClientSDK { + /** + * Retrieves file metadata or directory contents from an environment's snapshot. To download file contents directly, pass ?alt=media or use the files.download helper. + */ + list(environment, path, params, options) { + return unwrapAsAPIPromise(environmentsFilesList(this, environment, path, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, params === null || params === void 0 ? void 0 : params.recursive, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +class Environments extends ClientSDK { + get files() { + var _a; + return ((_a = this._files) !== null && _a !== void 0 ? _a : (this._files = new Files(this._options))); + } + /** + * Lists environments. + */ + listEnvironments(params, options) { + return unwrapAsAPIPromise(environmentsListEnvironments(this, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, options)); + } + /** + * Creates an environment. + */ + createEnvironment(body, api_version, options) { + return unwrapAsAPIPromise(environmentsCreateEnvironment(this, body, api_version, options)); + } + /** + * Deletes an environment. + */ + deleteEnvironment(id, params, options) { + return unwrapAsAPIPromise(environmentsDeleteEnvironment(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Gets an environment. + */ + getEnvironment(id, params, options) { + return unwrapAsAPIPromise(environmentsGetEnvironment(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Error cancelling interaction + */ +class CancelInteractionByIdServerError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "CancelInteractionByIdServerError"; + } +} +/** + * Error cancelling interaction + */ +class CancelInteractionByIdClientError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "CancelInteractionByIdClientError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Error creating interaction + */ +class CreateInteractionServerError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "CreateInteractionServerError"; + } +} +/** + * Error creating interaction + */ +class CreateInteractionClientError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "CreateInteractionClientError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Error deleting interaction + */ +class DeleteInteractionServerError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "DeleteInteractionServerError"; + } +} +/** + * Error deleting interaction + */ +class DeleteInteractionClientError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "DeleteInteractionClientError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Error getting interaction + */ +class GetInteractionByIdServerError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "GetInteractionByIdServerError"; + } +} +/** + * Error getting interaction + */ +class GetInteractionByIdClientError extends GoogleGenAiError { + constructor(err, httpMeta) { + var _a; + const message = ((_a = err.error) === null || _a === void 0 ? void 0 : _a.message) + || `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + this.error = err.error; + this.name = "GetInteractionByIdClientError"; + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Canceling an interaction + * + * @remarks + * Cancels an interaction by id. This only applies to background interactions that are still running. + */ +function interactionsCancel(client, id, api_version, options) { + return new APIPromise($do$h(client, id, api_version, options)); +} +async function $do$h(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "cancelInteractionById", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + httpMeta: { response: response, request: req }, + }; + const [result] = await match(json(200), jsonErr("4XX", CancelInteractionByIdClientError), jsonErr("5XX", CancelInteractionByIdServerError))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +function interactionsCreate(client, body, api_version, options) { + return new APIPromise($do$g(client, body, api_version, options)); +} +async function $do$g(client, body, api_version, options) { + var _a, _b, _c, _d; + const input = { + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/interactions")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: ((_b = input === null || input === void 0 ? void 0 : input.body) === null || _b === void 0 ? void 0 : _b.stream) ? "text/event-stream" : "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_d = (_c = options === null || options === void 0 ? void 0 : options.server_url) !== null && _c !== void 0 ? _c : client._baseURL) !== null && _d !== void 0 ? _d : "", + operation_id: "CreateInteraction", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + httpMeta: { response: response, request: req }, + }; + const [result] = await match(json(200), sse(200, { + sentinel: "[DONE]", + flattened: true, + }), jsonErr("4XX", CreateInteractionClientError), jsonErr("5XX", CreateInteractionServerError))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Deleting an interaction + * + * @remarks + * Deletes the interaction by id. + */ +function interactionsDelete(client, id, api_version, options) { + return new APIPromise($do$f(client, id, api_version, options)); +} +async function $do$f(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/interactions/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "deleteInteraction", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + httpMeta: { response: response, request: req }, + }; + const [result] = await match(nil(200), jsonErr("4XX", DeleteInteractionClientError), jsonErr("5XX", DeleteInteractionServerError))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +function interactionsGet(client, id, api_version, include_input, last_event_id, stream, options) { + return new APIPromise($do$e(client, id, api_version, include_input, last_event_id, stream, options)); +} +async function $do$e(client, id, api_version, include_input, last_event_id, stream, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + include_input: include_input, + last_event_id: last_event_id, + stream: stream, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/interactions/{id}")(pathParams); + const query = encodeFormQuery({ + "include_input": payload.include_input, + "last_event_id": payload.last_event_id, + "stream": payload.stream, + }); + const headers = new Headers(compactMap({ + Accept: (input === null || input === void 0 ? void 0 : input.stream) ? "text/event-stream" : "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "getInteractionById", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + httpMeta: { response: response, request: req }, + }; + const [result] = await match(json(200), sse(200, { + sentinel: "[DONE]", + flattened: true, + }), jsonErr("4XX", GetInteractionByIdClientError), jsonErr("5XX", GetInteractionByIdServerError))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class Interactions extends ClientSDK { + create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapAsAPIPromise(interactionsCreate(this, body, api_version, options)); + } + /** + * Deleting an interaction + * + * @remarks + * Deletes the interaction by id. + */ + delete(id, params, options) { + return unwrapAsAPIPromise(interactionsDelete(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + get(id, params, options) { + return unwrapAsAPIPromise(interactionsGet(this, id, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.include_input, params === null || params === void 0 ? void 0 : params.last_event_id, params === null || params === void 0 ? void 0 : params.stream, options)); + } + /** + * Canceling an interaction + * + * @remarks + * Cancels an interaction by id. This only applies to background interactions that are still running. + */ + cancel(id, params, options) { + return unwrapAsAPIPromise(interactionsCancel(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Creates a new trigger that will invoke the specified agent on the given cron schedule. + */ +function triggersCreate(client, body, api_version, options) { + return new APIPromise($do$d(client, body, api_version, options)); +} +async function $do$d(client, body, api_version, options) { + var _a, _b, _c; + const input = { + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/triggers")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "CreateTrigger", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Deletes a trigger. + */ +function triggersDelete(client, id, api_version, options) { + return new APIPromise($do$c(client, id, api_version, options)); +} +async function $do$c(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/triggers/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "DeleteTrigger", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Gets details of a single trigger. + */ +function triggersGet(client, id, api_version, options) { + return new APIPromise($do$b(client, id, api_version, options)); +} +async function $do$b(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/triggers/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "GetTrigger", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Lists executions for a trigger. + */ +function triggersListExecutions(client, trigger_id, api_version, page_size, page_token, options) { + return new APIPromise($do$a(client, trigger_id, api_version, page_size, page_token, options)); +} +async function $do$a(client, trigger_id, api_version, page_size, page_token, options) { + var _a, _b, _c; + const input = { + trigger_id: trigger_id, + api_version: api_version, + page_size: page_size, + page_token: page_token, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + trigger_id: encodeSimple("trigger_id", payload.trigger_id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams); + const query = encodeFormQuery({ + "page_size": payload.page_size, + "page_token": payload.page_token, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "ListTriggerExecutions", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Lists triggers for a project. + */ +function triggersList(client, api_version, filter, page_size, page_token, options) { + return new APIPromise($do$9(client, api_version, filter, page_size, page_token, options)); +} +async function $do$9(client, api_version, filter, page_size, page_token, options) { + var _a, _b, _c; + const input = { + api_version: api_version, + filter: filter, + page_size: page_size, + page_token: page_token, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload === null || payload === void 0 ? void 0 : payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/triggers")(pathParams); + const query = encodeFormQuery({ + "filter": payload === null || payload === void 0 ? void 0 : payload.filter, + "page_size": payload === null || payload === void 0 ? void 0 : payload.page_size, + "page_token": payload === null || payload === void 0 ? void 0 : payload.page_token, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "ListTriggers", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Runs a trigger immediately. + */ +function triggersRun(client, trigger_id, api_version, options) { + return new APIPromise($do$8(client, trigger_id, api_version, options)); +} +async function $do$8(client, trigger_id, api_version, options) { + var _a, _b, _c; + const input = { + trigger_id: trigger_id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + trigger_id: encodeSimple("trigger_id", payload.trigger_id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "RunTrigger", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Updates a trigger. + */ +function triggersUpdate(client, id, body, api_version, options) { + return new APIPromise($do$7(client, id, body, api_version, options)); +} +async function $do$7(client, id, body, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/triggers/{id}")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "UpdateTrigger", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(json(200), fail("4XX"), fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class Triggers extends ClientSDK { + /** + * Lists triggers for a project. + */ + list(params, options) { + return unwrapAsAPIPromise(triggersList(this, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.filter, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, options)); + } + /** + * Creates a new trigger that will invoke the specified agent on the given cron schedule. + */ + create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapAsAPIPromise(triggersCreate(this, body, api_version, options)); + } + /** + * Deletes a trigger. + */ + delete(id, params, options) { + return unwrapAsAPIPromise(triggersDelete(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Gets details of a single trigger. + */ + get(id, params, options) { + return unwrapAsAPIPromise(triggersGet(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Updates a trigger. + */ + update(id, params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapAsAPIPromise(triggersUpdate(this, id, body, api_version, options)); + } + /** + * Lists executions for a trigger. + */ + listExecutions(trigger_id, params, options) { + return unwrapAsAPIPromise(triggersListExecutions(this, trigger_id, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, options)); + } + /** + * Runs a trigger immediately. + */ + run(trigger_id, params, options) { + return unwrapAsAPIPromise(triggersRun(this, trigger_id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Creates a new Webhook. + */ +function webhooksCreate(client, body, api_version, options) { + return new APIPromise($do$6(client, body, api_version, options)); +} +async function $do$6(client, body, api_version, options) { + var _a, _b, _c; + const input = { + body: body, + api_version: api_version, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/webhooks")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "CreateWebhook", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Deletes a Webhook. + */ +function webhooksDelete(client, id, api_version, options) { + return new APIPromise($do$5(client, id, api_version, options)); +} +async function $do$5(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/webhooks/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "DeleteWebhook", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Gets a specific Webhook. + */ +function webhooksGet(client, id, api_version, options) { + return new APIPromise($do$4(client, id, api_version, options)); +} +async function $do$4(client, id, api_version, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/webhooks/{id}")(pathParams); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "GetWebhook", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Lists all Webhooks. + */ +function webhooksList(client, api_version, page_size, page_token, options) { + return new APIPromise($do$3(client, api_version, page_size, page_token, options)); +} +async function $do$3(client, api_version, page_size, page_token, options) { + var _a, _b, _c; + const input = { + api_version: api_version, + page_size: page_size, + page_token: page_token, + }; + const payload = input; + const body = null; + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload === null || payload === void 0 ? void 0 : payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + }; + const path = pathToFunc("/{api_version}/webhooks")(pathParams); + const query = encodeFormQuery({ + "page_size": payload === null || payload === void 0 ? void 0 : payload.page_size, + "page_token": payload === null || payload === void 0 ? void 0 : payload.page_token, + }); + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "ListWebhooks", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Sends a ping event to a Webhook. + */ +function webhooksPing(client, id, api_version, body, options) { + return new APIPromise($do$2(client, id, api_version, body, options)); +} +async function $do$2(client, id, api_version, body, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + body: body, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "PingWebhook", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Generates a new signing secret for a Webhook. + */ +function webhooksRotateSigningSecret(client, id, api_version, body, options) { + return new APIPromise($do$1(client, id, api_version, body, options)); +} +async function $do$1(client, id, api_version, body, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + body: body, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "RotateSigningSecret", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/** + * Updates an existing Webhook. + */ +function webhooksUpdate(client, id, api_version, update_mask, body, options) { + return new APIPromise($do(client, id, api_version, update_mask, body, options)); +} +async function $do(client, id, api_version, update_mask, body, options) { + var _a, _b, _c; + const input = { + id: id, + api_version: api_version, + update_mask: update_mask, + body: body, + }; + const payload = input; + const body$ = encodeJSON("body", payload.body, { explode: true }); + const pathParams = { + api_version: encodeSimple("api_version", (_a = payload.api_version) !== null && _a !== void 0 ? _a : client._options.api_version, { explode: false, charEncoding: "percent" }), + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/{api_version}/webhooks/{id}")(pathParams); + const query = encodeFormQuery({ + "update_mask": payload.update_mask, + }); + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + const context = { + options: client._options, + base_url: (_c = (_b = options === null || options === void 0 ? void 0 : options.server_url) !== null && _b !== void 0 ? _b : client._baseURL) !== null && _c !== void 0 ? _c : "", + operation_id: "UpdateWebhook", + o_auth2_scopes: null, + resolved_security: requestSecurity, + security_source: client._options.security, + retry_config: (options === null || options === void 0 ? void 0 : options.retries) + || client._options.retry_config + || { + strategy: "attempt-count-backoff", + backoff: { + initialInterval: 500, + maxInterval: 8000, + exponent: 2, + maxElapsedTime: 30000, + }, + retryConnectionErrors: true, + maxRetries: 4, + } + || { strategy: "none" }, + retry_codes: (options === null || options === void 0 ? void 0 : options.retry_codes) || ["408", "409", "429", "5XX"], + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options === null || options === void 0 ? void 0 : options.server_url, + path: path, + headers: headers, + query: query, + body: body$, + userAgent: client._options.user_agent, + timeout_ms: (options === null || options === void 0 ? void 0 : options.timeout_ms) || client._options.timeout_ms || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]), + retryConfig: context.retry_config, + retryCodes: context.retry_codes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await match(fail("4XX"), fail("5XX"), json("default"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +class Webhooks extends ClientSDK { + /** + * Lists all Webhooks. + */ + list(params, options) { + return unwrapAsAPIPromise(webhooksList(this, params === null || params === void 0 ? void 0 : params.api_version, params === null || params === void 0 ? void 0 : params.page_size, params === null || params === void 0 ? void 0 : params.page_token, options)); + } + /** + * Creates a new Webhook. + */ + create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapAsAPIPromise(webhooksCreate(this, body, api_version, options)); + } + /** + * Deletes a Webhook. + */ + delete(id, params, options) { + return unwrapAsAPIPromise(webhooksDelete(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Gets a specific Webhook. + */ + get(id, params, options) { + return unwrapAsAPIPromise(webhooksGet(this, id, params === null || params === void 0 ? void 0 : params.api_version, options)); + } + /** + * Updates an existing Webhook. + */ + update(id, params, options) { + const _a = params !== null && params !== void 0 ? params : {}, { api_version, update_mask } = _a, body$body = __rest(_a, ["api_version", "update_mask"]); + const body = params === undefined || Object.keys(body$body).length === 0 + ? undefined + : body$body; + return unwrapAsAPIPromise(webhooksUpdate(this, id, api_version, update_mask, body, options)); + } + /** + * Sends a ping event to a Webhook. + */ + ping(id, api_version, body, options) { + return unwrapAsAPIPromise(webhooksPing(this, id, api_version, body, options)); + } + /** + * Generates a new signing secret for a Webhook. + */ + rotateSigningSecret(id, api_version, body, options) { + return unwrapAsAPIPromise(webhooksRotateSigningSecret(this, id, api_version, body, options)); + } +} + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ +let GoogleGenAI$1 = class GoogleGenAI extends ClientSDK { + get agents() { + var _a; + return ((_a = this._agents) !== null && _a !== void 0 ? _a : (this._agents = new Agents(this._options))); + } + get environments() { + var _a; + return ((_a = this._environments) !== null && _a !== void 0 ? _a : (this._environments = new Environments(this._options))); + } + get interactions() { + var _a; + return ((_a = this._interactions) !== null && _a !== void 0 ? _a : (this._interactions = new Interactions(this._options))); + } + get triggers() { + var _a; + return ((_a = this._triggers) !== null && _a !== void 0 ? _a : (this._triggers = new Triggers(this._options))); + } + get webhooks() { + var _a; + return ((_a = this._webhooks) !== null && _a !== void 0 ? _a : (this._webhooks = new Webhooks(this._options))); + } +}; + +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + * + * g3-prettier-ignore-file + */ +const LEGACY_LYRIA_MODELS = new Set([ + "lyria-3-pro-preview", + "lyria-3-clip-preview", +]); +function getGoogleGenAIServerURL(parentClient) { + const serverURL = parentClient.getBaseUrl(); + if (!serverURL) { + throw new Error("Base URL must be set."); + } + return serverURL.replace(/\/+$/, ""); +} +function getGoogleGenAIAPIVersion(parentClient) { + const apiVersion = trimSlashes(parentClient.getApiVersion()); + const project = parentClient.getProject(); + const location = parentClient.getLocation(); + if (parentClient.isVertexAI() && apiVersion && project && location) { + return (`${apiVersion}/projects/${encodeURIComponent(project)}` + + `/locations/${encodeURIComponent(location)}`); + } + return apiVersion; +} +function buildGoogleGenAIClient(parentClient, options = {}) { + var _a, _b, _c, _d, _e; + const sdk = new GoogleGenAI$1(Object.assign(Object.assign({}, options), { api_version: (_a = options.api_version) !== null && _a !== void 0 ? _a : getGoogleGenAIAPIVersion(parentClient), security: (_b = options.security) !== null && _b !== void 0 ? _b : new GoogleGenAISecurityProvider({ + defaultHeaders: Object.assign(Object.assign({}, (_c = parentClient.getDefaultHeaders) === null || _c === void 0 ? void 0 : _c.call(parentClient)), (_d = parentClient.getHeaders) === null || _d === void 0 ? void 0 : _d.call(parentClient)), + getAuthHeaders: (url) => parentClient.getAuthHeaders(url), + }), server_url: (_e = options.server_url) !== null && _e !== void 0 ? _e : getGoogleGenAIServerURL(parentClient) })); + return sdk; +} +class GeminiNextGenInteractions { + constructor(parentClient) { + this.parentClient = parentClient; + } + async create(params, options) { + const { api_version } = params, request = __rest(params, ["api_version"]); + if (request.stream === true) { + const response = await wrapSDKCall(() => this.getClient(api_version).interactions.create(Object.assign(Object.assign({}, request), { stream: true, api_version }), toGoogleGenAIRequestOptions(options, true))); + return wrapStreamErrors(response); + } + const response = await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version), request, api_version, toGoogleGenAIRequestOptions(options))); + return addOutputPropertiesIfInteraction(response); + } + async get(id, params = {}, options) { + const { api_version, stream = false, last_event_id, include_input, } = params !== null && params !== void 0 ? params : {}; + if (stream === true) { + const response = await wrapSDKCall(() => this.getClient(api_version).interactions.get(id, { stream, last_event_id, include_input, api_version }, toGoogleGenAIRequestOptions(options, true))); + return wrapStreamErrors(response); + } + const response = await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version), id, api_version, include_input, last_event_id, stream, toGoogleGenAIRequestOptions(options))); + return addOutputPropertiesIfInteraction(response); + } + async delete(id, params = {}, options) { + return wrapSDKCall(() => this.getClient(params === null || params === void 0 ? void 0 : params.api_version).interactions.delete(id, { api_version: params === null || params === void 0 ? void 0 : params.api_version }, toGoogleGenAIRequestOptions(options))); + } + async cancel(id, params = {}, options) { + return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options)))); + } + getClient(apiVersion) { + var _a; + if (apiVersion) { + return buildGoogleGenAIClient(this.parentClient, { + api_version: apiVersion, + }); + } + (_a = this.sdk) !== null && _a !== void 0 ? _a : (this.sdk = buildGoogleGenAIClient(this.parentClient)); + return this.sdk; + } +} +class GeminiNextGenAgents { + constructor(parentClient) { + this.parentClient = parentClient; + } + async create(params = {}, options) { + const _a = params !== null && params !== void 0 ? params : {}, { api_version } = _a, body = __rest(_a, ["api_version"]); + return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version), body, api_version, toGoogleGenAIRequestOptions(options))); + } + async list(params = {}, options) { + const { api_version, pageSize, pageToken, parent } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version), api_version, pageSize, pageToken, parent, toGoogleGenAIRequestOptions(options))); + } + async get(id, params = {}, options) { + return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async delete(id, params = {}, options) { + return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + getClient(apiVersion) { + var _a; + if (apiVersion) { + return buildGoogleGenAIClient(this.parentClient, { + api_version: apiVersion, + }); + } + (_a = this.sdk) !== null && _a !== void 0 ? _a : (this.sdk = buildGoogleGenAIClient(this.parentClient)); + return this.sdk; + } +} +class GeminiNextGenWebhooks { + constructor(parentClient) { + this.parentClient = parentClient; + } + async create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(), body, api_version, toGoogleGenAIRequestOptions(options))); + } + async list(params = {}, options) { + const { api_version, page_size, page_token } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(webhooksList(this.getClient(), api_version, page_size, page_token, toGoogleGenAIRequestOptions(options))); + } + async get(id, params = {}, options) { + return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async update(id, params = {}, options) { + const _a = params !== null && params !== void 0 ? params : {}, { api_version, update_mask } = _a, body = __rest(_a, ["api_version", "update_mask"]); + return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(), id, api_version, update_mask, body, toGoogleGenAIRequestOptions(options))); + } + async delete(id, params = {}, options) { + return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async rotateSigningSecret(id, params = {}, options) { + const _a = params !== null && params !== void 0 ? params : {}, { api_version } = _a, body = __rest(_a, ["api_version"]); + return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(), id, api_version, body, toGoogleGenAIRequestOptions(options))); + } + async ping(id, params = undefined, options) { + const { api_version, body } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(), id, api_version, body, toGoogleGenAIRequestOptions(options))); + } + getClient() { + var _a; + (_a = this.sdk) !== null && _a !== void 0 ? _a : (this.sdk = buildGoogleGenAIClient(this.parentClient)); + return this.sdk; + } +} +class GeminiNextGenTriggers { + constructor(parentClient) { + this.parentClient = parentClient; + } + async create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version), body, api_version, toGoogleGenAIRequestOptions(options))); + } + async list(params = {}, options) { + const { api_version, filter, pageSize, pageToken } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version), api_version, filter, pageSize, pageToken, toGoogleGenAIRequestOptions(options))); + } + async get(id, params = {}, options) { + return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async update(id, params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version), id, body, api_version, toGoogleGenAIRequestOptions(options))); + } + async delete(id, params = {}, options) { + return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async run(trigger_id, params = {}, options) { + return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), trigger_id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async listExecutions(trigger_id, params = {}, options) { + const { api_version, pageSize, pageToken } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version), trigger_id, api_version, pageSize, pageToken, toGoogleGenAIRequestOptions(options))); + } + getClient(apiVersion) { + var _a; + if (apiVersion) { + return buildGoogleGenAIClient(this.parentClient, { + api_version: apiVersion, + }); + } + (_a = this.sdk) !== null && _a !== void 0 ? _a : (this.sdk = buildGoogleGenAIClient(this.parentClient)); + return this.sdk; + } +} +function trimSlashes(value) { + return value.replace(/^\/+|\/+$/g, ""); +} +function toGoogleGenAIRequestOptions(options, streaming = false) { + var _a, _b, _c, _d; + if (!options && !streaming) { + return undefined; + } + const _e = options !== null && options !== void 0 ? options : {}, { timeout, maxRetries, defaultBaseURL, query, body, fetchOptions } = _e, rest = __rest(_e, ["timeout", "maxRetries", "defaultBaseURL", "query", "body", "fetchOptions"]); + const nextOptions = Object.assign({}, rest); + if (isPlainObject(query)) { + nextOptions.extra_query = query; + } + else { + warnIgnoredOption("query", query); + } + if (isPlainObject(body)) { + nextOptions.extra_body = body; + } + else { + warnIgnoredOption("body", body); + } + const fetch_options = (_a = rest.fetch_options) !== null && _a !== void 0 ? _a : fetchOptions; + if (fetch_options) { + nextOptions.fetch_options = fetch_options; + } + const server_url = (_b = rest.server_url) !== null && _b !== void 0 ? _b : defaultBaseURL; + if (server_url) { + nextOptions.server_url = server_url; + } + const timeout_ms = (_c = rest.timeout_ms) !== null && _c !== void 0 ? _c : timeout; + if (timeout_ms !== undefined) { + nextOptions.timeout_ms = timeout_ms; + } + if (maxRetries !== undefined) { + nextOptions.retries = { + strategy: "attempt-count-backoff", + retryConnectionErrors: true, + maxRetries, + }; + } + if (streaming) { + const headers = new Headers((_d = nextOptions.headers) !== null && _d !== void 0 ? _d : fetch_options === null || fetch_options === void 0 ? void 0 : fetch_options.headers); + headers.set("Accept", "text/event-stream"); + nextOptions.headers = headers; + } + return nextOptions; +} +function warnIgnoredOption(name, value) { + if (value !== undefined && value !== null) { + console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`); + } +} +async function unwrapWithSdkHttpResponse(promise) { + const [result, call] = await promise.$inspect(); + if (!result.ok) { + throw wrapSDKError(result.error); + } + return attachSdkHttpResponse(result.value, call); +} +async function wrapSDKCall(operation) { + try { + return await operation(); + } + catch (error) { + throw wrapSDKError(error); + } +} +function wrapStreamErrors(stream) { + const asyncIterable = stream; + return new Proxy(stream, { + get(target, property) { + if (property !== Symbol.asyncIterator) { + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + } + return function wrappedAsyncIterator() { + const iterator = asyncIterable[Symbol.asyncIterator](); + return { + async next(...args) { + try { + return await iterator.next(...args); + } + catch (error) { + throw wrapSDKError(error); + } + }, + async return(value) { + if (!iterator.return) { + return { done: true, value }; + } + try { + return await iterator.return(value); + } + catch (error) { + throw wrapSDKError(error); + } + }, + async throw(error) { + if (!iterator.throw) { + throw wrapSDKError(error); + } + try { + return await iterator.throw(error); + } + catch (caught) { + throw wrapSDKError(caught); + } + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + }; + }, + }); +} +function attachSdkHttpResponse(value, call) { + if (!isPlainObject(value) || call.status !== "complete") { + return value; + } + return Object.assign(Object.assign({}, value), { sdkHttpResponse: createSdkHttpResponse(call.response, value) }); +} +function createSdkHttpResponse(response, parsedBody) { + const headers = {}; + for (const [key, value] of response.headers.entries()) { + headers[key] = value; + } + return { + headers, + responseInternal: response, + json: async () => parsedBody, + }; +} +function addOutputPropertiesIfInteraction(value) { + const interaction = normalizeInteractionShape(value); + if (!interaction) { + return value; + } + return addOutputProperties(interaction); +} +function normalizeInteractionShape(value) { + if (!isPlainObject(value)) { + return undefined; + } + if (Array.isArray(value["steps"])) { + return value; + } + if (isLegacyLyriaInteraction(value)) { + const outputs = value["outputs"]; + if (Array.isArray(outputs)) { + const { outputs: _outputs } = value, rest = __rest(value, ["outputs"]); + return Object.assign(Object.assign({}, rest), { steps: [{ type: "model_output", content: outputs }] }); + } + } + // Every interaction response carries a steps array on the public surface + // even when the wire payload omits it (e.g. Lyria envelopes). + return Object.assign(Object.assign({}, value), { steps: [] }); +} +function isLegacyLyriaInteraction(value) { + const model = value["model"]; + return typeof model === "string" && LEGACY_LYRIA_MODELS.has(model); +} +function isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function addOutputProperties(interaction) { + var _a, _b; + const normalized = normalizeInteractionDates(interaction); + const steps = (_a = normalized["steps"]) !== null && _a !== void 0 ? _a : []; + const textParts = []; + let collecting = false; + outer: for (let i = steps.length - 1; i >= 0; i--) { + const step = steps[i]; + if (step.type === "user_input") { + break; + } + if (step.type !== "model_output" || !step.content) { + if (collecting) { + break; + } + continue; + } + const content = step.content; + for (let j = content.length - 1; j >= 0; j--) { + const item = content[j]; + if (item.type === "text") { + collecting = true; + textParts.push((_b = item.text) !== null && _b !== void 0 ? _b : ""); + } + else if (collecting) { + break outer; + } + } + } + let output_image; + let output_audio; + let output_video; + for (let i = steps.length - 1; i >= 0; i--) { + const step = steps[i]; + if (step.type === "user_input") { + break; + } + if (step.type === "model_output" && step.content) { + for (let j = step.content.length - 1; j >= 0; j--) { + const content = step.content[j]; + if (content.type === "image" && !output_image) { + output_image = content; + } + if (content.type === "audio" && !output_audio) { + output_audio = content; + } + if (content.type === "video" && !output_video) { + output_video = content; + } + } + } + } + const output_text = textParts.reverse().join(""); + return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, normalized), (output_text && { output_text })), (output_image ? { output_image } : {})), (output_audio ? { output_audio } : {})), (output_video ? { output_video } : {})); +} +function normalizeInteractionDates(interaction) { + return Object.assign(Object.assign({}, interaction), { created: normalizeDateLike(interaction["created"]), updated: normalizeDateLike(interaction["updated"]) }); +} +function normalizeDateLike(value) { + return value instanceof Date ? value.toISOString() : value; +} +class GeminiNextGenEnvironmentFiles { + constructor(resolveClient) { + this.resolveClient = resolveClient; + } + async list(params, options) { + const { environment, path, page_size, page_token, recursive, api_version } = params; + return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(api_version), environment, path, api_version, page_size, page_token, recursive, toGoogleGenAIRequestOptions(options))); + } +} +class GeminiNextGenEnvironments { + constructor(parentClient) { + this.parentClient = parentClient; + this.files = new GeminiNextGenEnvironmentFiles((apiVersion) => this.getClient(apiVersion)); + } + async create(params, options) { + const { api_version } = params, body = __rest(params, ["api_version"]); + return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version), body, api_version, toGoogleGenAIRequestOptions(options))); + } + async list(params = {}, options) { + const { api_version, page_size, page_token } = params !== null && params !== void 0 ? params : {}; + return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version), api_version, page_size, page_token, toGoogleGenAIRequestOptions(options))); + } + async get(id, params = {}, options) { + return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + async delete(id, params = {}, options) { + return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params === null || params === void 0 ? void 0 : params.api_version), id, params === null || params === void 0 ? void 0 : params.api_version, toGoogleGenAIRequestOptions(options))); + } + getClient(apiVersion) { + var _a; + if (apiVersion) { + return buildGoogleGenAIClient(this.parentClient, { + api_version: apiVersion, + }); + } + (_a = this.sdk) !== null && _a !== void 0 ? _a : (this.sdk = buildGoogleGenAIClient(this.parentClient)); + return this.sdk; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new src.GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers, url) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers, url); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error('Trying to set API key header but apiKey is not set'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers, url) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error('Trying to set google-auth headers but googleAuth is unset'); + } + const authHeaders = await this.googleAuth.getRequestHeaders(url); + for (const [key, value] of authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, value); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } + else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } + else if ((typeof authOptions.scopes === 'string' && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) { + throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = (0,external_fs_.createWriteStream)(params.downloadPath); + const body = external_node_stream_.Readable.fromWeb(response.responseInternal.body); + body.pipe(writer); + await (0,external_node_stream_promises_.finished)(writer); + } + else { + try { + await (0,promises_.writeFile)(params.downloadPath, response, { + encoding: 'base64', + }); + } + catch (error) { + throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`); + } + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: 'GET', + queryParams: { + 'alt': 'media', + }, + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else if (isGeneratedVideo(params.file)) { + const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download generated video, Uri or videoBytes not found.'); + } + } + else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download video, Uri or videoBytes not found.'); + } + } + else { + throw new Error('Unsupported file type'); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new websocket(this.url, { headers: this.headers }); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function cancelTuningJobParametersToMldev(fromObject, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function cancelTuningJobResponseFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function cancelTuningJobResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function contentToVertex(fromObject, rootObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['tuningMode']) !== undefined) { + throw new Error('tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['customBaseModel']) !== undefined) { + throw new Error('customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['beta']) !== undefined) { + throw new Error('beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['baseTeacherModel']) !== undefined) { + throw new Error('baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['tunedTeacherModelSource']) !== undefined) { + throw new Error('tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['sftLossWeightMultiplier']) !== undefined) { + throw new Error('sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['outputUri']) !== undefined) { + throw new Error('outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['rewardConfig']) !== undefined) { + throw new Error('rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['compositeRewardConfig']) !== undefined) { + throw new Error('compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['samplesPerPrompt']) !== undefined) { + throw new Error('samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['evaluateInterval']) !== undefined) { + throw new Error('evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['checkpointInterval']) !== undefined) { + throw new Error('checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['maxOutputTokens']) !== undefined) { + throw new Error('maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['thinkingLevel']) !== undefined) { + throw new Error('thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['validationDatasetUri']) !== undefined) { + throw new Error('validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['encryptionSpec']) !== undefined) { + throw new Error('encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + let discriminatorValidationDataset = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorValidationDataset === undefined) { + discriminatorValidationDataset = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorValidationDataset === 'SUPERVISED_FINE_TUNING') { + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } + else if (discriminatorValidationDataset === 'PREFERENCE_TUNING') { + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec'], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } + else if (discriminatorValidationDataset === 'DISTILLATION') { + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['distillationSpec'], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } + else if (discriminatorValidationDataset === 'REINFORCEMENT_TUNING') { + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + let discriminatorEpochCount = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorEpochCount === undefined) { + discriminatorEpochCount = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorEpochCount === 'SUPERVISED_FINE_TUNING') { + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + } + else if (discriminatorEpochCount === 'PREFERENCE_TUNING') { + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + } + else if (discriminatorEpochCount === 'DISTILLATION') { + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + } + else if (discriminatorEpochCount === 'REINFORCEMENT_TUNING') { + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + } + let discriminatorLearningRateMultiplier = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorLearningRateMultiplier === undefined) { + discriminatorLearningRateMultiplier = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorLearningRateMultiplier === 'SUPERVISED_FINE_TUNING') { + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + } + else if (discriminatorLearningRateMultiplier === 'PREFERENCE_TUNING') { + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, [ + 'preferenceOptimizationSpec', + 'hyperParameters', + 'learningRateMultiplier', + ], fromLearningRateMultiplier); + } + } + else if (discriminatorLearningRateMultiplier === 'DISTILLATION') { + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + } + else if (discriminatorLearningRateMultiplier === 'REINFORCEMENT_TUNING') { + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, [ + 'reinforcementTuningSpec', + 'hyperParameters', + 'learningRateMultiplier', + ], fromLearningRateMultiplier); + } + } + let discriminatorExportLastCheckpointOnly = getValueByPath(rootObject, ['config', 'method']); + if (discriminatorExportLastCheckpointOnly === undefined) { + discriminatorExportLastCheckpointOnly = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorExportLastCheckpointOnly === 'SUPERVISED_FINE_TUNING') { + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + } + else if (discriminatorExportLastCheckpointOnly === 'PREFERENCE_TUNING') { + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + } + else if (discriminatorExportLastCheckpointOnly === 'DISTILLATION') { + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['distillationSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + } + let discriminatorAdapterSize = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorAdapterSize === undefined) { + discriminatorAdapterSize = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorAdapterSize === 'SUPERVISED_FINE_TUNING') { + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + } + else if (discriminatorAdapterSize === 'PREFERENCE_TUNING') { + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + } + else if (discriminatorAdapterSize === 'DISTILLATION') { + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + } + else if (discriminatorAdapterSize === 'REINFORCEMENT_TUNING') { + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + } + let discriminatorTuningMode = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorTuningMode === undefined) { + discriminatorTuningMode = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorTuningMode === 'SUPERVISED_FINE_TUNING') { + const fromTuningMode = getValueByPath(fromObject, ['tuningMode']); + if (parentObject !== undefined && fromTuningMode != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'tuningMode'], fromTuningMode); + } + } + else if (discriminatorTuningMode === 'DISTILLATION') { + const fromTuningMode = getValueByPath(fromObject, ['tuningMode']); + if (parentObject !== undefined && fromTuningMode != null) { + setValueByPath(parentObject, ['distillationSpec', 'tuningMode'], fromTuningMode); + } + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (parentObject !== undefined && fromCustomBaseModel != null) { + setValueByPath(parentObject, ['customBaseModel'], fromCustomBaseModel); + } + let discriminatorBatchSize = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorBatchSize === undefined) { + discriminatorBatchSize = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorBatchSize === 'SUPERVISED_FINE_TUNING') { + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'batchSize'], fromBatchSize); + } + } + else if (discriminatorBatchSize === 'DISTILLATION') { + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'batchSize'], fromBatchSize); + } + } + else if (discriminatorBatchSize === 'REINFORCEMENT_TUNING') { + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'batchSize'], fromBatchSize); + } + } + let discriminatorLearningRate = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorLearningRate === undefined) { + discriminatorLearningRate = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorLearningRate === 'SUPERVISED_FINE_TUNING') { + const fromLearningRate = getValueByPath(fromObject, [ + 'learningRate', + ]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRate'], fromLearningRate); + } + } + else if (discriminatorLearningRate === 'DISTILLATION') { + const fromLearningRate = getValueByPath(fromObject, [ + 'learningRate', + ]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'learningRate'], fromLearningRate); + } + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromBeta = getValueByPath(fromObject, ['beta']); + if (parentObject !== undefined && fromBeta != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'hyperParameters', 'beta'], fromBeta); + } + const fromBaseTeacherModel = getValueByPath(fromObject, [ + 'baseTeacherModel', + ]); + if (parentObject !== undefined && fromBaseTeacherModel != null) { + setValueByPath(parentObject, ['distillationSpec', 'baseTeacherModel'], fromBaseTeacherModel); + } + const fromTunedTeacherModelSource = getValueByPath(fromObject, [ + 'tunedTeacherModelSource', + ]); + if (parentObject !== undefined && fromTunedTeacherModelSource != null) { + setValueByPath(parentObject, ['distillationSpec', 'tunedTeacherModelSource'], fromTunedTeacherModelSource); + } + const fromSftLossWeightMultiplier = getValueByPath(fromObject, [ + 'sftLossWeightMultiplier', + ]); + if (parentObject !== undefined && fromSftLossWeightMultiplier != null) { + setValueByPath(parentObject, ['distillationSpec', 'hyperParameters', 'sftLossWeightMultiplier'], fromSftLossWeightMultiplier); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (parentObject !== undefined && fromOutputUri != null) { + setValueByPath(parentObject, ['outputUri'], fromOutputUri); + } + const fromRewardConfig = getValueByPath(fromObject, ['rewardConfig']); + if (parentObject !== undefined && fromRewardConfig != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'singleRewardConfig'], fromRewardConfig); + } + const fromCompositeRewardConfig = getValueByPath(fromObject, [ + 'compositeRewardConfig', + ]); + if (parentObject !== undefined && fromCompositeRewardConfig != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'compositeRewardConfig'], fromCompositeRewardConfig); + } + const fromSamplesPerPrompt = getValueByPath(fromObject, [ + 'samplesPerPrompt', + ]); + if (parentObject !== undefined && fromSamplesPerPrompt != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'samplesPerPrompt'], fromSamplesPerPrompt); + } + const fromEvaluateInterval = getValueByPath(fromObject, [ + 'evaluateInterval', + ]); + if (parentObject !== undefined && fromEvaluateInterval != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'evaluateInterval'], fromEvaluateInterval); + } + const fromCheckpointInterval = getValueByPath(fromObject, [ + 'checkpointInterval', + ]); + if (parentObject !== undefined && fromCheckpointInterval != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'checkpointInterval'], fromCheckpointInterval); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromThinkingLevel = getValueByPath(fromObject, [ + 'thinkingLevel', + ]); + if (parentObject !== undefined && fromThinkingLevel != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'hyperParameters', 'thinkingLevel'], fromThinkingLevel); + } + const fromValidationDatasetUri = getValueByPath(fromObject, [ + 'validationDatasetUri', + ]); + if (parentObject !== undefined && fromValidationDatasetUri != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'validationDatasetUri'], fromValidationDatasetUri); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (parentObject !== undefined && fromEncryptionSpec != null) { + setValueByPath(parentObject, ['encryptionSpec'], fromEncryptionSpec); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject, rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + tuningDatasetToMldev(fromTrainingDataset); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createTuningJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject, rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + createTuningJobConfigToVertex(fromConfig, toObject, rootObject); + } + return toObject; +} +function distillationHyperParametersFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (fromEpochCount != null) { + setValueByPath(toObject, ['epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (fromAdapterSize != null) { + setValueByPath(toObject, ['adapterSize'], fromAdapterSize); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (fromBatchSize != null) { + setValueByPath(toObject, ['batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (fromLearningRate != null) { + setValueByPath(toObject, ['learningRate'], fromLearningRate); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig != null) { + setValueByPath(toObject, ['generationConfig'], generationConfigFromVertex(fromGenerationConfig)); + } + return toObject; +} +function distillationSamplingSpecFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromPromptDatasetUri = getValueByPath(fromObject, [ + 'promptDatasetUri', + ]); + if (fromPromptDatasetUri != null) { + setValueByPath(toObject, ['promptDatasetUri'], fromPromptDatasetUri); + } + const fromValidationDatasetUri = getValueByPath(fromObject, [ + 'validationDatasetUri', + ]); + if (fromValidationDatasetUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromValidationDatasetUri); + } + const fromBaseTeacherModel = getValueByPath(fromObject, [ + 'baseTeacherModel', + ]); + if (fromBaseTeacherModel != null) { + setValueByPath(toObject, ['baseTeacherModel'], fromBaseTeacherModel); + } + const fromTunedTeacherModelSource = getValueByPath(fromObject, [ + 'tunedTeacherModelSource', + ]); + if (fromTunedTeacherModelSource != null) { + setValueByPath(toObject, ['tunedTeacherModelSource'], fromTunedTeacherModelSource); + } + const fromHyperparameters = getValueByPath(fromObject, [ + 'hyperparameters', + ]); + if (fromHyperparameters != null) { + setValueByPath(toObject, ['hyperparameters'], distillationHyperParametersFromVertex(fromHyperparameters)); + } + return toObject; +} +function distillationSpecFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromBaseTeacherModel = getValueByPath(fromObject, [ + 'baseTeacherModel', + ]); + if (fromBaseTeacherModel != null) { + setValueByPath(toObject, ['baseTeacherModel'], fromBaseTeacherModel); + } + const fromHyperParameters = getValueByPath(fromObject, [ + 'hyperParameters', + ]); + if (fromHyperParameters != null) { + setValueByPath(toObject, ['hyperParameters'], distillationHyperParametersFromVertex(fromHyperParameters)); + } + const fromPipelineRootDirectory = getValueByPath(fromObject, [ + 'pipelineRootDirectory', + ]); + if (fromPipelineRootDirectory != null) { + setValueByPath(toObject, ['pipelineRootDirectory'], fromPipelineRootDirectory); + } + const fromPromptDatasetUri = getValueByPath(fromObject, [ + 'promptDatasetUri', + ]); + if (fromPromptDatasetUri != null) { + setValueByPath(toObject, ['promptDatasetUri'], fromPromptDatasetUri); + } + const fromStudentModel = getValueByPath(fromObject, ['studentModel']); + if (fromStudentModel != null) { + setValueByPath(toObject, ['studentModel'], fromStudentModel); + } + const fromTrainingDatasetUri = getValueByPath(fromObject, [ + 'trainingDatasetUri', + ]); + if (fromTrainingDatasetUri != null) { + setValueByPath(toObject, ['trainingDatasetUri'], fromTrainingDatasetUri); + } + const fromTunedTeacherModelSource = getValueByPath(fromObject, [ + 'tunedTeacherModelSource', + ]); + if (fromTunedTeacherModelSource != null) { + setValueByPath(toObject, ['tunedTeacherModelSource'], fromTunedTeacherModelSource); + } + const fromTuningMode = getValueByPath(fromObject, ['tuningMode']); + if (fromTuningMode != null) { + setValueByPath(toObject, ['tuningMode'], fromTuningMode); + } + const fromValidationDatasetUri = getValueByPath(fromObject, [ + 'validationDatasetUri', + ]); + if (fromValidationDatasetUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromValidationDatasetUri); + } + return toObject; +} +function generationConfigFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelSelectionConfig'], fromModelSelectionConfig); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], tJsonSchema(fromResponseJsonSchema)); + } + const fromAudioTranscriptionConfig = getValueByPath(fromObject, [ + 'audioTranscriptionConfig', + ]); + if (fromAudioTranscriptionConfig != null) { + setValueByPath(toObject, ['audioTranscriptionConfig'], fromAudioTranscriptionConfig); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (fromEnableAffectiveDialog != null) { + setValueByPath(toObject, ['enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromResponseFormat = getValueByPath(fromObject, [ + 'responseFormat', + ]); + if (fromResponseFormat != null) { + let transformedList = fromResponseFormat; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['responseFormat'], transformedList); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], fromResponseSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], fromSpeechConfig); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + return toObject; +} +function getTuningJobParametersToMldev(fromObject, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + listTuningJobsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function partToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + if (getValueByPath(fromObject, ['toolCall']) !== undefined) { + throw new Error('toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + if (getValueByPath(fromObject, ['toolResponse']) !== undefined) { + throw new Error('toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromAudioTranscription = getValueByPath(fromObject, [ + 'audioTranscription', + ]); + if (fromAudioTranscription != null) { + setValueByPath(toObject, ['audioTranscription'], fromAudioTranscription); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fromFileData); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], fromInlineData); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + if (getValueByPath(fromObject, ['partMetadata']) !== undefined) { + throw new Error('partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + const fromMediaProcessing = getValueByPath(fromObject, [ + 'mediaProcessing', + ]); + if (fromMediaProcessing != null) { + setValueByPath(toObject, ['mediaProcessing'], fromMediaProcessing); + } + return toObject; +} +function reinforcementTuningExampleToVertex(fromObject, rootObject) { + const toObject = {}; + const fromReferences = getValueByPath(fromObject, ['references']); + if (fromReferences != null) { + setValueByPath(toObject, ['references'], fromReferences); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = fromContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction != null) { + setValueByPath(toObject, ['systemInstruction'], contentToVertex(fromSystemInstruction)); + } + return toObject; +} +function tunedModelFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningDatasetToMldev(fromObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject, rootObject) { + const toObject = {}; + let discriminatorGcsUri = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorGcsUri === undefined) { + discriminatorGcsUri = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorGcsUri === 'SUPERVISED_FINE_TUNING') { + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + } + else if (discriminatorGcsUri === 'PREFERENCE_TUNING') { + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'trainingDatasetUri'], fromGcsUri); + } + } + else if (discriminatorGcsUri === 'DISTILLATION') { + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['distillationSpec', 'promptDatasetUri'], fromGcsUri); + } + } + else if (discriminatorGcsUri === 'REINFORCEMENT_TUNING') { + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + } + let discriminatorVertexDatasetResource = getValueByPath(rootObject, [ + 'config', + 'method', + ]); + if (discriminatorVertexDatasetResource === undefined) { + discriminatorVertexDatasetResource = 'SUPERVISED_FINE_TUNING'; + } + if (discriminatorVertexDatasetResource === 'SUPERVISED_FINE_TUNING') { + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + } + else if (discriminatorVertexDatasetResource === 'PREFERENCE_TUNING') { + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['preferenceOptimizationSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + } + else if (discriminatorVertexDatasetResource === 'DISTILLATION') { + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['distillationSpec', 'promptDatasetUri'], fromVertexDatasetResource); + } + } + else if (discriminatorVertexDatasetResource === 'REINFORCEMENT_TUNING') { + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['reinforcementTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.'); + } + return toObject; +} +function tuningJobFromMldev(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + return toObject; +} +function tuningJobFromVertex(fromObject, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], fromTunedModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromPreferenceOptimizationSpec = getValueByPath(fromObject, [ + 'preferenceOptimizationSpec', + ]); + if (fromPreferenceOptimizationSpec != null) { + setValueByPath(toObject, ['preferenceOptimizationSpec'], fromPreferenceOptimizationSpec); + } + const fromDistillationSamplingSpec = getValueByPath(fromObject, [ + 'distillationSamplingSpec', + ]); + if (fromDistillationSamplingSpec != null) { + setValueByPath(toObject, ['distillationSamplingSpec'], distillationSamplingSpecFromVertex(fromDistillationSamplingSpec)); + } + const fromDistillationSpec = getValueByPath(fromObject, [ + 'distillationSpec', + ]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ['distillationSpec'], distillationSpecFromVertex(fromDistillationSpec)); + } + const fromReinforcementTuningSpec = getValueByPath(fromObject, [ + 'reinforcementTuningSpec', + ]); + if (fromReinforcementTuningSpec != null) { + setValueByPath(toObject, ['reinforcementTuningSpec'], fromReinforcementTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromEvaluateDatasetRuns = getValueByPath(fromObject, [ + 'evaluateDatasetRuns', + ]); + if (fromEvaluateDatasetRuns != null) { + let transformedList = fromEvaluateDatasetRuns; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ['evaluateDatasetRuns'], transformedList); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromFullFineTuningSpec = getValueByPath(fromObject, [ + 'fullFineTuningSpec', + ]); + if (fromFullFineTuningSpec != null) { + setValueByPath(toObject, ['fullFineTuningSpec'], fromFullFineTuningSpec); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromTuningJobMetadata = getValueByPath(fromObject, [ + 'tuningJobMetadata', + ]); + if (fromTuningJobMetadata != null) { + setValueByPath(toObject, ['tuningJobMetadata'], fromTuningJobMetadata); + } + const fromTuningJobState = getValueByPath(fromObject, [ + 'tuningJobState', + ]); + if (fromTuningJobState != null) { + setValueByPath(toObject, ['tuningJobState'], fromTuningJobState); + } + const fromVeoLoraTuningSpec = getValueByPath(fromObject, [ + 'veoLoraTuningSpec', + ]); + if (fromVeoLoraTuningSpec != null) { + setValueByPath(toObject, ['veoLoraTuningSpec'], fromVeoLoraTuningSpec); + } + const fromVeoTuningSpec = getValueByPath(fromObject, [ + 'veoTuningSpec', + ]); + if (fromVeoTuningSpec != null) { + setValueByPath(toObject, ['veoTuningSpec'], fromVeoTuningSpec); + } + return toObject; +} +function tuningOperationFromMldev(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (fromVertexDatasetResource != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function validateRewardParametersToVertex(fromObject, rootObject) { + const toObject = {}; + const fromParent = getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + setValueByPath(toObject, ['_url', 'parent'], fromParent); + } + const fromSampleResponse = getValueByPath(fromObject, [ + 'sampleResponse', + ]); + if (fromSampleResponse != null) { + setValueByPath(toObject, ['sampleResponse'], contentToVertex(fromSampleResponse)); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], reinforcementTuningExampleToVertex(fromExample)); + } + const fromSingleRewardConfig = getValueByPath(fromObject, [ + 'singleRewardConfig', + ]); + if (fromSingleRewardConfig != null) { + setValueByPath(toObject, ['singleRewardConfig'], fromSingleRewardConfig); + } + const fromCompositeRewardConfig = getValueByPath(fromObject, [ + 'compositeRewardConfig', + ]); + if (fromCompositeRewardConfig != null) { + setValueByPath(toObject, ['compositeRewardConfig'], fromCompositeRewardConfig); + } + return toObject; +} +function validateRewardResponseFromVertex(fromObject, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromOverallReward = getValueByPath(fromObject, [ + 'overallReward', + ]); + if (fromOverallReward != null) { + setValueByPath(toObject, ['overallReward'], fromOverallReward); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromRewardInfoDetails = getValueByPath(fromObject, [ + 'rewardInfoDetails', + ]); + if (fromRewardInfoDetails != null) { + setValueByPath(toObject, ['rewardInfoDetails'], fromRewardInfoDetails); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists tuning jobs. + * + * @param params - The parameters for the list request. + * @return - A pager of tuning jobs. + * + * @example + * ```ts + * const tuningJobs = await ai.tunings.list({config: {'pageSize': 2}}); + * for await (const tuningJob of tuningJobs) { + * console.log(tuningJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + var _a; + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + if ((_a = params.config) === null || _a === void 0 ? void 0 : _a.preTunedModelCheckpointId) { + preTunedModel.checkpointId = params.config.preTunedModelCheckpointId; + } + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = cancelTuningJobResponseFromVertex(apiResponse); + const typedResp = new CancelTuningJobResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = cancelTuningJobResponseFromMldev(apiResponse); + const typedResp = new CancelTuningJobResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params, params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } + async validateReward(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = validateRewardParametersToVertex(params); + path = formatMap('{parent}/tuningJobs:validateReinforcementTuningReward', body['_url']); + queryParams = body['_query']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = validateRewardResponseFromVertex(apiResponse); + const typedResp = new ValidateRewardResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).'); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient, httpOptions) { + var _a; + const response = await uploadBlobInternal(file, uploadUrl, apiClient, httpOptions); + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient, httpOptions) { + var _a; + const response = await uploadBlobInternal(file, uploadUrl, apiClient, httpOptions); + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + const resp = uploadToFileSearchStoreOperationFromMldev(responseJson); + const typedResp = new UploadToFileSearchStoreOperation(); + Object.assign(typedResp, resp); + return typedResp; +} +async function uploadBlobInternal(file, uploadUrl, apiClient, httpOptions) { + var _a, _b, _c; + let finalUrl = uploadUrl; + const effectiveBaseUrl = (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl) || ((_a = apiClient.clientOptions.httpOptions) === null || _a === void 0 ? void 0 : _a.baseUrl); + if (effectiveBaseUrl) { + const baseUri = new URL(effectiveBaseUrl); + const uploadUri = new URL(uploadUrl); + uploadUri.protocol = baseUri.protocol; + uploadUri.host = baseUri.host; + uploadUri.port = baseUri.port; + finalUrl = uploadUri.toString(); + } + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + const mergedHeaders = Object.assign(Object.assign({}, ((httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.headers) || {})), { 'X-Goog-Upload-Command': uploadCommand, 'X-Goog-Upload-Offset': String(offset) }); + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: Object.assign(Object.assign({}, httpOptions), { apiVersion: '', baseUrl: finalUrl, headers: mergedHeaders }), + }); + if ((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + return response; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === 'string') { + const originalStat = await promises_.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient, httpOptions) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient, httpOptions); + } + else { + return uploadBlob(file, uploadUrl, apiClient, httpOptions); + } + } + async uploadToFileSearchStore(file, uploadUrl, apiClient, httpOptions) { + if (typeof file === 'string') { + return await this.uploadFileToFileSearchStoreFromPath(file, uploadUrl, apiClient, httpOptions); + } + else { + return uploadBlobToFileSearchStore(file, uploadUrl, apiClient, httpOptions); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 'aac': 'audio/aac', + 'abw': 'application/x-abiword', + 'arc': 'application/x-freearc', + 'avi': 'video/x-msvideo', + 'azw': 'application/vnd.amazon.ebook', + 'bin': 'application/octet-stream', + 'bmp': 'image/bmp', + 'bz': 'application/x-bzip', + 'bz2': 'application/x-bzip2', + 'csh': 'application/x-csh', + 'css': 'text/css', + 'csv': 'text/csv', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eot': 'application/vnd.ms-fontobject', + 'epub': 'application/epub+zip', + 'gz': 'application/gzip', + 'gif': 'image/gif', + 'htm': 'text/html', + 'html': 'text/html', + 'ico': 'image/vnd.microsoft.icon', + 'ics': 'text/calendar', + 'jar': 'application/java-archive', + 'jpeg': 'image/jpeg', + 'jpg': 'image/jpeg', + 'js': 'text/javascript', + 'json': 'application/json', + 'jsonld': 'application/ld+json', + 'kml': 'application/vnd.google-earth.kml+xml', + 'kmz': 'application/vnd.google-earth.kmz+xml', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'mpeg': 'video/mpeg', + 'mpkg': 'application/vnd.apple.installer+xml', + 'odt': 'application/vnd.oasis.opendocument.text', + 'oga': 'audio/ogg', + 'ogv': 'video/ogg', + 'ogx': 'application/ogg', + 'opus': 'audio/opus', + 'otf': 'font/otf', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'php': 'application/x-httpd-php', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'rar': 'application/vnd.rar', + 'rtf': 'application/rtf', + 'sh': 'application/x-sh', + 'svg': 'image/svg+xml', + 'swf': 'application/x-shockwave-flash', + 'tar': 'application/x-tar', + 'tif': 'image/tiff', + 'tiff': 'image/tiff', + 'ts': 'video/mp2t', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'vsd': 'application/vnd.visio', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'webp': 'image/webp', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xhtml': 'application/xhtml+xml', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml': 'application/xml', + 'xul': 'application/vnd.mozilla.xul+xml', + 'zip': 'application/zip', + '3gp': 'video/3gpp', + '3g2': 'video/3gpp2', + '7z': 'application/x-7z-compressed', + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient, httpOptions) { + var _a; + const response = await this.uploadFileFromPathInternal(file, uploadUrl, apiClient, httpOptions); + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + async uploadFileToFileSearchStoreFromPath(file, uploadUrl, apiClient, httpOptions) { + var _a; + const response = await this.uploadFileFromPathInternal(file, uploadUrl, apiClient, httpOptions); + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + const resp = uploadToFileSearchStoreOperationFromMldev(responseJson); + const typedResp = new UploadToFileSearchStoreOperation(); + Object.assign(typedResp, resp); + return typedResp; + } + async uploadFileFromPathInternal(file, uploadUrl, apiClient, httpOptions) { + var _a, _b, _c; + let finalUrl = uploadUrl; + const effectiveBaseUrl = (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl) || ((_a = apiClient.clientOptions.httpOptions) === null || _a === void 0 ? void 0 : _a.baseUrl); + if (effectiveBaseUrl) { + const baseUri = new URL(effectiveBaseUrl); + const uploadUri = new URL(uploadUrl); + uploadUri.protocol = baseUri.protocol; + uploadUri.host = baseUri.host; + uploadUri.port = baseUri.port; + finalUrl = uploadUri.toString(); + } + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + const fileName = external_path_.basename(file); + try { + fileHandle = await promises_.open(file, 'r'); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset); + if (bytesRead !== chunkSize) { + throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + const mergedHeaders = Object.assign(Object.assign({}, ((httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.headers) || {})), { 'X-Goog-Upload-Command': uploadCommand, 'X-Goog-Upload-Offset': String(offset), 'X-Goog-Upload-File-Name': fileName }); + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: Object.assign(Object.assign({}, httpOptions), { apiVersion: '', baseUrl: finalUrl, headers: mergedHeaders }), + }); + if ((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + return response; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeFiles extends Files$1 { + /** + * Registers Google Cloud Storage files for use with the API. + * This method is only available in Node.js environments. + */ + async registerFiles(params) { + if (typeof process === 'undefined' || + !process.versions || + !process.versions.node) { + throw new Error('registerFiles is only supported in Node.js environments.'); + } + const googleAuth = params.auth; + const authHeaders = await googleAuth.getRequestHeaders(); + const config = params.config || {}; + const httpOptions = config.httpOptions || {}; + const headers = Object.assign({}, (httpOptions.headers || {})); + if (authHeaders) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof authHeaders[Symbol.iterator] === 'function') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + for (const [key, value] of authHeaders) { + headers[key] = value; + } + } + else { + for (const [key, value] of Object.entries(authHeaders)) { + headers[key] = value; + } + } + } + return this._registerFiles({ + uris: params.uris, + config: Object.assign(Object.assign({}, config), { httpOptions: Object.assign(Object.assign({}, httpOptions), { headers }) }), + }); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +function resolveCloudFlag(options) { + var _a; + if (options && + (options.enterprise !== undefined || options.vertexai !== undefined)) { + if (options.enterprise !== undefined && + options.vertexai !== undefined && + options.enterprise !== options.vertexai) { + throw new Error('enterprise and vertexAI flags have conflicting values, please set enterprise value only.'); + } + return (_a = options.enterprise) !== null && _a !== void 0 ? _a : options.vertexai; + } + const envEnterpriseStr = getEnv('GOOGLE_GENAI_USE_ENTERPRISE'); + const envVertexaiStr = getEnv('GOOGLE_GENAI_USE_VERTEXAI'); + const useEnterpriseEnv = stringToBoolean(envEnterpriseStr); + const useVertexaiEnv = stringToBoolean(envVertexaiStr); + if (envEnterpriseStr !== undefined && + envVertexaiStr !== undefined && + useEnterpriseEnv !== useVertexaiEnv) { + console.warn('Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used.'); + } + if (envEnterpriseStr !== undefined) { + return useEnterpriseEnv; + } + if (envVertexaiStr !== undefined) { + return useVertexaiEnv; + } + return false; +} +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + getNextGenClient() { + const httpOpts = this.httpOptions; + if (this._nextGenClient === undefined) { + this._nextGenClient = buildGoogleGenAIClient(this.apiClient, { + timeout_ms: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout, + }); + } + if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) { + console.warn('GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored.'); + } + return this._nextGenClient; + } + get interactions() { + if (this._interactions !== undefined) { + return this._interactions; + } + this._interactions = new GeminiNextGenInteractions(this.apiClient); + return this._interactions; + } + get webhooks() { + if (this._webhooks !== undefined) { + return this._webhooks; + } + this._webhooks = new GeminiNextGenWebhooks(this.apiClient); + return this._webhooks; + } + get agents() { + if (this._agents !== undefined) { + return this._agents; + } + console.warn('GoogleGenAI.agents: Agents usage is experimental and may change in future versions.'); + this._agents = new GeminiNextGenAgents(this.apiClient); + return this._agents; + } + get triggers() { + if (this._triggers !== undefined) { + return this._triggers; + } + console.warn('GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions.'); + this._triggers = new GeminiNextGenTriggers(this.apiClient); + return this._triggers; + } + get environments() { + if (this._environments !== undefined) { + return this._environments; + } + console.warn('GoogleGenAI.environments: Environments usage is experimental and may change in future versions.'); + this._environments = new GeminiNextGenEnvironments(this.apiClient); + return this._environments; + } + constructor(options = {}) { + var _a, _b, _c, _d; + this.vertexai = resolveCloudFlag(options); + // Validate explicitly set initializer values. + if ((options.project || options.location) && !this.vertexai) { + throw new Error('Project and location are not supported for Gemini API backend.'); + } + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_a = options.apiKey) !== null && _a !== void 0 ? _a : envApiKey; + this.project = (_b = options.project) !== null && _b !== void 0 ? _b : envProject; + this.location = (_c = options.location) !== null && _c !== void 0 ? _c : envLocation; + if (!this.vertexai && !this.apiKey) { + console.warn('API key should be set when using the Gemini API.'); + } + // Handle when to use Vertex AI in express mode (api key) + if (this.vertexai) { + if ((_d = options.googleAuthOptions) === null || _d === void 0 ? void 0 : _d.credentials) { + // Explicit credentials take precedence over implicit api_key. + console.debug('The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.'); + this.apiKey = undefined; + } + if (!options.project && + !options.location && + (envProject || envLocation) && + options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug('The user provided Vertex AI API key will take precedence over' + + ' the project/location from the environment variables.'); + this.project = undefined; + this.location = undefined; + } + else if ((options.project || options.location) && + !options.apiKey && + envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug('The user provided project/location will take precedence over' + + ' the API key from the environment variables.'); + this.apiKey = undefined; + } + else if (!options.project && + !options.location && + !options.apiKey && + (envProject || envLocation) && + envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug('The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.'); + this.apiKey = undefined; + } + if (!this.location && !this.apiKey) { + this.location = 'global'; + } + } + const baseUrl = getBaseUrl(options.httpOptions, this.vertexai, getEnv('GOOGLE_VERTEX_BASE_URL'), getEnv('GOOGLE_GEMINI_BASE_URL')); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + this.httpOptions = options.httpOptions; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: this.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new NodeFiles(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + this.fileSearchStores = new FileSearchStores(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = (_b = (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined; +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv('GOOGLE_API_KEY'); + const envGeminiApiKey = getEnv('GEMINI_API_KEY'); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn('Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'); + } + return envGoogleApiKey || envGeminiApiKey || undefined; +} + + +//# sourceMappingURL=index.mjs.map + + +/***/ }), + +/***/ 62598: +/***/ ((module) => { + +module.exports = /*#__PURE__*/JSON.parse('{"name":"gaxios","version":"7.3.1","description":"A simple common HTTP client specifically for Google APIs and services.","main":"build/cjs/src/index.js","types":"build/cjs/src/index.d.ts","files":["build/"],"exports":{".":{"import":{"types":"./build/esm/src/index.d.ts","default":"./build/esm/src/index.js"},"require":{"types":"./build/cjs/src/index.d.ts","default":"./build/cjs/src/index.js"}}},"scripts":{"lint":"gts check --no-inline-config","test":"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000","compile":"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs","fix":"gts fix","prepare":"npm run compile","pretest":"npm run compile","webpack":"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js","docs":"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","prelint":"cd samples; npm link ../; npm install","clean":"gts clean"},"repository":{"type":"git","directory":"core/packages/gaxios","url":"https://github.com/googleapis/google-cloud-node.git"},"keywords":["google"],"engines":{"node":">=18"},"author":"Google, LLC","license":"Apache-2.0","devDependencies":{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6","assert":"^2.0.0","browserify":"^17.0.0","c8":"^10.1.3","cors":"^2.8.5","express":"^5.0.0","gts":"^6.0.2","is-docker":"^3.0.0","jsdoc":"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0","karma":"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0","mocha":"^11.1.0","multiparty":"^4.2.1","mv":"^2.1.1","ncp":"^2.0.0","nock":"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0","puppeteer":"^24.0.0","sinon":"21.0.3","stream-browserify":"^3.0.0","tmp":"0.2.7","ts-loader":"^9.5.2","typescript":"5.8.3","undici-types":"^7.24.1","webpack":"^5.97.1","webpack-cli":"^6.0.1"},"dependencies":{"extend":"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},"homepage":"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}'); + +/***/ }), + +/***/ 21930: +/***/ ((module) => { + +module.exports = /*#__PURE__*/JSON.parse('{"name":"google-auth-library","version":"10.9.1","author":"Google Inc.","description":"Google APIs Authentication Client Library for Node.js","engines":{"node":">=18"},"main":"./build/src/index.js","types":"./build/src/index.d.ts","repository":{"type":"git","directory":"core/packages/google-auth-library-nodejs","url":"https://github.com/googleapis/google-cloud-node.git"},"keywords":["google","api","google apis","client","client library"],"dependencies":{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11","gaxios":"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3","jws":"^4.0.0"},"devDependencies":{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0","c8":"^10.1.3","codecov":"^3.8.3","gts":"^6.0.2","is-docker":"^3.0.0","jsdoc":"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0","karma":"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1","keypair":"^1.0.4","mocha":"^11.1.0","mv":"^2.1.1","ncp":"^2.0.0","nock":"^14.0.5","null-loader":"^4.0.1","puppeteer":"^24.0.0","sinon":"21.0.3","ts-loader":"^9.5.2","typescript":"5.8.3","webpack":"^5.97.1","webpack-cli":"^6.0.1"},"files":["build/src","!build/src/**/*.map"],"scripts":{"test":"c8 mocha build/test","clean":"gts clean","prepare":"npm run compile","lint":"gts check --no-inline-config","compile":"tsc -p .","fix":"gts fix","pretest":"npm run compile -- --sourceMap","docs":"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap","webpack":"webpack","browser-test":"karma start","prelint":"cd samples; npm link ../; npm install"},"license":"Apache-2.0","homepage":"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}'); + +/***/ }) + +}; diff --git a/dist/action/833.index.js b/dist/action/833.index.js new file mode 100644 index 000000000..f6fae28fe --- /dev/null +++ b/dist/action/833.index.js @@ -0,0 +1,37808 @@ +export const id = 833; +export const ids = [833]; +export const modules = { + +/***/ 36214: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var hljs = __webpack_require__(50795); + +hljs.registerLanguage('1c', __webpack_require__(76860)); +hljs.registerLanguage('abnf', __webpack_require__(53887)); +hljs.registerLanguage('accesslog', __webpack_require__(10846)); +hljs.registerLanguage('actionscript', __webpack_require__(97001)); +hljs.registerLanguage('ada', __webpack_require__(98614)); +hljs.registerLanguage('angelscript', __webpack_require__(11156)); +hljs.registerLanguage('apache', __webpack_require__(93934)); +hljs.registerLanguage('applescript', __webpack_require__(43673)); +hljs.registerLanguage('arcade', __webpack_require__(59452)); +hljs.registerLanguage('arduino', __webpack_require__(22202)); +hljs.registerLanguage('armasm', __webpack_require__(6337)); +hljs.registerLanguage('xml', __webpack_require__(95327)); +hljs.registerLanguage('asciidoc', __webpack_require__(3515)); +hljs.registerLanguage('aspectj', __webpack_require__(50436)); +hljs.registerLanguage('autohotkey', __webpack_require__(39381)); +hljs.registerLanguage('autoit', __webpack_require__(62694)); +hljs.registerLanguage('avrasm', __webpack_require__(74206)); +hljs.registerLanguage('awk', __webpack_require__(10327)); +hljs.registerLanguage('axapta', __webpack_require__(72171)); +hljs.registerLanguage('bash', __webpack_require__(23670)); +hljs.registerLanguage('basic', __webpack_require__(4720)); +hljs.registerLanguage('bnf', __webpack_require__(43120)); +hljs.registerLanguage('brainfuck', __webpack_require__(80249)); +hljs.registerLanguage('c-like', __webpack_require__(29315)); +hljs.registerLanguage('c', __webpack_require__(76663)); +hljs.registerLanguage('cal', __webpack_require__(12142)); +hljs.registerLanguage('capnproto', __webpack_require__(63346)); +hljs.registerLanguage('ceylon', __webpack_require__(72312)); +hljs.registerLanguage('clean', __webpack_require__(40583)); +hljs.registerLanguage('clojure', __webpack_require__(83926)); +hljs.registerLanguage('clojure-repl', __webpack_require__(8430)); +hljs.registerLanguage('cmake', __webpack_require__(95765)); +hljs.registerLanguage('coffeescript', __webpack_require__(12007)); +hljs.registerLanguage('coq', __webpack_require__(61083)); +hljs.registerLanguage('cos', __webpack_require__(25501)); +hljs.registerLanguage('cpp', __webpack_require__(39767)); +hljs.registerLanguage('crmsh', __webpack_require__(61309)); +hljs.registerLanguage('crystal', __webpack_require__(5356)); +hljs.registerLanguage('csharp', __webpack_require__(39403)); +hljs.registerLanguage('csp', __webpack_require__(22216)); +hljs.registerLanguage('css', __webpack_require__(40961)); +hljs.registerLanguage('d', __webpack_require__(1782)); +hljs.registerLanguage('markdown', __webpack_require__(83745)); +hljs.registerLanguage('dart', __webpack_require__(27341)); +hljs.registerLanguage('delphi', __webpack_require__(5732)); +hljs.registerLanguage('diff', __webpack_require__(90775)); +hljs.registerLanguage('django', __webpack_require__(46019)); +hljs.registerLanguage('dns', __webpack_require__(86057)); +hljs.registerLanguage('dockerfile', __webpack_require__(1534)); +hljs.registerLanguage('dos', __webpack_require__(88620)); +hljs.registerLanguage('dsconfig', __webpack_require__(15259)); +hljs.registerLanguage('dts', __webpack_require__(43991)); +hljs.registerLanguage('dust', __webpack_require__(32188)); +hljs.registerLanguage('ebnf', __webpack_require__(35603)); +hljs.registerLanguage('elixir', __webpack_require__(61755)); +hljs.registerLanguage('elm', __webpack_require__(79046)); +hljs.registerLanguage('ruby', __webpack_require__(31176)); +hljs.registerLanguage('erb', __webpack_require__(36193)); +hljs.registerLanguage('erlang-repl', __webpack_require__(37497)); +hljs.registerLanguage('erlang', __webpack_require__(89843)); +hljs.registerLanguage('excel', __webpack_require__(8553)); +hljs.registerLanguage('fix', __webpack_require__(56137)); +hljs.registerLanguage('flix', __webpack_require__(94215)); +hljs.registerLanguage('fortran', __webpack_require__(79368)); +hljs.registerLanguage('fsharp', __webpack_require__(990)); +hljs.registerLanguage('gams', __webpack_require__(18916)); +hljs.registerLanguage('gauss', __webpack_require__(25875)); +hljs.registerLanguage('gcode', __webpack_require__(83306)); +hljs.registerLanguage('gherkin', __webpack_require__(20412)); +hljs.registerLanguage('glsl', __webpack_require__(76836)); +hljs.registerLanguage('gml', __webpack_require__(27646)); +hljs.registerLanguage('go', __webpack_require__(29762)); +hljs.registerLanguage('golo', __webpack_require__(46831)); +hljs.registerLanguage('gradle', __webpack_require__(41787)); +hljs.registerLanguage('groovy', __webpack_require__(98570)); +hljs.registerLanguage('haml', __webpack_require__(90458)); +hljs.registerLanguage('handlebars', __webpack_require__(77168)); +hljs.registerLanguage('haskell', __webpack_require__(84994)); +hljs.registerLanguage('haxe', __webpack_require__(50428)); +hljs.registerLanguage('hsp', __webpack_require__(99053)); +hljs.registerLanguage('htmlbars', __webpack_require__(44683)); +hljs.registerLanguage('http', __webpack_require__(66376)); +hljs.registerLanguage('hy', __webpack_require__(52327)); +hljs.registerLanguage('inform7', __webpack_require__(89928)); +hljs.registerLanguage('ini', __webpack_require__(35856)); +hljs.registerLanguage('irpf90', __webpack_require__(42084)); +hljs.registerLanguage('isbl', __webpack_require__(73162)); +hljs.registerLanguage('java', __webpack_require__(61192)); +hljs.registerLanguage('javascript', __webpack_require__(92963)); +hljs.registerLanguage('jboss-cli', __webpack_require__(30482)); +hljs.registerLanguage('json', __webpack_require__(7802)); +hljs.registerLanguage('julia', __webpack_require__(89879)); +hljs.registerLanguage('julia-repl', __webpack_require__(64109)); +hljs.registerLanguage('kotlin', __webpack_require__(56254)); +hljs.registerLanguage('lasso', __webpack_require__(17084)); +hljs.registerLanguage('latex', __webpack_require__(71302)); +hljs.registerLanguage('ldif', __webpack_require__(94711)); +hljs.registerLanguage('leaf', __webpack_require__(22796)); +hljs.registerLanguage('less', __webpack_require__(35665)); +hljs.registerLanguage('lisp', __webpack_require__(81388)); +hljs.registerLanguage('livecodeserver', __webpack_require__(57232)); +hljs.registerLanguage('livescript', __webpack_require__(79369)); +hljs.registerLanguage('llvm', __webpack_require__(64881)); +hljs.registerLanguage('lsl', __webpack_require__(38477)); +hljs.registerLanguage('lua', __webpack_require__(27112)); +hljs.registerLanguage('makefile', __webpack_require__(11388)); +hljs.registerLanguage('mathematica', __webpack_require__(92982)); +hljs.registerLanguage('matlab', __webpack_require__(91313)); +hljs.registerLanguage('maxima', __webpack_require__(89887)); +hljs.registerLanguage('mel', __webpack_require__(62872)); +hljs.registerLanguage('mercury', __webpack_require__(19763)); +hljs.registerLanguage('mipsasm', __webpack_require__(52340)); +hljs.registerLanguage('mizar', __webpack_require__(14825)); +hljs.registerLanguage('perl', __webpack_require__(80045)); +hljs.registerLanguage('mojolicious', __webpack_require__(29027)); +hljs.registerLanguage('monkey', __webpack_require__(9853)); +hljs.registerLanguage('moonscript', __webpack_require__(15250)); +hljs.registerLanguage('n1ql', __webpack_require__(74620)); +hljs.registerLanguage('nginx', __webpack_require__(27158)); +hljs.registerLanguage('nim', __webpack_require__(52478)); +hljs.registerLanguage('nix', __webpack_require__(57041)); +hljs.registerLanguage('node-repl', __webpack_require__(14608)); +hljs.registerLanguage('nsis', __webpack_require__(76035)); +hljs.registerLanguage('objectivec', __webpack_require__(92748)); +hljs.registerLanguage('ocaml', __webpack_require__(8590)); +hljs.registerLanguage('openscad', __webpack_require__(76055)); +hljs.registerLanguage('oxygene', __webpack_require__(51333)); +hljs.registerLanguage('parser3', __webpack_require__(70990)); +hljs.registerLanguage('pf', __webpack_require__(93238)); +hljs.registerLanguage('pgsql', __webpack_require__(21257)); +hljs.registerLanguage('php', __webpack_require__(8490)); +hljs.registerLanguage('php-template', __webpack_require__(16425)); +hljs.registerLanguage('plaintext', __webpack_require__(87241)); +hljs.registerLanguage('pony', __webpack_require__(35412)); +hljs.registerLanguage('powershell', __webpack_require__(47521)); +hljs.registerLanguage('processing', __webpack_require__(74063)); +hljs.registerLanguage('profile', __webpack_require__(47643)); +hljs.registerLanguage('prolog', __webpack_require__(80127)); +hljs.registerLanguage('properties', __webpack_require__(9309)); +hljs.registerLanguage('protobuf', __webpack_require__(61719)); +hljs.registerLanguage('puppet', __webpack_require__(29854)); +hljs.registerLanguage('purebasic', __webpack_require__(30006)); +hljs.registerLanguage('python', __webpack_require__(52606)); +hljs.registerLanguage('python-repl', __webpack_require__(7078)); +hljs.registerLanguage('q', __webpack_require__(16201)); +hljs.registerLanguage('qml', __webpack_require__(32348)); +hljs.registerLanguage('r', __webpack_require__(40720)); +hljs.registerLanguage('reasonml', __webpack_require__(36889)); +hljs.registerLanguage('rib', __webpack_require__(38035)); +hljs.registerLanguage('roboconf', __webpack_require__(16826)); +hljs.registerLanguage('routeros', __webpack_require__(13071)); +hljs.registerLanguage('rsl', __webpack_require__(17355)); +hljs.registerLanguage('ruleslanguage', __webpack_require__(52663)); +hljs.registerLanguage('rust', __webpack_require__(56726)); +hljs.registerLanguage('sas', __webpack_require__(48775)); +hljs.registerLanguage('scala', __webpack_require__(37700)); +hljs.registerLanguage('scheme', __webpack_require__(77359)); +hljs.registerLanguage('scilab', __webpack_require__(10348)); +hljs.registerLanguage('scss', __webpack_require__(69908)); +hljs.registerLanguage('shell', __webpack_require__(52836)); +hljs.registerLanguage('smali', __webpack_require__(62602)); +hljs.registerLanguage('smalltalk', __webpack_require__(70787)); +hljs.registerLanguage('sml', __webpack_require__(92002)); +hljs.registerLanguage('sqf', __webpack_require__(11516)); +hljs.registerLanguage('sql_more', __webpack_require__(21420)); +hljs.registerLanguage('sql', __webpack_require__(42318)); +hljs.registerLanguage('stan', __webpack_require__(16272)); +hljs.registerLanguage('stata', __webpack_require__(53727)); +hljs.registerLanguage('step21', __webpack_require__(99191)); +hljs.registerLanguage('stylus', __webpack_require__(49614)); +hljs.registerLanguage('subunit', __webpack_require__(32798)); +hljs.registerLanguage('swift', __webpack_require__(93073)); +hljs.registerLanguage('taggerscript', __webpack_require__(73269)); +hljs.registerLanguage('yaml', __webpack_require__(51467)); +hljs.registerLanguage('tap', __webpack_require__(73675)); +hljs.registerLanguage('tcl', __webpack_require__(49717)); +hljs.registerLanguage('thrift', __webpack_require__(12287)); +hljs.registerLanguage('tp', __webpack_require__(6180)); +hljs.registerLanguage('twig', __webpack_require__(53201)); +hljs.registerLanguage('typescript', __webpack_require__(36043)); +hljs.registerLanguage('vala', __webpack_require__(89938)); +hljs.registerLanguage('vbnet', __webpack_require__(76053)); +hljs.registerLanguage('vbscript', __webpack_require__(38111)); +hljs.registerLanguage('vbscript-html', __webpack_require__(97589)); +hljs.registerLanguage('verilog', __webpack_require__(53508)); +hljs.registerLanguage('vhdl', __webpack_require__(60326)); +hljs.registerLanguage('vim', __webpack_require__(33510)); +hljs.registerLanguage('x86asm', __webpack_require__(19085)); +hljs.registerLanguage('xl', __webpack_require__(85852)); +hljs.registerLanguage('xquery', __webpack_require__(47412)); +hljs.registerLanguage('zephir', __webpack_require__(89994)); + +module.exports = hljs; + +/***/ }), + +/***/ 76860: +/***/ ((module) => { + +/* +Language: 1C:Enterprise +Author: Stanislav Belov +Description: built-in language 1C:Enterprise (v7, v8) +Category: enterprise +*/ + +function _1c(hljs) { + + // общий паттерн для определения идентификаторов + var UNDERSCORE_IDENT_RE = '[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+'; + + // v7 уникальные ключевые слова, отсутствующие в v8 ==> keyword + var v7_keywords = + 'далее '; + + // v8 ключевые слова ==> keyword + var v8_keywords = + 'возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли ' + + 'конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт '; + + // keyword : ключевые слова + var KEYWORD = v7_keywords + v8_keywords; + + // v7 уникальные директивы, отсутствующие в v8 ==> meta-keyword + var v7_meta_keywords = + 'загрузитьизфайла '; + + // v8 ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях ==> meta-keyword + var v8_meta_keywords = + 'вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер ' + + 'наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед ' + + 'после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент '; + + // meta-keyword : ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях + var METAKEYWORD = v7_meta_keywords + v8_meta_keywords; + + // v7 системные константы ==> built_in + var v7_system_constants = + 'разделительстраниц разделительстрок символтабуляции '; + + // v7 уникальные методы глобального контекста, отсутствующие в v8 ==> built_in + var v7_global_context_methods = + 'ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов ' + + 'датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя ' + + 'кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца ' + + 'коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид ' + + 'назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца ' + + 'начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов ' + + 'основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута ' + + 'получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта ' + + 'префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына ' + + 'рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента ' + + 'счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон '; + + // v8 методы глобального контекста ==> built_in + var v8_global_context_methods = + 'acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока ' + + 'xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ' + + 'ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации ' + + 'выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода ' + + 'деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы ' + + 'загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации ' + + 'заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию ' + + 'значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла ' + + 'изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке ' + + 'каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку ' + + 'кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты ' + + 'конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы ' + + 'копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти ' + + 'найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы ' + + 'началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя ' + + 'начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты ' + + 'начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов ' + + 'начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя ' + + 'начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога ' + + 'начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией ' + + 'начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы ' + + 'номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения ' + + 'обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении ' + + 'отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения ' + + 'открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально ' + + 'отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа ' + + 'перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту ' + + 'подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения ' + + 'подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки ' + + 'показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение ' + + 'показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя ' + + 'получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса ' + + 'получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора ' + + 'получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса ' + + 'получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации ' + + 'получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла ' + + 'получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурналарегистрации ' + + 'получитьиспользованиесобытияжурналарегистрации получитькраткийзаголовокприложения получитьмакетоформления ' + + 'получитьмаскувсефайлы получитьмаскувсефайлыклиента получитьмаскувсефайлысервера получитьместоположениепоадресу ' + + 'получитьминимальнуюдлинупаролейпользователей получитьнавигационнуюссылку получитьнавигационнуюссылкуинформационнойбазы ' + + 'получитьобновлениеконфигурациибазыданных получитьобновлениепредопределенныхданныхинформационнойбазы получитьобщиймакет ' + + 'получитьобщуюформу получитьокна получитьоперативнуюотметкувремени получитьотключениебезопасногорежима ' + + 'получитьпараметрыфункциональныхопцийинтерфейса получитьполноеимяпредопределенногозначения ' + + 'получитьпредставлениянавигационныхссылок получитьпроверкусложностипаролейпользователей получитьразделительпути ' + + 'получитьразделительпутиклиента получитьразделительпутисервера получитьсеансыинформационнойбазы ' + + 'получитьскоростьклиентскогосоединения получитьсоединенияинформационнойбазы получитьсообщенияпользователю ' + + 'получитьсоответствиеобъектаиформы получитьсоставстандартногоинтерфейсаodata получитьструктурухранениябазыданных ' + + 'получитьтекущийсеансинформационнойбазы получитьфайл получитьфайлы получитьформу получитьфункциональнуюопцию ' + + 'получитьфункциональнуюопциюинтерфейса получитьчасовойпоясинформационнойбазы пользователиос поместитьвовременноехранилище ' + + 'поместитьфайл поместитьфайлы прав праводоступа предопределенноезначение представлениекодалокализации представлениепериода ' + + 'представлениеправа представлениеприложения представлениесобытияжурналарегистрации представлениечасовогопояса предупреждение ' + + 'прекратитьработусистемы привилегированныйрежим продолжитьвызов прочитатьjson прочитатьxml прочитатьдатуjson пустаястрока ' + + 'рабочийкаталогданныхпользователя разблокироватьданныедляредактирования разделитьфайл разорватьсоединениесвнешнимисточникомданных ' + + 'раскодироватьстроку рольдоступна секунда сигнал символ скопироватьжурналрегистрации смещениелетнеговремени ' + + 'смещениестандартноговремени соединитьбуферыдвоичныхданных создатькаталог создатьфабрикуxdto сокрл сокрлп сокрп сообщить ' + + 'состояние сохранитьзначение сохранитьнастройкипользователя сред стрдлина стрзаканчиваетсяна стрзаменить стрнайти стрначинаетсяс ' + + 'строка строкасоединенияинформационнойбазы стрполучитьстроку стрразделить стрсоединить стрсравнить стрчисловхождений '+ + 'стрчислострок стршаблон текущаядата текущаядатасеанса текущаяуниверсальнаядата текущаяуниверсальнаядатавмиллисекундах ' + + 'текущийвариантинтерфейсаклиентскогоприложения текущийвариантосновногошрифтаклиентскогоприложения текущийкодлокализации ' + + 'текущийрежимзапуска текущийязык текущийязыксистемы тип типзнч транзакцияактивна трег удалитьданныеинформационнойбазы ' + + 'удалитьизвременногохранилища удалитьобъекты удалитьфайлы универсальноевремя установитьбезопасныйрежим ' + + 'установитьбезопасныйрежимразделенияданных установитьблокировкусеансов установитьвнешнююкомпоненту ' + + 'установитьвремязавершенияспящегосеанса установитьвремязасыпанияпассивногосеанса установитьвремяожиданияблокировкиданных ' + + 'установитьзаголовокклиентскогоприложения установитьзаголовоксистемы установитьиспользованиежурналарегистрации ' + + 'установитьиспользованиесобытияжурналарегистрации установитькраткийзаголовокприложения ' + + 'установитьминимальнуюдлинупаролейпользователей установитьмонопольныйрежим установитьнастройкиклиенталицензирования ' + + 'установитьобновлениепредопределенныхданныхинформационнойбазы установитьотключениебезопасногорежима ' + + 'установитьпараметрыфункциональныхопцийинтерфейса установитьпривилегированныйрежим ' + + 'установитьпроверкусложностипаролейпользователей установитьрасширениеработыскриптографией ' + + 'установитьрасширениеработысфайлами установитьсоединениесвнешнимисточникомданных установитьсоответствиеобъектаиформы ' + + 'установитьсоставстандартногоинтерфейсаodata установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса ' + + 'формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища '; + + // v8 свойства глобального контекста ==> built_in + var v8_global_context_property = + 'wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы ' + + 'внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль ' + + 'документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты ' + + 'историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений ' + + 'отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик ' + + 'планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок ' + + 'рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений ' + + 'регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа ' + + 'средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек ' + + 'хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков ' + + 'хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек '; + + // built_in : встроенные или библиотечные объекты (константы, классы, функции) + var BUILTIN = + v7_system_constants + + v7_global_context_methods + v8_global_context_methods + + v8_global_context_property; + + // v8 системные наборы значений ==> class + var v8_system_sets_of_values = + 'webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля '; + + // v8 системные перечисления - интерфейсные ==> class + var v8_system_enums_interface = + 'автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий ' + + 'анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы ' + + 'вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы ' + + 'виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя ' + + 'видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение ' + + 'горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы ' + + 'группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания ' + + 'интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки ' + + 'используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы ' + + 'источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева ' + + 'начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы ' + + 'ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме ' + + 'отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы ' + + 'отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы ' + + 'отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы ' + + 'отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска ' + + 'отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования ' + + 'отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта ' + + 'отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы ' + + 'поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы ' + + 'поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы ' + + 'положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы ' + + 'положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы ' + + 'положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском ' + + 'положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы ' + + 'размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта ' + + 'режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты ' + + 'режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения ' + + 'режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра ' + + 'режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения ' + + 'режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы ' + + 'режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки ' + + 'режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание ' + + 'сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы ' + + 'способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление ' + + 'статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы ' + + 'типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы ' + + 'типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления ' + + 'типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы ' + + 'типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы ' + + 'типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений ' + + 'типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы ' + + 'типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы ' + + 'типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы ' + + 'факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени ' + + 'форматкартинки ширинаподчиненныхэлементовформы '; + + // v8 системные перечисления - свойства прикладных объектов ==> class + var v8_system_enums_objects_properties = + 'виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса ' + + 'использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения ' + + 'использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента '; + + // v8 системные перечисления - планы обмена ==> class + var v8_system_enums_exchange_plans = + 'авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных '; + + // v8 системные перечисления - табличный документ ==> class + var v8_system_enums_tabular_document = + 'использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы ' + + 'положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента ' + + 'способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента ' + + 'типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента ' + + 'типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы ' + + 'типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента ' + + 'типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц '; + + // v8 системные перечисления - планировщик ==> class + var v8_system_enums_sheduler = + 'отображениевремениэлементовпланировщика '; + + // v8 системные перечисления - форматированный документ ==> class + var v8_system_enums_formatted_document = + 'типфайлаформатированногодокумента '; + + // v8 системные перечисления - запрос ==> class + var v8_system_enums_query = + 'обходрезультатазапроса типзаписизапроса '; + + // v8 системные перечисления - построитель отчета ==> class + var v8_system_enums_report_builder = + 'видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов '; + + // v8 системные перечисления - работа с файлами ==> class + var v8_system_enums_files = + 'доступкфайлу режимдиалогавыборафайла режимоткрытияфайла '; + + // v8 системные перечисления - построитель запроса ==> class + var v8_system_enums_query_builder = + 'типизмеренияпостроителязапроса '; + + // v8 системные перечисления - анализ данных ==> class + var v8_system_enums_data_analysis = + 'видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных ' + + 'типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений ' + + 'типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций ' + + 'типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных ' + + 'типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных ' + + 'типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений '; + + // v8 системные перечисления - xml, json, xs, dom, xdto, web-сервисы ==> class + var v8_system_enums_xml_json_xs_dom_xdto_ws = + 'wsнаправлениепараметра вариантxpathxs вариантзаписидатыjson вариантпростоготипаxs видгруппымоделиxs видфасетаxdto ' + + 'действиепостроителяdom завершенностьпростоготипаxs завершенностьсоставноготипаxs завершенностьсхемыxs запрещенныеподстановкиxs ' + + 'исключениягруппподстановкиxs категорияиспользованияатрибутаxs категорияограниченияидентичностиxs категорияограниченияпространствименxs ' + + 'методнаследованияxs модельсодержимогоxs назначениетипаxml недопустимыеподстановкиxs обработкапробельныхсимволовxs обработкасодержимогоxs ' + + 'ограничениезначенияxs параметрыотбораузловdom переносстрокjson позициявдокументеdom пробельныесимволыxml типатрибутаxml типзначенияjson ' + + 'типканоническогоxml типкомпонентыxs типпроверкиxml типрезультатаdomxpath типузлаdom типузлаxml формаxml формапредставленияxs ' + + 'форматдатыjson экранированиесимволовjson '; + + // v8 системные перечисления - система компоновки данных ==> class + var v8_system_enums_data_composition_system = + 'видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных ' + + 'расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных ' + + 'расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных ' + + 'расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных ' + + 'типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных ' + + 'типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных ' + + 'типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных ' + + 'расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных ' + + 'режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных ' + + 'режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных '+ + 'вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных ' + + 'использованиеусловногооформлениякомпоновкиданных '; + + // v8 системные перечисления - почта ==> class + var v8_system_enums_email = + 'важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения ' + + 'способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты ' + + 'статусразборапочтовогосообщения '; + + // v8 системные перечисления - журнал регистрации ==> class + var v8_system_enums_logbook = + 'режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации '; + + // v8 системные перечисления - криптография ==> class + var v8_system_enums_cryptography = + 'расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии ' + + 'типхранилищасертификатовкриптографии '; + + // v8 системные перечисления - ZIP ==> class + var v8_system_enums_zip = + 'кодировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip ' + + 'режимсохраненияпутейzip уровеньсжатияzip '; + + // v8 системные перечисления - + // Блокировка данных, Фоновые задания, Автоматизированное тестирование, + // Доставляемые уведомления, Встроенные покупки, Интернет, Работа с двоичными данными ==> class + var v8_system_enums_other = + 'звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных ' + + 'сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp '; + + // v8 системные перечисления - схема запроса ==> class + var v8_system_enums_request_schema = + 'направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса ' + + 'типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса '; + + // v8 системные перечисления - свойства объектов метаданных ==> class + var v8_system_enums_properties_of_metadata_objects = + 'httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления ' + + 'видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование ' + + 'использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения ' + + 'использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита ' + + 'назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных ' + + 'оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи ' + + 'основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении ' + + 'периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений ' + + 'повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение ' + + 'разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита '+ + 'режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности ' + + 'режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов ' + + 'режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса ' + + 'режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов ' + + 'сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования ' + + 'типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса ' + + 'типномерадокумента типномеразадачи типформы удалениедвижений '; + + // v8 системные перечисления - разные ==> class + var v8_system_enums_differents = + 'важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения ' + + 'вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки ' + + 'видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак ' + + 'использованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога ' + + 'кодировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных ' + + 'отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения ' + + 'режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных ' + + 'способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter ' + + 'типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты'; + + // class: встроенные наборы значений, системные перечисления (содержат дочерние значения, обращения к которым через разыменование) + var CLASS = + v8_system_sets_of_values + + v8_system_enums_interface + + v8_system_enums_objects_properties + + v8_system_enums_exchange_plans + + v8_system_enums_tabular_document + + v8_system_enums_sheduler + + v8_system_enums_formatted_document + + v8_system_enums_query + + v8_system_enums_report_builder + + v8_system_enums_files + + v8_system_enums_query_builder + + v8_system_enums_data_analysis + + v8_system_enums_xml_json_xs_dom_xdto_ws + + v8_system_enums_data_composition_system + + v8_system_enums_email + + v8_system_enums_logbook + + v8_system_enums_cryptography + + v8_system_enums_zip + + v8_system_enums_other + + v8_system_enums_request_schema + + v8_system_enums_properties_of_metadata_objects + + v8_system_enums_differents; + + // v8 общие объекты (у объектов есть конструктор, экземпляры создаются методом НОВЫЙ) ==> type + var v8_shared_object = + 'comобъект ftpсоединение httpзапрос httpсервисответ httpсоединение wsопределения wsпрокси xbase анализданных аннотацияxs ' + + 'блокировкаданных буфердвоичныхданных включениеxs выражениекомпоновкиданных генераторслучайныхчисел географическаясхема ' + + 'географическиекоординаты графическаясхема группамоделиxs данныерасшифровкикомпоновкиданных двоичныеданные дендрограмма ' + + 'диаграмма диаграммаганта диалогвыборафайла диалогвыборацвета диалогвыборашрифта диалограсписаниярегламентногозадания ' + + 'диалогредактированиястандартногопериода диапазон документdom документhtml документацияxs доставляемоеуведомление ' + + 'записьdom записьfastinfoset записьhtml записьjson записьxml записьzipфайла записьданных записьтекста записьузловdom ' + + 'запрос защищенноесоединениеopenssl значенияполейрасшифровкикомпоновкиданных извлечениетекста импортxs интернетпочта ' + + 'интернетпочтовоесообщение интернетпочтовыйпрофиль интернетпрокси интернетсоединение информациядляприложенияxs ' + + 'использованиеатрибутаxs использованиесобытияжурналарегистрации источникдоступныхнастроеккомпоновкиданных ' + + 'итераторузловdom картинка квалификаторыдаты квалификаторыдвоичныхданных квалификаторыстроки квалификаторычисла ' + + 'компоновщикмакетакомпоновкиданных компоновщикнастроеккомпоновкиданных конструктормакетаоформлениякомпоновкиданных ' + + 'конструкторнастроеккомпоновкиданных конструкторформатнойстроки линия макеткомпоновкиданных макетобластикомпоновкиданных ' + + 'макетоформлениякомпоновкиданных маскаxs менеджеркриптографии наборсхемxml настройкикомпоновкиданных настройкисериализацииjson ' + + 'обработкакартинок обработкарасшифровкикомпоновкиданных обходдереваdom объявлениеатрибутаxs объявлениенотацииxs ' + + 'объявлениеэлементаxs описаниеиспользованиясобытиядоступжурналарегистрации ' + + 'описаниеиспользованиясобытияотказвдоступежурналарегистрации описаниеобработкирасшифровкикомпоновкиданных ' + + 'описаниепередаваемогофайла описаниетипов определениегруппыатрибутовxs определениегруппымоделиxs ' + + 'определениеограниченияидентичностиxs определениепростоготипаxs определениесоставноготипаxs определениетипадокументаdom ' + + 'определенияxpathxs отборкомпоновкиданных пакетотображаемыхдокументов параметрвыбора параметркомпоновкиданных ' + + 'параметрызаписиjson параметрызаписиxml параметрычтенияxml переопределениеxs планировщик полеанализаданных ' + + 'полекомпоновкиданных построительdom построительзапроса построительотчета построительотчетаанализаданных ' + + 'построительсхемxml поток потоквпамяти почта почтовоесообщение преобразованиеxsl преобразованиекканоническомуxml ' + + 'процессорвыводарезультатакомпоновкиданныхвколлекциюзначений процессорвыводарезультатакомпоновкиданныхвтабличныйдокумент ' + + 'процессоркомпоновкиданных разыменовательпространствименdom рамка расписаниерегламентногозадания расширенноеимяxml ' + + 'результатчтенияданных своднаядиаграмма связьпараметравыбора связьпотипу связьпотипукомпоновкиданных сериализаторxdto ' + + 'сертификатклиентаwindows сертификатклиентафайл сертификаткриптографии сертификатыудостоверяющихцентровwindows ' + + 'сертификатыудостоверяющихцентровфайл сжатиеданных системнаяинформация сообщениепользователю сочетаниеклавиш ' + + 'сравнениезначений стандартнаядатаначала стандартныйпериод схемаxml схемакомпоновкиданных табличныйдокумент ' + + 'текстовыйдокумент тестируемоеприложение типданныхxml уникальныйидентификатор фабрикаxdto файл файловыйпоток ' + + 'фасетдлиныxs фасетколичестваразрядовдробнойчастиxs фасетмаксимальноговключающегозначенияxs ' + + 'фасетмаксимальногоисключающегозначенияxs фасетмаксимальнойдлиныxs фасетминимальноговключающегозначенияxs ' + + 'фасетминимальногоисключающегозначенияxs фасетминимальнойдлиныxs фасетобразцаxs фасетобщегоколичестваразрядовxs ' + + 'фасетперечисленияxs фасетпробельныхсимволовxs фильтрузловdom форматированнаястрока форматированныйдокумент ' + + 'фрагментxs хешированиеданных хранилищезначения цвет чтениеfastinfoset чтениеhtml чтениеjson чтениеxml чтениеzipфайла ' + + 'чтениеданных чтениетекста чтениеузловdom шрифт элементрезультатакомпоновкиданных '; + + // v8 универсальные коллекции значений ==> type + var v8_universal_collection = + 'comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура ' + + 'фиксированноесоответствие фиксированныймассив '; + + // type : встроенные типы + var TYPE = + v8_shared_object + + v8_universal_collection; + + // literal : примитивные типы + var LITERAL = 'null истина ложь неопределено'; + + // number : числа + var NUMBERS = hljs.inherit(hljs.NUMBER_MODE); + + // string : строки + var STRINGS = { + className: 'string', + begin: '"|\\|', end: '"|$', + contains: [{begin: '""'}] + }; + + // number : даты + var DATE = { + begin: "'", end: "'", excludeBegin: true, excludeEnd: true, + contains: [ + { + className: 'number', + begin: '\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}' + } + ] + }; + + // comment : комментарии + var COMMENTS = hljs.inherit(hljs.C_LINE_COMMENT_MODE); + + // meta : инструкции препроцессора, директивы компиляции + var META = { + className: 'meta', + + begin: '#|&', end: '$', + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + 'meta-keyword': KEYWORD + METAKEYWORD + }, + contains: [ + COMMENTS + ] + }; + + // symbol : метка goto + var SYMBOL = { + className: 'symbol', + begin: '~', end: ';|:', excludeEnd: true + }; + + // function : объявление процедур и функций + var FUNCTION = { + className: 'function', + variants: [ + {begin: 'процедура|функция', end: '\\)', keywords: 'процедура функция'}, + {begin: 'конецпроцедуры|конецфункции', keywords: 'конецпроцедуры конецфункции'} + ], + contains: [ + { + begin: '\\(', end: '\\)', endsParent : true, + contains: [ + { + className: 'params', + begin: UNDERSCORE_IDENT_RE, end: ',', excludeEnd: true, endsWithParent: true, + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + keyword: 'знач', + literal: LITERAL + }, + contains: [ + NUMBERS, + STRINGS, + DATE + ] + }, + COMMENTS + ] + }, + hljs.inherit(hljs.TITLE_MODE, {begin: UNDERSCORE_IDENT_RE}) + ] + }; + + return { + name: '1C:Enterprise', + case_insensitive: true, + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + keyword: KEYWORD, + built_in: BUILTIN, + class: CLASS, + type: TYPE, + literal: LITERAL + }, + contains: [ + META, + FUNCTION, + COMMENTS, + SYMBOL, + NUMBERS, + STRINGS, + DATE + ] + }; +} + +module.exports = _1c; + + +/***/ }), + +/***/ 53887: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Augmented Backus-Naur Form +Author: Alex McKibben +Website: https://tools.ietf.org/html/rfc5234 +Audit: 2020 +*/ + +/** @type LanguageFn */ +function abnf(hljs) { + const regexes = { + ruleDeclaration: /^[a-zA-Z][a-zA-Z0-9-]*/, + unexpectedChars: /[!@#$^&',?+~`|:]/ + }; + + const keywords = [ + "ALPHA", + "BIT", + "CHAR", + "CR", + "CRLF", + "CTL", + "DIGIT", + "DQUOTE", + "HEXDIG", + "HTAB", + "LF", + "LWSP", + "OCTET", + "SP", + "VCHAR", + "WSP" + ]; + + const commentMode = hljs.COMMENT(/;/, /$/); + + const terminalBinaryMode = { + className: "symbol", + begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/ + }; + + const terminalDecimalMode = { + className: "symbol", + begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/ + }; + + const terminalHexadecimalMode = { + className: "symbol", + begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/ + }; + + const caseSensitivityIndicatorMode = { + className: "symbol", + begin: /%[si]/ + }; + + const ruleDeclarationMode = { + className: "attribute", + begin: concat(regexes.ruleDeclaration, /(?=\s*=)/) + }; + + return { + name: 'Augmented Backus-Naur Form', + illegal: regexes.unexpectedChars, + keywords: keywords, + contains: [ + ruleDeclarationMode, + commentMode, + terminalBinaryMode, + terminalDecimalMode, + terminalHexadecimalMode, + caseSensitivityIndicatorMode, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = abnf; + + +/***/ }), + +/***/ 10846: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* + Language: Apache Access Log + Author: Oleg Efimov + Description: Apache/Nginx Access Logs + Website: https://httpd.apache.org/docs/2.4/logs.html#accesslog + Audit: 2020 + */ + +/** @type LanguageFn */ +function accesslog(_hljs) { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods + const HTTP_VERBS = [ + "GET", + "POST", + "HEAD", + "PUT", + "DELETE", + "CONNECT", + "OPTIONS", + "PATCH", + "TRACE" + ]; + return { + name: 'Apache Access Log', + contains: [ + // IP + { + className: 'number', + begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/, + relevance: 5 + }, + // Other numbers + { + className: 'number', + begin: /\b\d+\b/, + relevance: 0 + }, + // Requests + { + className: 'string', + begin: concat(/"/, either(...HTTP_VERBS)), + end: /"/, + keywords: HTTP_VERBS, + illegal: /\n/, + relevance: 5, + contains: [ + { + begin: /HTTP\/[12]\.\d'/, + relevance: 5 + } + ] + }, + // Dates + { + className: 'string', + // dates must have a certain length, this prevents matching + // simple array accesses a[123] and [] and other common patterns + // found in other languages + begin: /\[\d[^\]\n]{8,}\]/, + illegal: /\n/, + relevance: 1 + }, + { + className: 'string', + begin: /\[/, + end: /\]/, + illegal: /\n/, + relevance: 0 + }, + // User agent / relevance boost + { + className: 'string', + begin: /"Mozilla\/\d\.\d \(/, + end: /"/, + illegal: /\n/, + relevance: 3 + }, + // Strings + { + className: 'string', + begin: /"/, + end: /"/, + illegal: /\n/, + relevance: 0 + } + ] + }; +} + +module.exports = accesslog; + + +/***/ }), + +/***/ 97001: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: ActionScript +Author: Alexander Myadzel +Category: scripting +Audit: 2020 +*/ + +/** @type LanguageFn */ +function actionscript(hljs) { + const IDENT_RE = /[a-zA-Z_$][a-zA-Z0-9_$]*/; + const IDENT_FUNC_RETURN_TYPE_RE = /([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/; + + const AS3_REST_ARG_MODE = { + className: 'rest_arg', + begin: /[.]{3}/, + end: IDENT_RE, + relevance: 10 + }; + + return { + name: 'ActionScript', + aliases: [ 'as' ], + keywords: { + keyword: 'as break case catch class const continue default delete do dynamic each ' + + 'else extends final finally for function get if implements import in include ' + + 'instanceof interface internal is namespace native new override package private ' + + 'protected public return set static super switch this throw try typeof use var void ' + + 'while with', + literal: 'true false null undefined' + }, + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_NUMBER_MODE, + { + className: 'class', + beginKeywords: 'package', + end: /\{/, + contains: [ hljs.TITLE_MODE ] + }, + { + className: 'class', + beginKeywords: 'class interface', + end: /\{/, + excludeEnd: true, + contains: [ + { beginKeywords: 'extends implements' }, + hljs.TITLE_MODE + ] + }, + { + className: 'meta', + beginKeywords: 'import include', + end: /;/, + keywords: { 'meta-keyword': 'import include' } + }, + { + className: 'function', + beginKeywords: 'function', + end: /[{;]/, + excludeEnd: true, + illegal: /\S/, + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AS3_REST_ARG_MODE + ] + }, + { begin: concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) } + ] + }, + hljs.METHOD_GUARD + ], + illegal: /#/ + }; +} + +module.exports = actionscript; + + +/***/ }), + +/***/ 98614: +/***/ ((module) => { + +/* +Language: Ada +Author: Lars Schulna +Description: Ada is a general-purpose programming language that has great support for saftey critical and real-time applications. + It has been developed by the DoD and thus has been used in military and safety-critical applications (like civil aviation). + The first version appeared in the 80s, but it's still actively developed today with + the newest standard being Ada2012. +*/ + +// We try to support full Ada2012 +// +// We highlight all appearances of types, keywords, literals (string, char, number, bool) +// and titles (user defined function/procedure/package) +// CSS classes are set accordingly +// +// Languages causing problems for language detection: +// xml (broken by Foo : Bar type), elm (broken by Foo : Bar type), vbscript-html (broken by body keyword) +// sql (ada default.txt has a lot of sql keywords) + +/** @type LanguageFn */ +function ada(hljs) { + // Regular expression for Ada numeric literals. + // stolen form the VHDL highlighter + + // Decimal literal: + const INTEGER_RE = '\\d(_|\\d)*'; + const EXPONENT_RE = '[eE][-+]?' + INTEGER_RE; + const DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?'; + + // Based literal: + const BASED_INTEGER_RE = '\\w+'; + const BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?'; + + const NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')'; + + // Identifier regex + const ID_REGEX = '[A-Za-z](_?[A-Za-z0-9.])*'; + + // bad chars, only allowed in literals + const BAD_CHARS = `[]\\{\\}%#'"`; + + // Ada doesn't have block comments, only line comments + const COMMENTS = hljs.COMMENT('--', '$'); + + // variable declarations of the form + // Foo : Bar := Baz; + // where only Bar will be highlighted + const VAR_DECLS = { + // TODO: These spaces are not required by the Ada syntax + // however, I have yet to see handwritten Ada code where + // someone does not put spaces around : + begin: '\\s+:\\s+', + end: '\\s*(:=|;|\\)|=>|$)', + // endsWithParent: true, + // returnBegin: true, + illegal: BAD_CHARS, + contains: [ + { + // workaround to avoid highlighting + // named loops and declare blocks + beginKeywords: 'loop for declare others', + endsParent: true + }, + { + // properly highlight all modifiers + className: 'keyword', + beginKeywords: 'not null constant access function procedure in out aliased exception' + }, + { + className: 'type', + begin: ID_REGEX, + endsParent: true, + relevance: 0 + } + ] + }; + + return { + name: 'Ada', + case_insensitive: true, + keywords: { + keyword: + 'abort else new return abs elsif not reverse abstract end ' + + 'accept entry select access exception of separate aliased exit or some ' + + 'all others subtype and for out synchronized array function overriding ' + + 'at tagged generic package task begin goto pragma terminate ' + + 'body private then if procedure type case in protected constant interface ' + + 'is raise use declare range delay limited record when delta loop rem while ' + + 'digits renames with do mod requeue xor', + literal: + 'True False' + }, + contains: [ + COMMENTS, + // strings "foobar" + { + className: 'string', + begin: /"/, + end: /"/, + contains: [{ + begin: /""/, + relevance: 0 + }] + }, + // characters '' + { + // character literals always contain one char + className: 'string', + begin: /'.'/ + }, + { + // number literals + className: 'number', + begin: NUMBER_RE, + relevance: 0 + }, + { + // Attributes + className: 'symbol', + begin: "'" + ID_REGEX + }, + { + // package definition, maybe inside generic + className: 'title', + begin: '(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?', + end: '(is|$)', + keywords: 'package body', + excludeBegin: true, + excludeEnd: true, + illegal: BAD_CHARS + }, + { + // function/procedure declaration/definition + // maybe inside generic + begin: '(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+', + end: '(\\bis|\\bwith|\\brenames|\\)\\s*;)', + keywords: 'overriding function procedure with is renames return', + // we need to re-match the 'function' keyword, so that + // the title mode below matches only exactly once + returnBegin: true, + contains: + [ + COMMENTS, + { + // name of the function/procedure + className: 'title', + begin: '(\\bwith\\s+)?\\b(function|procedure)\\s+', + end: '(\\(|\\s+|$)', + excludeBegin: true, + excludeEnd: true, + illegal: BAD_CHARS + }, + // 'self' + // // parameter types + VAR_DECLS, + { + // return type + className: 'type', + begin: '\\breturn\\s+', + end: '(\\s+|;|$)', + keywords: 'return', + excludeBegin: true, + excludeEnd: true, + // we are done with functions + endsParent: true, + illegal: BAD_CHARS + + } + ] + }, + { + // new type declarations + // maybe inside generic + className: 'type', + begin: '\\b(sub)?type\\s+', + end: '\\s+', + keywords: 'type', + excludeBegin: true, + illegal: BAD_CHARS + }, + + // see comment above the definition + VAR_DECLS + + // no markup + // relevance boosters for small snippets + // {begin: '\\s*=>\\s*'}, + // {begin: '\\s*:=\\s*'}, + // {begin: '\\s+:=\\s+'}, + ] + }; +} + +module.exports = ada; + + +/***/ }), + +/***/ 11156: +/***/ ((module) => { + +/* +Language: AngelScript +Author: Melissa Geels +Category: scripting +Website: https://www.angelcode.com/angelscript/ +*/ + +/** @type LanguageFn */ +function angelscript(hljs) { + var builtInTypeMode = { + className: 'built_in', + begin: '\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)' + }; + + var objectHandleMode = { + className: 'symbol', + begin: '[a-zA-Z0-9_]+@' + }; + + var genericMode = { + className: 'keyword', + begin: '<', end: '>', + contains: [ builtInTypeMode, objectHandleMode ] + }; + + builtInTypeMode.contains = [ genericMode ]; + objectHandleMode.contains = [ genericMode ]; + + return { + name: 'AngelScript', + aliases: ['asc'], + + keywords: + 'for in|0 break continue while do|0 return if else case switch namespace is cast ' + + 'or and xor not get|0 in inout|10 out override set|0 private public const default|0 ' + + 'final shared external mixin|10 enum typedef funcdef this super import from interface ' + + 'abstract|0 try catch protected explicit property', + + // avoid close detection with C# and JS + illegal: '(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])', + + contains: [ + { // 'strings' + className: 'string', + begin: '\'', end: '\'', + illegal: '\\n', + contains: [ hljs.BACKSLASH_ESCAPE ], + relevance: 0 + }, + + // """heredoc strings""" + { + className: 'string', + begin: '"""', end: '"""' + }, + + { // "strings" + className: 'string', + begin: '"', end: '"', + illegal: '\\n', + contains: [ hljs.BACKSLASH_ESCAPE ], + relevance: 0 + }, + + hljs.C_LINE_COMMENT_MODE, // single-line comments + hljs.C_BLOCK_COMMENT_MODE, // comment blocks + + { // metadata + className: 'string', + begin: '^\\s*\\[', end: '\\]', + }, + + { // interface or namespace declaration + beginKeywords: 'interface namespace', end: /\{/, + illegal: '[;.\\-]', + contains: [ + { // interface or namespace name + className: 'symbol', + begin: '[a-zA-Z0-9_]+' + } + ] + }, + + { // class declaration + beginKeywords: 'class', end: /\{/, + illegal: '[;.\\-]', + contains: [ + { // class name + className: 'symbol', + begin: '[a-zA-Z0-9_]+', + contains: [ + { + begin: '[:,]\\s*', + contains: [ + { + className: 'symbol', + begin: '[a-zA-Z0-9_]+' + } + ] + } + ] + } + ] + }, + + builtInTypeMode, // built-in types + objectHandleMode, // object handles + + { // literals + className: 'literal', + begin: '\\b(null|true|false)' + }, + + { // numbers + className: 'number', + relevance: 0, + begin: '(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)' + } + ] + }; +} + +module.exports = angelscript; + + +/***/ }), + +/***/ 93934: +/***/ ((module) => { + +/* +Language: Apache config +Author: Ruslan Keba +Contributors: Ivan Sagalaev +Website: https://httpd.apache.org +Description: language definition for Apache configuration files (httpd.conf & .htaccess) +Category: common, config +Audit: 2020 +*/ + +/** @type LanguageFn */ +function apache(hljs) { + const NUMBER_REF = { + className: 'number', + begin: /[$%]\d+/ + }; + const NUMBER = { + className: 'number', + begin: /\d+/ + }; + const IP_ADDRESS = { + className: "number", + begin: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/ + }; + const PORT_NUMBER = { + className: "number", + begin: /:\d{1,5}/ + }; + return { + name: 'Apache config', + aliases: [ 'apacheconf' ], + case_insensitive: true, + contains: [ + hljs.HASH_COMMENT_MODE, + { + className: 'section', + begin: /<\/?/, + end: />/, + contains: [ + IP_ADDRESS, + PORT_NUMBER, + // low relevance prevents us from claming XML/HTML where this rule would + // match strings inside of XML tags + hljs.inherit(hljs.QUOTE_STRING_MODE, { relevance: 0 }) + ] + }, + { + className: 'attribute', + begin: /\w+/, + relevance: 0, + // keywords aren’t needed for highlighting per se, they only boost relevance + // for a very generally defined mode (starts with a word, ends with line-end + keywords: { + nomarkup: + 'order deny allow setenv rewriterule rewriteengine rewritecond documentroot ' + + 'sethandler errordocument loadmodule options header listen serverroot ' + + 'servername' + }, + starts: { + end: /$/, + relevance: 0, + keywords: { literal: 'on off all deny allow' }, + contains: [ + { + className: 'meta', + begin: /\s\[/, + end: /\]$/ + }, + { + className: 'variable', + begin: /[\$%]\{/, + end: /\}/, + contains: [ + 'self', + NUMBER_REF + ] + }, + IP_ADDRESS, + NUMBER, + hljs.QUOTE_STRING_MODE + ] + } + } + ], + illegal: /\S/ + }; +} + +module.exports = apache; + + +/***/ }), + +/***/ 43673: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: AppleScript +Authors: Nathan Grigg , Dr. Drang +Category: scripting +Website: https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html +Audit: 2020 +*/ + +/** @type LanguageFn */ +function applescript(hljs) { + const STRING = hljs.inherit( + hljs.QUOTE_STRING_MODE, { + illegal: null + }); + const PARAMS = { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [ + 'self', + hljs.C_NUMBER_MODE, + STRING + ] + }; + const COMMENT_MODE_1 = hljs.COMMENT(/--/, /$/); + const COMMENT_MODE_2 = hljs.COMMENT( + /\(\*/, + /\*\)/, + { + contains: [ + 'self', // allow nesting + COMMENT_MODE_1 + ] + } + ); + const COMMENTS = [ + COMMENT_MODE_1, + COMMENT_MODE_2, + hljs.HASH_COMMENT_MODE + ]; + + const KEYWORD_PATTERNS = [ + /apart from/, + /aside from/, + /instead of/, + /out of/, + /greater than/, + /isn't|(doesn't|does not) (equal|come before|come after|contain)/, + /(greater|less) than( or equal)?/, + /(starts?|ends|begins?) with/, + /contained by/, + /comes (before|after)/, + /a (ref|reference)/, + /POSIX (file|path)/, + /(date|time) string/, + /quoted form/ + ]; + + const BUILT_IN_PATTERNS = [ + /clipboard info/, + /the clipboard/, + /info for/, + /list (disks|folder)/, + /mount volume/, + /path to/, + /(close|open for) access/, + /(get|set) eof/, + /current date/, + /do shell script/, + /get volume settings/, + /random number/, + /set volume/, + /system attribute/, + /system info/, + /time to GMT/, + /(load|run|store) script/, + /scripting components/, + /ASCII (character|number)/, + /localized string/, + /choose (application|color|file|file name|folder|from list|remote application|URL)/, + /display (alert|dialog)/ + ]; + + return { + name: 'AppleScript', + aliases: [ 'osascript' ], + keywords: { + keyword: + 'about above after against and around as at back before beginning ' + + 'behind below beneath beside between but by considering ' + + 'contain contains continue copy div does eighth else end equal ' + + 'equals error every exit fifth first for fourth from front ' + + 'get given global if ignoring in into is it its last local me ' + + 'middle mod my ninth not of on onto or over prop property put ref ' + + 'reference repeat returning script second set seventh since ' + + 'sixth some tell tenth that the|0 then third through thru ' + + 'timeout times to transaction try until where while whose with ' + + 'without', + literal: + 'AppleScript false linefeed return pi quote result space tab true', + built_in: + 'alias application boolean class constant date file integer list ' + + 'number real record string text ' + + 'activate beep count delay launch log offset read round ' + + 'run say summarize write ' + + 'character characters contents day frontmost id item length ' + + 'month name paragraph paragraphs rest reverse running time version ' + + 'weekday word words year' + }, + contains: [ + STRING, + hljs.C_NUMBER_MODE, + { + className: 'built_in', + begin: concat( + /\b/, + either(...BUILT_IN_PATTERNS), + /\b/ + ) + }, + { + className: 'built_in', + begin: /^\s*return\b/ + }, + { + className: 'literal', + begin: + /\b(text item delimiters|current application|missing value)\b/ + }, + { + className: 'keyword', + begin: concat( + /\b/, + either(...KEYWORD_PATTERNS), + /\b/ + ) + }, + { + beginKeywords: 'on', + illegal: /[${=;\n]/, + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }, + ...COMMENTS + ], + illegal: /\/\/|->|=>|\[\[/ + }; +} + +module.exports = applescript; + + +/***/ }), + +/***/ 59452: +/***/ ((module) => { + +/* + Language: ArcGIS Arcade + Category: scripting + Author: John Foster + Website: https://developers.arcgis.com/arcade/ + Description: ArcGIS Arcade is an expression language used in many Esri ArcGIS products such as Pro, Online, Server, Runtime, JavaScript, and Python +*/ + +/** @type LanguageFn */ +function arcade(hljs) { + const IDENT_RE = '[A-Za-z_][0-9A-Za-z_]*'; + const KEYWORDS = { + keyword: + 'if for while var new function do return void else break', + literal: + 'BackSlash DoubleQuote false ForwardSlash Infinity NaN NewLine null PI SingleQuote Tab TextFormatting true undefined', + built_in: + 'Abs Acos Angle Attachments Area AreaGeodetic Asin Atan Atan2 Average Bearing Boolean Buffer BufferGeodetic ' + + 'Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd ' + + 'DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance DistanceGeodetic Distinct ' + + 'DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetByAssociation FeatureSetById FeatureSetByPortalItem ' + + 'FeatureSetByRelationshipName FeatureSetByTitle FeatureSetByUrl Filter First Floor Geometry GroupBy Guid HasKey Hour IIf IndexOf ' + + 'Intersection Intersects IsEmpty IsNan IsSelfIntersecting Length LengthGeodetic Log Max Mean Millisecond Min Minute Month ' + + 'MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon ' + + 'Polyline Portal Pow Random Relate Reverse RingIsClockWise Round Second SetGeometry Sin Sort Sqrt Stdev Sum ' + + 'SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TrackCurrentTime ' + + 'TrackGeometryWindow TrackIndex TrackStartTime TrackWindow TypeOf Union UrlEncode Variance ' + + 'Weekday When Within Year ' + }; + const SYMBOL = { + className: 'symbol', + begin: '\\$[datastore|feature|layer|map|measure|sourcefeature|sourcelayer|targetfeature|targetlayer|value|view]+' + }; + const NUMBER = { + className: 'number', + variants: [ + { + begin: '\\b(0[bB][01]+)' + }, + { + begin: '\\b(0[oO][0-7]+)' + }, + { + begin: hljs.C_NUMBER_RE + } + ], + relevance: 0 + }; + const SUBST = { + className: 'subst', + begin: '\\$\\{', + end: '\\}', + keywords: KEYWORDS, + contains: [] // defined later + }; + const TEMPLATE_STRING = { + className: 'string', + begin: '`', + end: '`', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }; + SUBST.contains = [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + TEMPLATE_STRING, + NUMBER, + hljs.REGEXP_MODE + ]; + const PARAMS_CONTAINS = SUBST.contains.concat([ + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_LINE_COMMENT_MODE + ]); + + return { + name: 'ArcGIS Arcade', + keywords: KEYWORDS, + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + TEMPLATE_STRING, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + SYMBOL, + NUMBER, + { // object attr container + begin: /[{,]\s*/, + relevance: 0, + contains: [{ + begin: IDENT_RE + '\\s*:', + returnBegin: true, + relevance: 0, + contains: [{ + className: 'attr', + begin: IDENT_RE, + relevance: 0 + }] + }] + }, + { // "value" container + begin: '(' + hljs.RE_STARTERS_RE + '|\\b(return)\\b)\\s*', + keywords: 'return', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.REGEXP_MODE, + { + className: 'function', + begin: '(\\(.*?\\)|' + IDENT_RE + ')\\s*=>', + returnBegin: true, + end: '\\s*=>', + contains: [{ + className: 'params', + variants: [ + { + begin: IDENT_RE + }, + { + begin: /\(\s*\)/ + }, + { + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS, + contains: PARAMS_CONTAINS + } + ] + }] + } + ], + relevance: 0 + }, + { + className: 'function', + beginKeywords: 'function', + end: /\{/, + excludeEnd: true, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: IDENT_RE + }), + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + contains: PARAMS_CONTAINS + } + ], + illegal: /\[|%/ + }, + { + begin: /\$[(.]/ + } + ], + illegal: /#(?!!)/ + }; +} + +module.exports = arcade; + + +/***/ }), + +/***/ 22202: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: C++ +Category: common, system +Website: https://isocpp.org +*/ + +/** @type LanguageFn */ +function cPlusPlus(hljs) { + // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does + // not include such support nor can we be sure all the grammars depending + // on it would desire this behavior + const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', { + contains: [ + { + begin: /\\\n/ + } + ] + }); + const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)'; + const NAMESPACE_RE = '[a-zA-Z_]\\w*::'; + const TEMPLATE_ARGUMENT_RE = '<[^<>]+>'; + const FUNCTION_TYPE_RE = '(' + + DECLTYPE_AUTO_RE + '|' + + optional(NAMESPACE_RE) + + '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) + + ')'; + const CPP_PRIMITIVE_TYPES = { + className: 'keyword', + begin: '\\b[a-z\\d_]*_t\\b' + }; + + // https://en.cppreference.com/w/cpp/language/escape + // \\ \x \xFF \u2837 \u00323747 \374 + const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)'; + const STRINGS = { + className: 'string', + variants: [ + { + begin: '(u8?|U|L)?"', + end: '"', + illegal: '\\n', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)", + end: '\'', + illegal: '.' + }, + hljs.END_SAME_AS_BEGIN({ + begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/, + end: /\)([^()\\ ]{0,16})"/ + }) + ] + }; + + const NUMBERS = { + className: 'number', + variants: [ + { + begin: '\\b(0b[01\']+)' + }, + { + begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)' + }, + { + begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)' + } + ], + relevance: 0 + }; + + const PREPROCESSOR = { + className: 'meta', + begin: /#\s*[a-z]+\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'if else elif endif define undef warning error line ' + + 'pragma _Pragma ifdef ifndef include' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: /<.*?>/ + }, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + const TITLE_MODE = { + className: 'title', + begin: optional(NAMESPACE_RE) + hljs.IDENT_RE, + relevance: 0 + }; + + const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\('; + + const COMMON_CPP_HINTS = [ + 'asin', + 'atan2', + 'atan', + 'calloc', + 'ceil', + 'cosh', + 'cos', + 'exit', + 'exp', + 'fabs', + 'floor', + 'fmod', + 'fprintf', + 'fputs', + 'free', + 'frexp', + 'auto_ptr', + 'deque', + 'list', + 'queue', + 'stack', + 'vector', + 'map', + 'set', + 'pair', + 'bitset', + 'multiset', + 'multimap', + 'unordered_set', + 'fscanf', + 'future', + 'isalnum', + 'isalpha', + 'iscntrl', + 'isdigit', + 'isgraph', + 'islower', + 'isprint', + 'ispunct', + 'isspace', + 'isupper', + 'isxdigit', + 'tolower', + 'toupper', + 'labs', + 'ldexp', + 'log10', + 'log', + 'malloc', + 'realloc', + 'memchr', + 'memcmp', + 'memcpy', + 'memset', + 'modf', + 'pow', + 'printf', + 'putchar', + 'puts', + 'scanf', + 'sinh', + 'sin', + 'snprintf', + 'sprintf', + 'sqrt', + 'sscanf', + 'strcat', + 'strchr', + 'strcmp', + 'strcpy', + 'strcspn', + 'strlen', + 'strncat', + 'strncmp', + 'strncpy', + 'strpbrk', + 'strrchr', + 'strspn', + 'strstr', + 'tanh', + 'tan', + 'unordered_map', + 'unordered_multiset', + 'unordered_multimap', + 'priority_queue', + 'make_pair', + 'array', + 'shared_ptr', + 'abort', + 'terminate', + 'abs', + 'acos', + 'vfprintf', + 'vprintf', + 'vsprintf', + 'endl', + 'initializer_list', + 'unique_ptr', + 'complex', + 'imaginary', + 'std', + 'string', + 'wstring', + 'cin', + 'cout', + 'cerr', + 'clog', + 'stdin', + 'stdout', + 'stderr', + 'stringstream', + 'istringstream', + 'ostringstream' + ]; + + const CPP_KEYWORDS = { + keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' + + 'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' + + 'unsigned long volatile static protected bool template mutable if public friend ' + + 'do goto auto void enum else break extern using asm case typeid wchar_t ' + + 'short reinterpret_cast|10 default double register explicit signed typename try this ' + + 'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' + + 'concept co_await co_return co_yield requires ' + + 'noexcept static_assert thread_local restrict final override ' + + 'atomic_bool atomic_char atomic_schar ' + + 'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' + + 'atomic_ullong new throw return ' + + 'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq', + built_in: '_Bool _Complex _Imaginary', + _relevance_hints: COMMON_CPP_HINTS, + literal: 'true false nullptr NULL' + }; + + const FUNCTION_DISPATCH = { + className: "function.dispatch", + relevance: 0, + keywords: CPP_KEYWORDS, + begin: concat( + /\b/, + /(?!decltype)/, + /(?!if)/, + /(?!for)/, + /(?!while)/, + hljs.IDENT_RE, + lookahead(/\s*\(/)) + }; + + const EXPRESSION_CONTAINS = [ + FUNCTION_DISPATCH, + PREPROCESSOR, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS + ]; + + + const EXPRESSION_CONTEXT = { + // This mode covers expression context where we can't expect a function + // definition and shouldn't highlight anything that looks like one: + // `return some()`, `else if()`, `(x*sum(1, 2))` + variants: [ + { + begin: /=/, + end: /;/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + beginKeywords: 'new throw return else', + end: /;/ + } + ], + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat([ + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat([ 'self' ]), + relevance: 0 + } + ]), + relevance: 0 + }; + + const FUNCTION_DECLARATION = { + className: 'function', + begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE, + returnBegin: true, + end: /[{;=]/, + excludeEnd: true, + keywords: CPP_KEYWORDS, + illegal: /[^\w\s\*&:<>.]/, + contains: [ + { // to prevent it from being confused as the function title + begin: DECLTYPE_AUTO_RE, + keywords: CPP_KEYWORDS, + relevance: 0 + }, + { + begin: FUNCTION_TITLE, + returnBegin: true, + contains: [ TITLE_MODE ], + relevance: 0 + }, + // needed because we do not have look-behind on the below rule + // to prevent it from grabbing the final : in a :: pair + { + begin: /::/, + relevance: 0 + }, + // initializers + { + begin: /:/, + endsWithParent: true, + contains: [ + STRINGS, + NUMBERS + ] + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES, + // Count matching parentheses. + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + 'self', + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES + ] + } + ] + }, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + PREPROCESSOR + ] + }; + + return { + name: 'C++', + aliases: [ + 'cc', + 'c++', + 'h++', + 'hpp', + 'hh', + 'hxx', + 'cxx' + ], + keywords: CPP_KEYWORDS, + illegal: ' rooms (9);` + begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', + end: '>', + keywords: CPP_KEYWORDS, + contains: [ + 'self', + CPP_PRIMITIVE_TYPES + ] + }, + { + begin: hljs.IDENT_RE + '::', + keywords: CPP_KEYWORDS + }, + { + className: 'class', + beginKeywords: 'enum class struct union', + end: /[{;:<>=]/, + contains: [ + { + beginKeywords: "final class struct" + }, + hljs.TITLE_MODE + ] + } + ]), + exports: { + preprocessor: PREPROCESSOR, + strings: STRINGS, + keywords: CPP_KEYWORDS + } + }; +} + +/* +Language: Arduino +Author: Stefania Mellai +Description: The Arduino® Language is a superset of C++. This rules are designed to highlight the Arduino® source code. For info about language see http://www.arduino.cc. +Website: https://www.arduino.cc +*/ + +/** @type LanguageFn */ +function arduino(hljs) { + const ARDUINO_KW = { + keyword: + 'boolean byte word String', + built_in: + 'KeyboardController MouseController SoftwareSerial ' + + 'EthernetServer EthernetClient LiquidCrystal ' + + 'RobotControl GSMVoiceCall EthernetUDP EsploraTFT ' + + 'HttpClient RobotMotor WiFiClient GSMScanner ' + + 'FileSystem Scheduler GSMServer YunClient YunServer ' + + 'IPAddress GSMClient GSMModem Keyboard Ethernet ' + + 'Console GSMBand Esplora Stepper Process ' + + 'WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage ' + + 'Client Server GSMPIN FileIO Bridge Serial ' + + 'EEPROM Stream Mouse Audio Servo File Task ' + + 'GPRS WiFi Wire TFT GSM SPI SD ', + _: + 'setup loop ' + + 'runShellCommandAsynchronously analogWriteResolution ' + + 'retrieveCallingNumber printFirmwareVersion ' + + 'analogReadResolution sendDigitalPortPair ' + + 'noListenOnLocalhost readJoystickButton setFirmwareVersion ' + + 'readJoystickSwitch scrollDisplayRight getVoiceCallStatus ' + + 'scrollDisplayLeft writeMicroseconds delayMicroseconds ' + + 'beginTransmission getSignalStrength runAsynchronously ' + + 'getAsynchronously listenOnLocalhost getCurrentCarrier ' + + 'readAccelerometer messageAvailable sendDigitalPorts ' + + 'lineFollowConfig countryNameWrite runShellCommand ' + + 'readStringUntil rewindDirectory readTemperature ' + + 'setClockDivider readLightSensor endTransmission ' + + 'analogReference detachInterrupt countryNameRead ' + + 'attachInterrupt encryptionType readBytesUntil ' + + 'robotNameWrite readMicrophone robotNameRead cityNameWrite ' + + 'userNameWrite readJoystickY readJoystickX mouseReleased ' + + 'openNextFile scanNetworks noInterrupts digitalWrite ' + + 'beginSpeaker mousePressed isActionDone mouseDragged ' + + 'displayLogos noAutoscroll addParameter remoteNumber ' + + 'getModifiers keyboardRead userNameRead waitContinue ' + + 'processInput parseCommand printVersion readNetworks ' + + 'writeMessage blinkVersion cityNameRead readMessage ' + + 'setDataMode parsePacket isListening setBitOrder ' + + 'beginPacket isDirectory motorsWrite drawCompass ' + + 'digitalRead clearScreen serialEvent rightToLeft ' + + 'setTextSize leftToRight requestFrom keyReleased ' + + 'compassRead analogWrite interrupts WiFiServer ' + + 'disconnect playMelody parseFloat autoscroll ' + + 'getPINUsed setPINUsed setTimeout sendAnalog ' + + 'readSlider analogRead beginWrite createChar ' + + 'motorsStop keyPressed tempoWrite readButton ' + + 'subnetMask debugPrint macAddress writeGreen ' + + 'randomSeed attachGPRS readString sendString ' + + 'remotePort releaseAll mouseMoved background ' + + 'getXChange getYChange answerCall getResult ' + + 'voiceCall endPacket constrain getSocket writeJSON ' + + 'getButton available connected findUntil readBytes ' + + 'exitValue readGreen writeBlue startLoop IPAddress ' + + 'isPressed sendSysex pauseMode gatewayIP setCursor ' + + 'getOemKey tuneWrite noDisplay loadImage switchPIN ' + + 'onRequest onReceive changePIN playFile noBuffer ' + + 'parseInt overflow checkPIN knobRead beginTFT ' + + 'bitClear updateIR bitWrite position writeRGB ' + + 'highByte writeRed setSpeed readBlue noStroke ' + + 'remoteIP transfer shutdown hangCall beginSMS ' + + 'endWrite attached maintain noCursor checkReg ' + + 'checkPUK shiftOut isValid shiftIn pulseIn ' + + 'connect println localIP pinMode getIMEI ' + + 'display noBlink process getBand running beginSD ' + + 'drawBMP lowByte setBand release bitRead prepare ' + + 'pointTo readRed setMode noFill remove listen ' + + 'stroke detach attach noTone exists buffer ' + + 'height bitSet circle config cursor random ' + + 'IRread setDNS endSMS getKey micros ' + + 'millis begin print write ready flush width ' + + 'isPIN blink clear press mkdir rmdir close ' + + 'point yield image BSSID click delay ' + + 'read text move peek beep rect line open ' + + 'seek fill size turn stop home find ' + + 'step tone sqrt RSSI SSID ' + + 'end bit tan cos sin pow map abs max ' + + 'min get run put', + literal: + 'DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE ' + + 'REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP ' + + 'SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN ' + + 'INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL ' + + 'DEFAULT OUTPUT INPUT HIGH LOW' + }; + + const ARDUINO = cPlusPlus(hljs); + + const kws = /** @type {Record} */ (ARDUINO.keywords); + + kws.keyword += ' ' + ARDUINO_KW.keyword; + kws.literal += ' ' + ARDUINO_KW.literal; + kws.built_in += ' ' + ARDUINO_KW.built_in; + kws._ += ' ' + ARDUINO_KW._; + + ARDUINO.name = 'Arduino'; + ARDUINO.aliases = ['ino']; + ARDUINO.supersetOf = "cpp"; + + return ARDUINO; +} + +module.exports = arduino; + + +/***/ }), + +/***/ 6337: +/***/ ((module) => { + +/* +Language: ARM Assembly +Author: Dan Panzarella +Description: ARM Assembly including Thumb and Thumb2 instructions +Category: assembler +*/ + +/** @type LanguageFn */ +function armasm(hljs) { + // local labels: %?[FB]?[AT]?\d{1,2}\w+ + + const COMMENT = { + variants: [ + hljs.COMMENT('^[ \\t]*(?=#)', '$', { + relevance: 0, + excludeBegin: true + }), + hljs.COMMENT('[;@]', '$', { + relevance: 0 + }), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + return { + name: 'ARM Assembly', + case_insensitive: true, + aliases: ['arm'], + keywords: { + $pattern: '\\.?' + hljs.IDENT_RE, + meta: + // GNU preprocs + '.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ' + + // ARM directives + 'ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ', + built_in: + 'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 ' + // standard registers + 'pc lr sp ip sl sb fp ' + // typical regs plus backward compatibility + 'a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 ' + // more regs and fp + 'p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 ' + // coprocessor regs + 'c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 ' + // more coproc + 'q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 ' + // advanced SIMD NEON regs + + // program status registers + 'cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf ' + + 'spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf ' + + + // NEON and VFP registers + 's0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 ' + + 's16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 ' + + 'd0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 ' + + 'd16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 ' + + + '{PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @' + }, + contains: [ + { + className: 'keyword', + begin: '\\b(' + // mnemonics + 'adc|' + + '(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|' + + 'and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|' + + 'bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|' + + 'setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|' + + 'ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|' + + 'mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|' + + 'mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|' + + 'mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|' + + 'rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|' + + 'stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|' + + '[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|' + + 'wfe|wfi|yield' + + ')' + + '(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?' + // condition codes + '[sptrx]?' + // legal postfixes + '(?=\\s)' // followed by space + }, + COMMENT, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '[^\\\\]\'', + relevance: 0 + }, + { + className: 'title', + begin: '\\|', + end: '\\|', + illegal: '\\n', + relevance: 0 + }, + { + className: 'number', + variants: [ + { // hex + begin: '[#$=]?0x[0-9a-f]+' + }, + { // bin + begin: '[#$=]?0b[01]+' + }, + { // literal + begin: '[#$=]\\d+' + }, + { // bare number + begin: '\\b\\d+' + } + ], + relevance: 0 + }, + { + className: 'symbol', + variants: [ + { // GNU ARM syntax + begin: '^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:' + }, + { // ARM syntax + begin: '^[a-z_\\.\\$][a-z0-9_\\.\\$]+' + }, + { // label reference + begin: '[=#]\\w+' + } + ], + relevance: 0 + } + ] + }; +} + +module.exports = armasm; + + +/***/ }), + +/***/ 3515: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: AsciiDoc +Requires: xml.js +Author: Dan Allen +Website: http://asciidoc.org +Description: A semantic, text-based document format that can be exported to HTML, DocBook and other backends. +Category: markup +*/ + +/** @type LanguageFn */ +function asciidoc(hljs) { + const HORIZONTAL_RULE = { + begin: '^\'{3,}[ \\t]*$', + relevance: 10 + }; + const ESCAPED_FORMATTING = [ + // escaped constrained formatting marks (i.e., \* \_ or \`) + { + begin: /\\[*_`]/ + }, + // escaped unconstrained formatting marks (i.e., \\** \\__ or \\``) + // must ignore until the next formatting marks + // this rule might not be 100% compliant with Asciidoctor 2.0 but we are entering undefined behavior territory... + { + begin: /\\\\\*{2}[^\n]*?\*{2}/ + }, + { + begin: /\\\\_{2}[^\n]*_{2}/ + }, + { + begin: /\\\\`{2}[^\n]*`{2}/ + }, + // guard: constrained formatting mark may not be preceded by ":", ";" or + // "}". match these so the constrained rule doesn't see them + { + begin: /[:;}][*_`](?![*_`])/ + } + ]; + const STRONG = [ + // inline unconstrained strong (single line) + { + className: 'strong', + begin: /\*{2}([^\n]+?)\*{2}/ + }, + // inline unconstrained strong (multi-line) + { + className: 'strong', + begin: concat( + /\*\*/, + /((\*(?!\*)|\\[^\n]|[^*\n\\])+\n)+/, + /(\*(?!\*)|\\[^\n]|[^*\n\\])*/, + /\*\*/ + ), + relevance: 0 + }, + // inline constrained strong (single line) + { + className: 'strong', + // must not precede or follow a word character + begin: /\B\*(\S|\S[^\n]*?\S)\*(?!\w)/ + }, + // inline constrained strong (multi-line) + { + className: 'strong', + // must not precede or follow a word character + begin: /\*[^\s]([^\n]+\n)+([^\n]+)\*/ + } + ]; + const EMPHASIS = [ + // inline unconstrained emphasis (single line) + { + className: 'emphasis', + begin: /_{2}([^\n]+?)_{2}/ + }, + // inline unconstrained emphasis (multi-line) + { + className: 'emphasis', + begin: concat( + /__/, + /((_(?!_)|\\[^\n]|[^_\n\\])+\n)+/, + /(_(?!_)|\\[^\n]|[^_\n\\])*/, + /__/ + ), + relevance: 0 + }, + // inline constrained emphasis (single line) + { + className: 'emphasis', + // must not precede or follow a word character + begin: /\b_(\S|\S[^\n]*?\S)_(?!\w)/ + }, + // inline constrained emphasis (multi-line) + { + className: 'emphasis', + // must not precede or follow a word character + begin: /_[^\s]([^\n]+\n)+([^\n]+)_/ + }, + // inline constrained emphasis using single quote (legacy) + { + className: 'emphasis', + // must not follow a word character or be followed by a single quote or space + begin: '\\B\'(?![\'\\s])', + end: '(\\n{2}|\')', + // allow escaped single quote followed by word char + contains: [{ + begin: '\\\\\'\\w', + relevance: 0 + }], + relevance: 0 + } + ]; + const ADMONITION = { + className: 'symbol', + begin: '^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+', + relevance: 10 + }; + const BULLET_LIST = { + className: 'bullet', + begin: '^(\\*+|-+|\\.+|[^\\n]+?::)\\s+' + }; + + return { + name: 'AsciiDoc', + aliases: ['adoc'], + contains: [ + // block comment + hljs.COMMENT( + '^/{4,}\\n', + '\\n/{4,}$', + // can also be done as... + // '^/{4,}$', + // '^/{4,}$', + { + relevance: 10 + } + ), + // line comment + hljs.COMMENT( + '^//', + '$', + { + relevance: 0 + } + ), + // title + { + className: 'title', + begin: '^\\.\\w.*$' + }, + // example, admonition & sidebar blocks + { + begin: '^[=\\*]{4,}\\n', + end: '\\n^[=\\*]{4,}$', + relevance: 10 + }, + // headings + { + className: 'section', + relevance: 10, + variants: [ + { + begin: '^(={1,6})[ \t].+?([ \t]\\1)?$' + }, + { + begin: '^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$' + } + ] + }, + // document attributes + { + className: 'meta', + begin: '^:.+?:', + end: '\\s', + excludeEnd: true, + relevance: 10 + }, + // block attributes + { + className: 'meta', + begin: '^\\[.+?\\]$', + relevance: 0 + }, + // quoteblocks + { + className: 'quote', + begin: '^_{4,}\\n', + end: '\\n_{4,}$', + relevance: 10 + }, + // listing and literal blocks + { + className: 'code', + begin: '^[\\-\\.]{4,}\\n', + end: '\\n[\\-\\.]{4,}$', + relevance: 10 + }, + // passthrough blocks + { + begin: '^\\+{4,}\\n', + end: '\\n\\+{4,}$', + contains: [{ + begin: '<', + end: '>', + subLanguage: 'xml', + relevance: 0 + }], + relevance: 10 + }, + + BULLET_LIST, + ADMONITION, + ...ESCAPED_FORMATTING, + ...STRONG, + ...EMPHASIS, + + // inline smart quotes + { + className: 'string', + variants: [ + { + begin: "``.+?''" + }, + { + begin: "`.+?'" + } + ] + }, + // inline unconstrained emphasis + { + className: 'code', + begin: /`{2}/, + end: /(\n{2}|`{2})/ + }, + // inline code snippets (TODO should get same treatment as strong and emphasis) + { + className: 'code', + begin: '(`.+?`|\\+.+?\\+)', + relevance: 0 + }, + // indented literal block + { + className: 'code', + begin: '^[ \\t]', + end: '$', + relevance: 0 + }, + HORIZONTAL_RULE, + // images and links + { + begin: '(link:)?(http|https|ftp|file|irc|image:?):\\S+?\\[[^[]*?\\]', + returnBegin: true, + contains: [ + { + begin: '(link|image:?):', + relevance: 0 + }, + { + className: 'link', + begin: '\\w', + end: '[^\\[]+', + relevance: 0 + }, + { + className: 'string', + begin: '\\[', + end: '\\]', + excludeBegin: true, + excludeEnd: true, + relevance: 0 + } + ], + relevance: 10 + } + ] + }; +} + +module.exports = asciidoc; + + +/***/ }), + +/***/ 50436: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: AspectJ +Author: Hakan Ozler +Website: https://www.eclipse.org/aspectj/ +Description: Syntax Highlighting for the AspectJ Language which is a general-purpose aspect-oriented extension to the Java programming language. +Audit: 2020 +*/ + +/** @type LanguageFn */ +function aspectj(hljs) { + const KEYWORDS = + 'false synchronized int abstract float private char boolean static null if const ' + + 'for true while long throw strictfp finally protected import native final return void ' + + 'enum else extends implements break transient new catch instanceof byte super volatile case ' + + 'assert short package default double public try this switch continue throws privileged ' + + 'aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization ' + + 'staticinitialization withincode target within execution getWithinTypeName handler ' + + 'thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents ' + + 'warning error soft precedence thisAspectInstance'; + const SHORTKEYS = 'get set args call'; + + return { + name: 'AspectJ', + keywords: KEYWORDS, + illegal: /<\/|#/, + contains: [ + hljs.COMMENT( + /\/\*\*/, + /\*\//, + { + relevance: 0, + contains: [ + { + // eat up @'s in emails to prevent them to be recognized as doctags + begin: /\w+@/, + relevance: 0 + }, + { + className: 'doctag', + begin: /@[A-Za-z]+/ + } + ] + } + ), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'class', + beginKeywords: 'aspect', + end: /[{;=]/, + excludeEnd: true, + illegal: /[:;"\[\]]/, + contains: [ + { + beginKeywords: 'extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton' + }, + hljs.UNDERSCORE_TITLE_MODE, + { + begin: /\([^\)]*/, + end: /[)]+/, + keywords: KEYWORDS + ' ' + SHORTKEYS, + excludeEnd: false + } + ] + }, + { + className: 'class', + beginKeywords: 'class interface', + end: /[{;=]/, + excludeEnd: true, + relevance: 0, + keywords: 'class interface', + illegal: /[:"\[\]]/, + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + // AspectJ Constructs + beginKeywords: 'pointcut after before around throwing returning', + end: /[)]/, + excludeEnd: false, + illegal: /["\[\]]/, + contains: [ + { + begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/), + returnBegin: true, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + } + ] + }, + { + begin: /[:]/, + returnBegin: true, + end: /[{;]/, + relevance: 0, + excludeEnd: false, + keywords: KEYWORDS, + illegal: /["\[\]]/, + contains: [ + { + begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/), + keywords: KEYWORDS + ' ' + SHORTKEYS, + relevance: 0 + }, + hljs.QUOTE_STRING_MODE + ] + }, + { + // this prevents 'new Name(...), or throw ...' from being recognized as a function definition + beginKeywords: 'new throw', + relevance: 0 + }, + { + // the function class is a bit different for AspectJ compared to the Java language + className: 'function', + begin: /\w+ +\w+(\.\w+)?\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/, + returnBegin: true, + end: /[{;=]/, + keywords: KEYWORDS, + excludeEnd: true, + contains: [ + { + begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/), + returnBegin: true, + relevance: 0, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + relevance: 0, + keywords: KEYWORDS, + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_NUMBER_MODE, + { + // annotation is also used in this language + className: 'meta', + begin: /@[A-Za-z]+/ + } + ] + }; +} + +module.exports = aspectj; + + +/***/ }), + +/***/ 39381: +/***/ ((module) => { + +/* +Language: AutoHotkey +Author: Seongwon Lee +Description: AutoHotkey language definition +Category: scripting +*/ + +/** @type LanguageFn */ +function autohotkey(hljs) { + const BACKTICK_ESCAPE = { + begin: '`[\\s\\S]' + }; + + return { + name: 'AutoHotkey', + case_insensitive: true, + aliases: ['ahk'], + keywords: { + keyword: 'Break Continue Critical Exit ExitApp Gosub Goto New OnExit Pause return SetBatchLines SetTimer Suspend Thread Throw Until ahk_id ahk_class ahk_pid ahk_exe ahk_group', + literal: 'true false NOT AND OR', + built_in: 'ComSpec Clipboard ClipboardAll ErrorLevel' + }, + contains: [ + BACKTICK_ESCAPE, + hljs.inherit(hljs.QUOTE_STRING_MODE, { + contains: [BACKTICK_ESCAPE] + }), + hljs.COMMENT(';', '$', { + relevance: 0 + }), + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'number', + begin: hljs.NUMBER_RE, + relevance: 0 + }, + { + // subst would be the most accurate however fails the point of + // highlighting. variable is comparably the most accurate that actually + // has some effect + className: 'variable', + begin: '%[a-zA-Z0-9#_$@]+%' + }, + { + className: 'built_in', + begin: '^\\s*\\w+\\s*(,|%)' + // I don't really know if this is totally relevant + }, + { + // symbol would be most accurate however is highlighted just like + // built_in and that makes up a lot of AutoHotkey code meaning that it + // would fail to highlight anything + className: 'title', + variants: [ + { + begin: '^[^\\n";]+::(?!=)' + }, + { + begin: '^[^\\n";]+:(?!=)', + // zero relevance as it catches a lot of things + // followed by a single ':' in many languages + relevance: 0 + } + ] + }, + { + className: 'meta', + begin: '^\\s*#\\w+', + end: '$', + relevance: 0 + }, + { + className: 'built_in', + begin: 'A_[a-zA-Z0-9]+' + }, + { + // consecutive commas, not for highlighting but just for relevance + begin: ',\\s*,' + } + ] + }; +} + +module.exports = autohotkey; + + +/***/ }), + +/***/ 62694: +/***/ ((module) => { + +/* +Language: AutoIt +Author: Manh Tuan +Description: AutoIt language definition +Category: scripting +*/ + +/** @type LanguageFn */ +function autoit(hljs) { + const KEYWORDS = 'ByRef Case Const ContinueCase ContinueLoop ' + + 'Dim Do Else ElseIf EndFunc EndIf EndSelect ' + + 'EndSwitch EndWith Enum Exit ExitLoop For Func ' + + 'Global If In Local Next ReDim Return Select Static ' + + 'Step Switch Then To Until Volatile WEnd While With'; + + const DIRECTIVES = [ + "EndRegion", + "forcedef", + "forceref", + "ignorefunc", + "include", + "include-once", + "NoTrayIcon", + "OnAutoItStartRegister", + "pragma", + "Region", + "RequireAdmin", + "Tidy_Off", + "Tidy_On", + "Tidy_Parameters" + ]; + + const LITERAL = 'True False And Null Not Or Default'; + + const BUILT_IN + = 'Abs ACos AdlibRegister AdlibUnRegister Asc AscW ASin Assign ATan AutoItSetOption AutoItWinGetTitle AutoItWinSetTitle Beep Binary BinaryLen BinaryMid BinaryToString BitAND BitNOT BitOR BitRotate BitShift BitXOR BlockInput Break Call CDTray Ceiling Chr ChrW ClipGet ClipPut ConsoleRead ConsoleWrite ConsoleWriteError ControlClick ControlCommand ControlDisable ControlEnable ControlFocus ControlGetFocus ControlGetHandle ControlGetPos ControlGetText ControlHide ControlListView ControlMove ControlSend ControlSetText ControlShow ControlTreeView Cos Dec DirCopy DirCreate DirGetSize DirMove DirRemove DllCall DllCallAddress DllCallbackFree DllCallbackGetPtr DllCallbackRegister DllClose DllOpen DllStructCreate DllStructGetData DllStructGetPtr DllStructGetSize DllStructSetData DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus EnvGet EnvSet EnvUpdate Eval Execute Exp FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileReadToArray FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetEnd FileSetPos FileSetTime FileWrite FileWriteLine Floor FtpSetProxy FuncName GUICreate GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateCheckbox GUICtrlCreateCombo GUICtrlCreateContextMenu GUICtrlCreateDate GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView GUICtrlCreateTreeViewItem GUICtrlCreateUpdown GUICtrlDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRecvMsg GUICtrlRegisterListViewSort GUICtrlSendMsg GUICtrlSendToDummy GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState GUICtrlSetStyle GUICtrlSetTip GUIDelete GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle GUIStartGroup GUISwitch Hex HotKeySet HttpSetProxy HttpSetUserAgent HWnd InetClose InetGet InetGetInfo InetGetSize InetRead IniDelete IniRead IniReadSection IniReadSectionNames IniRenameSection IniWrite IniWriteSection InputBox Int IsAdmin IsArray IsBinary IsBool IsDeclared IsDllStruct IsFloat IsFunc IsHWnd IsInt IsKeyword IsNumber IsObj IsPtr IsString Log MemGetStats Mod MouseClick MouseClickDrag MouseDown MouseGetCursor MouseGetPos MouseMove MouseUp MouseWheel MsgBox Number ObjCreate ObjCreateInterface ObjEvent ObjGet ObjName OnAutoItExitRegister OnAutoItExitUnRegister Ping PixelChecksum PixelGetColor PixelSearch ProcessClose ProcessExists ProcessGetStats ProcessList ProcessSetPriority ProcessWait ProcessWaitClose ProgressOff ProgressOn ProgressSet Ptr Random RegDelete RegEnumKey RegEnumVal RegRead RegWrite Round Run RunAs RunAsWait RunWait Send SendKeepActive SetError SetExtended ShellExecute ShellExecuteWait Shutdown Sin Sleep SoundPlay SoundSetWaveVolume SplashImageOn SplashOff SplashTextOn Sqrt SRandom StatusbarGetText StderrRead StdinWrite StdioClose StdoutRead String StringAddCR StringCompare StringFormat StringFromASCIIArray StringInStr StringIsAlNum StringIsAlpha StringIsASCII StringIsDigit StringIsFloat StringIsInt StringIsLower StringIsSpace StringIsUpper StringIsXDigit StringLeft StringLen StringLower StringMid StringRegExp StringRegExpReplace StringReplace StringReverse StringRight StringSplit StringStripCR StringStripWS StringToASCIIArray StringToBinary StringTrimLeft StringTrimRight StringUpper Tan TCPAccept TCPCloseSocket TCPConnect TCPListen TCPNameToIP TCPRecv TCPSend TCPShutdown, UDPShutdown TCPStartup, UDPStartup TimerDiff TimerInit ToolTip TrayCreateItem TrayCreateMenu TrayGetMsg TrayItemDelete TrayItemGetHandle TrayItemGetState TrayItemGetText TrayItemSetOnEvent TrayItemSetState TrayItemSetText TraySetClick TraySetIcon TraySetOnEvent TraySetPauseIcon TraySetState TraySetToolTip TrayTip UBound UDPBind UDPCloseSocket UDPOpen UDPRecv UDPSend VarGetType WinActivate WinActive WinClose WinExists WinFlash WinGetCaretPos WinGetClassList WinGetClientSize WinGetHandle WinGetPos WinGetProcess WinGetState WinGetText WinGetTitle WinKill WinList WinMenuSelectItem WinMinimizeAll WinMinimizeAllUndo WinMove WinSetOnTop WinSetState WinSetTitle WinSetTrans WinWait WinWaitActive WinWaitClose WinWaitNotActive'; + + const COMMENT = { + variants: [ + hljs.COMMENT(';', '$', { + relevance: 0 + }), + hljs.COMMENT('#cs', '#ce'), + hljs.COMMENT('#comments-start', '#comments-end') + ] + }; + + const VARIABLE = { + begin: '\\$[A-z0-9_]+' + }; + + const STRING = { + className: 'string', + variants: [ + { + begin: /"/, + end: /"/, + contains: [{ + begin: /""/, + relevance: 0 + }] + }, + { + begin: /'/, + end: /'/, + contains: [{ + begin: /''/, + relevance: 0 + }] + } + ] + }; + + const NUMBER = { + variants: [ + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE + ] + }; + + const PREPROCESSOR = { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': DIRECTIVES + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + { + beginKeywords: 'include', + keywords: { + 'meta-keyword': 'include' + }, + end: '$', + contains: [ + STRING, + { + className: 'meta-string', + variants: [ + { + begin: '<', + end: '>' + }, + { + begin: /"/, + end: /"/, + contains: [{ + begin: /""/, + relevance: 0 + }] + }, + { + begin: /'/, + end: /'/, + contains: [{ + begin: /''/, + relevance: 0 + }] + } + ] + } + ] + }, + STRING, + COMMENT + ] + }; + + const CONSTANT = { + className: 'symbol', + // begin: '@', + // end: '$', + // keywords: 'AppDataCommonDir AppDataDir AutoItExe AutoItPID AutoItVersion AutoItX64 COM_EventObj CommonFilesDir Compiled ComputerName ComSpec CPUArch CR CRLF DesktopCommonDir DesktopDepth DesktopDir DesktopHeight DesktopRefresh DesktopWidth DocumentsCommonDir error exitCode exitMethod extended FavoritesCommonDir FavoritesDir GUI_CtrlHandle GUI_CtrlId GUI_DragFile GUI_DragId GUI_DropId GUI_WinHandle HomeDrive HomePath HomeShare HotKeyPressed HOUR IPAddress1 IPAddress2 IPAddress3 IPAddress4 KBLayout LF LocalAppDataDir LogonDNSDomain LogonDomain LogonServer MDAY MIN MON MSEC MUILang MyDocumentsDir NumParams OSArch OSBuild OSLang OSServicePack OSType OSVersion ProgramFilesDir ProgramsCommonDir ProgramsDir ScriptDir ScriptFullPath ScriptLineNumber ScriptName SEC StartMenuCommonDir StartMenuDir StartupCommonDir StartupDir SW_DISABLE SW_ENABLE SW_HIDE SW_LOCK SW_MAXIMIZE SW_MINIMIZE SW_RESTORE SW_SHOW SW_SHOWDEFAULT SW_SHOWMAXIMIZED SW_SHOWMINIMIZED SW_SHOWMINNOACTIVE SW_SHOWNA SW_SHOWNOACTIVATE SW_SHOWNORMAL SW_UNLOCK SystemDir TAB TempDir TRAY_ID TrayIconFlashing TrayIconVisible UserName UserProfileDir WDAY WindowsDir WorkingDir YDAY YEAR', + // relevance: 5 + begin: '@[A-z0-9_]+' + }; + + const FUNCTION = { + className: 'function', + beginKeywords: 'Func', + end: '$', + illegal: '\\$|\\[|%', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)', + contains: [ + VARIABLE, + STRING, + NUMBER + ] + } + ] + }; + + return { + name: 'AutoIt', + case_insensitive: true, + illegal: /\/\*/, + keywords: { + keyword: KEYWORDS, + built_in: BUILT_IN, + literal: LITERAL + }, + contains: [ + COMMENT, + VARIABLE, + STRING, + NUMBER, + PREPROCESSOR, + CONSTANT, + FUNCTION + ] + }; +} + +module.exports = autoit; + + +/***/ }), + +/***/ 74206: +/***/ ((module) => { + +/* +Language: AVR Assembly +Author: Vladimir Ermakov +Category: assembler +Website: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html +*/ + +/** @type LanguageFn */ +function avrasm(hljs) { + return { + name: 'AVR Assembly', + case_insensitive: true, + keywords: { + $pattern: '\\.?' + hljs.IDENT_RE, + keyword: + /* mnemonic */ + 'adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs ' + + 'brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr ' + + 'clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor ' + + 'fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul ' + + 'muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs ' + + 'sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub ' + + 'subi swap tst wdr', + built_in: + /* general purpose registers */ + 'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 ' + + 'r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ' + + /* IO Registers (ATMega128) */ + 'ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h ' + + 'tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ' + + 'ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ' + + 'ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk ' + + 'tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ' + + 'ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr ' + + 'porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ' + + 'ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf', + meta: + '.byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list ' + + '.listmac .macro .nolist .org .set' + }, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + hljs.C_NUMBER_MODE, // 0x..., decimal, float + hljs.BINARY_NUMBER_MODE, // 0b... + { + className: 'number', + begin: '\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)' // $..., 0o... + }, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '[^\\\\]\'', + illegal: '[^\\\\][^\']' + }, + { + className: 'symbol', + begin: '^[A-Za-z0-9_.$]+:' + }, + { + className: 'meta', + begin: '#', + end: '$' + }, + { // substitution within a macro + className: 'subst', + begin: '@[0-9]+' + } + ] + }; +} + +module.exports = avrasm; + + +/***/ }), + +/***/ 10327: +/***/ ((module) => { + +/* +Language: Awk +Author: Matthew Daly +Website: https://www.gnu.org/software/gawk/manual/gawk.html +Description: language definition for Awk scripts +*/ + +/** @type LanguageFn */ +function awk(hljs) { + const VARIABLE = { + className: 'variable', + variants: [ + { + begin: /\$[\w\d#@][\w\d_]*/ + }, + { + begin: /\$\{(.*?)\}/ + } + ] + }; + const KEYWORDS = 'BEGIN END if else while do for in break continue delete next nextfile function func exit|10'; + const STRING = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + { + begin: /(u|b)?r?'''/, + end: /'''/, + relevance: 10 + }, + { + begin: /(u|b)?r?"""/, + end: /"""/, + relevance: 10 + }, + { + begin: /(u|r|ur)'/, + end: /'/, + relevance: 10 + }, + { + begin: /(u|r|ur)"/, + end: /"/, + relevance: 10 + }, + { + begin: /(b|br)'/, + end: /'/ + }, + { + begin: /(b|br)"/, + end: /"/ + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }; + return { + name: 'Awk', + keywords: { + keyword: KEYWORDS + }, + contains: [ + VARIABLE, + STRING, + hljs.REGEXP_MODE, + hljs.HASH_COMMENT_MODE, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = awk; + + +/***/ }), + +/***/ 72171: +/***/ ((module) => { + +/* +Language: Microsoft X++ +Description: X++ is a language used in Microsoft Dynamics 365, Dynamics AX, and Axapta. +Author: Dmitri Roudakov +Website: https://dynamics.microsoft.com/en-us/ax-overview/ +Category: enterprise +*/ + +/** @type LanguageFn */ +function axapta(hljs) { + const BUILT_IN_KEYWORDS = [ + 'anytype', + 'boolean', + 'byte', + 'char', + 'container', + 'date', + 'double', + 'enum', + 'guid', + 'int', + 'int64', + 'long', + 'real', + 'short', + 'str', + 'utcdatetime', + 'var' + ]; + + const LITERAL_KEYWORDS = [ + 'default', + 'false', + 'null', + 'true' + ]; + + const NORMAL_KEYWORDS = [ + 'abstract', + 'as', + 'asc', + 'avg', + 'break', + 'breakpoint', + 'by', + 'byref', + 'case', + 'catch', + 'changecompany', + 'class', + 'client', + 'client', + 'common', + 'const', + 'continue', + 'count', + 'crosscompany', + 'delegate', + 'delete_from', + 'desc', + 'display', + 'div', + 'do', + 'edit', + 'else', + 'eventhandler', + 'exists', + 'extends', + 'final', + 'finally', + 'firstfast', + 'firstonly', + 'firstonly1', + 'firstonly10', + 'firstonly100', + 'firstonly1000', + 'flush', + 'for', + 'forceliterals', + 'forcenestedloop', + 'forceplaceholders', + 'forceselectorder', + 'forupdate', + 'from', + 'generateonly', + 'group', + 'hint', + 'if', + 'implements', + 'in', + 'index', + 'insert_recordset', + 'interface', + 'internal', + 'is', + 'join', + 'like', + 'maxof', + 'minof', + 'mod', + 'namespace', + 'new', + 'next', + 'nofetch', + 'notexists', + 'optimisticlock', + 'order', + 'outer', + 'pessimisticlock', + 'print', + 'private', + 'protected', + 'public', + 'readonly', + 'repeatableread', + 'retry', + 'return', + 'reverse', + 'select', + 'server', + 'setting', + 'static', + 'sum', + 'super', + 'switch', + 'this', + 'throw', + 'try', + 'ttsabort', + 'ttsbegin', + 'ttscommit', + 'unchecked', + 'update_recordset', + 'using', + 'validtimestate', + 'void', + 'where', + 'while' + ]; + + const KEYWORDS = { + keyword: NORMAL_KEYWORDS, + built_in: BUILT_IN_KEYWORDS, + literal: LITERAL_KEYWORDS + }; + + return { + name: 'X++', + aliases: ['x++'], + keywords: KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '#', + end: '$' + }, + { + className: 'class', + beginKeywords: 'class interface', + end: /\{/, + excludeEnd: true, + illegal: ':', + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + } + ] + }; +} + +module.exports = axapta; + + +/***/ }), + +/***/ 4720: +/***/ ((module) => { + +/* +Language: BASIC +Author: Raphaël Assénat +Description: Based on the BASIC reference from the Tandy 1000 guide +Website: https://en.wikipedia.org/wiki/Tandy_1000 +*/ + +/** @type LanguageFn */ +function basic(hljs) { + return { + name: 'BASIC', + case_insensitive: true, + illegal: '^\.', + // Support explicitly typed variables that end with $%! or #. + keywords: { + $pattern: '[a-zA-Z][a-zA-Z0-9_$%!#]*', + keyword: + 'ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE ' + + 'CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ ' + + 'DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ ' + + 'EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO ' + + 'HEX$ IF THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON ' + + 'OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET ' + + 'MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION ' + + 'BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET ' + + 'PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET ' + + 'RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP ' + + 'SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE ' + + 'WEND WIDTH WINDOW WRITE XOR' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.COMMENT('REM', '$', { + relevance: 10 + }), + hljs.COMMENT('\'', '$', { + relevance: 0 + }), + { + // Match line numbers + className: 'symbol', + begin: '^[0-9]+ ', + relevance: 10 + }, + { + // Match typed numeric constants (1000, 12.34!, 1.2e5, 1.5#, 1.2D2) + className: 'number', + begin: '\\b\\d+(\\.\\d+)?([edED]\\d+)?[#\!]?', + relevance: 0 + }, + { + // Match hexadecimal numbers (&Hxxxx) + className: 'number', + begin: '(&[hH][0-9a-fA-F]{1,4})' + }, + { + // Match octal numbers (&Oxxxxxx) + className: 'number', + begin: '(&[oO][0-7]{1,6})' + } + ] + }; +} + +module.exports = basic; + + +/***/ }), + +/***/ 43120: +/***/ ((module) => { + +/* +Language: Backus–Naur Form +Website: https://en.wikipedia.org/wiki/Backus–Naur_form +Author: Oleg Efimov +*/ + +/** @type LanguageFn */ +function bnf(hljs) { + return { + name: 'Backus–Naur Form', + contains: [ + // Attribute + { + className: 'attribute', + begin: // + }, + // Specific + { + begin: /::=/, + end: /$/, + contains: [ + { + begin: // + }, + // Common + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + ] + }; +} + +module.exports = bnf; + + +/***/ }), + +/***/ 80249: +/***/ ((module) => { + +/* +Language: Brainfuck +Author: Evgeny Stepanischev +Website: https://esolangs.org/wiki/Brainfuck +*/ + +/** @type LanguageFn */ +function brainfuck(hljs) { + const LITERAL = { + className: 'literal', + begin: /[+-]/, + relevance: 0 + }; + return { + name: 'Brainfuck', + aliases: ['bf'], + contains: [ + hljs.COMMENT( + '[^\\[\\]\\.,\\+\\-<> \r\n]', + '[\\[\\]\\.,\\+\\-<> \r\n]', + { + returnEnd: true, + relevance: 0 + } + ), + { + className: 'title', + begin: '[\\[\\]]', + relevance: 0 + }, + { + className: 'string', + begin: '[\\.,]', + relevance: 0 + }, + { + // this mode works as the only relevance counter + begin: /(?:\+\+|--)/, + contains: [LITERAL] + }, + LITERAL + ] + }; +} + +module.exports = brainfuck; + + +/***/ }), + +/***/ 29315: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: C++ +Category: common, system +Website: https://isocpp.org +*/ + +/** @type LanguageFn */ +function cPlusPlus(hljs) { + // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does + // not include such support nor can we be sure all the grammars depending + // on it would desire this behavior + const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', { + contains: [ + { + begin: /\\\n/ + } + ] + }); + const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)'; + const NAMESPACE_RE = '[a-zA-Z_]\\w*::'; + const TEMPLATE_ARGUMENT_RE = '<[^<>]+>'; + const FUNCTION_TYPE_RE = '(' + + DECLTYPE_AUTO_RE + '|' + + optional(NAMESPACE_RE) + + '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) + + ')'; + const CPP_PRIMITIVE_TYPES = { + className: 'keyword', + begin: '\\b[a-z\\d_]*_t\\b' + }; + + // https://en.cppreference.com/w/cpp/language/escape + // \\ \x \xFF \u2837 \u00323747 \374 + const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)'; + const STRINGS = { + className: 'string', + variants: [ + { + begin: '(u8?|U|L)?"', + end: '"', + illegal: '\\n', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)", + end: '\'', + illegal: '.' + }, + hljs.END_SAME_AS_BEGIN({ + begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/, + end: /\)([^()\\ ]{0,16})"/ + }) + ] + }; + + const NUMBERS = { + className: 'number', + variants: [ + { + begin: '\\b(0b[01\']+)' + }, + { + begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)' + }, + { + begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)' + } + ], + relevance: 0 + }; + + const PREPROCESSOR = { + className: 'meta', + begin: /#\s*[a-z]+\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'if else elif endif define undef warning error line ' + + 'pragma _Pragma ifdef ifndef include' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: /<.*?>/ + }, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + const TITLE_MODE = { + className: 'title', + begin: optional(NAMESPACE_RE) + hljs.IDENT_RE, + relevance: 0 + }; + + const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\('; + + const COMMON_CPP_HINTS = [ + 'asin', + 'atan2', + 'atan', + 'calloc', + 'ceil', + 'cosh', + 'cos', + 'exit', + 'exp', + 'fabs', + 'floor', + 'fmod', + 'fprintf', + 'fputs', + 'free', + 'frexp', + 'auto_ptr', + 'deque', + 'list', + 'queue', + 'stack', + 'vector', + 'map', + 'set', + 'pair', + 'bitset', + 'multiset', + 'multimap', + 'unordered_set', + 'fscanf', + 'future', + 'isalnum', + 'isalpha', + 'iscntrl', + 'isdigit', + 'isgraph', + 'islower', + 'isprint', + 'ispunct', + 'isspace', + 'isupper', + 'isxdigit', + 'tolower', + 'toupper', + 'labs', + 'ldexp', + 'log10', + 'log', + 'malloc', + 'realloc', + 'memchr', + 'memcmp', + 'memcpy', + 'memset', + 'modf', + 'pow', + 'printf', + 'putchar', + 'puts', + 'scanf', + 'sinh', + 'sin', + 'snprintf', + 'sprintf', + 'sqrt', + 'sscanf', + 'strcat', + 'strchr', + 'strcmp', + 'strcpy', + 'strcspn', + 'strlen', + 'strncat', + 'strncmp', + 'strncpy', + 'strpbrk', + 'strrchr', + 'strspn', + 'strstr', + 'tanh', + 'tan', + 'unordered_map', + 'unordered_multiset', + 'unordered_multimap', + 'priority_queue', + 'make_pair', + 'array', + 'shared_ptr', + 'abort', + 'terminate', + 'abs', + 'acos', + 'vfprintf', + 'vprintf', + 'vsprintf', + 'endl', + 'initializer_list', + 'unique_ptr', + 'complex', + 'imaginary', + 'std', + 'string', + 'wstring', + 'cin', + 'cout', + 'cerr', + 'clog', + 'stdin', + 'stdout', + 'stderr', + 'stringstream', + 'istringstream', + 'ostringstream' + ]; + + const CPP_KEYWORDS = { + keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' + + 'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' + + 'unsigned long volatile static protected bool template mutable if public friend ' + + 'do goto auto void enum else break extern using asm case typeid wchar_t ' + + 'short reinterpret_cast|10 default double register explicit signed typename try this ' + + 'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' + + 'concept co_await co_return co_yield requires ' + + 'noexcept static_assert thread_local restrict final override ' + + 'atomic_bool atomic_char atomic_schar ' + + 'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' + + 'atomic_ullong new throw return ' + + 'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq', + built_in: '_Bool _Complex _Imaginary', + _relevance_hints: COMMON_CPP_HINTS, + literal: 'true false nullptr NULL' + }; + + const FUNCTION_DISPATCH = { + className: "function.dispatch", + relevance: 0, + keywords: CPP_KEYWORDS, + begin: concat( + /\b/, + /(?!decltype)/, + /(?!if)/, + /(?!for)/, + /(?!while)/, + hljs.IDENT_RE, + lookahead(/\s*\(/)) + }; + + const EXPRESSION_CONTAINS = [ + FUNCTION_DISPATCH, + PREPROCESSOR, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS + ]; + + + const EXPRESSION_CONTEXT = { + // This mode covers expression context where we can't expect a function + // definition and shouldn't highlight anything that looks like one: + // `return some()`, `else if()`, `(x*sum(1, 2))` + variants: [ + { + begin: /=/, + end: /;/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + beginKeywords: 'new throw return else', + end: /;/ + } + ], + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat([ + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat([ 'self' ]), + relevance: 0 + } + ]), + relevance: 0 + }; + + const FUNCTION_DECLARATION = { + className: 'function', + begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE, + returnBegin: true, + end: /[{;=]/, + excludeEnd: true, + keywords: CPP_KEYWORDS, + illegal: /[^\w\s\*&:<>.]/, + contains: [ + { // to prevent it from being confused as the function title + begin: DECLTYPE_AUTO_RE, + keywords: CPP_KEYWORDS, + relevance: 0 + }, + { + begin: FUNCTION_TITLE, + returnBegin: true, + contains: [ TITLE_MODE ], + relevance: 0 + }, + // needed because we do not have look-behind on the below rule + // to prevent it from grabbing the final : in a :: pair + { + begin: /::/, + relevance: 0 + }, + // initializers + { + begin: /:/, + endsWithParent: true, + contains: [ + STRINGS, + NUMBERS + ] + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES, + // Count matching parentheses. + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + 'self', + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES + ] + } + ] + }, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + PREPROCESSOR + ] + }; + + return { + name: 'C++', + aliases: [ + 'cc', + 'c++', + 'h++', + 'hpp', + 'hh', + 'hxx', + 'cxx' + ], + keywords: CPP_KEYWORDS, + illegal: ' rooms (9);` + begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', + end: '>', + keywords: CPP_KEYWORDS, + contains: [ + 'self', + CPP_PRIMITIVE_TYPES + ] + }, + { + begin: hljs.IDENT_RE + '::', + keywords: CPP_KEYWORDS + }, + { + className: 'class', + beginKeywords: 'enum class struct union', + end: /[{;:<>=]/, + contains: [ + { + beginKeywords: "final class struct" + }, + hljs.TITLE_MODE + ] + } + ]), + exports: { + preprocessor: PREPROCESSOR, + strings: STRINGS, + keywords: CPP_KEYWORDS + } + }; +} + +/* +Language: C-like (deprecated, use C and C++ instead) +Author: Ivan Sagalaev +Contributors: Evgeny Stepanischev , Zaven Muradyan , Roel Deckers , Sam Wu , Jordi Petit , Pieter Vantorre , Google Inc. (David Benjamin) +*/ + +/** @type LanguageFn */ +function cLike(hljs) { + const lang = cPlusPlus(hljs); + + const C_ALIASES = [ + "c", + "h" + ]; + + const CPP_ALIASES = [ + 'cc', + 'c++', + 'h++', + 'hpp', + 'hh', + 'hxx', + 'cxx' + ]; + + lang.disableAutodetect = true; + lang.aliases = []; + // support users only loading c-like (legacy) + if (!hljs.getLanguage("c")) lang.aliases.push(...C_ALIASES); + if (!hljs.getLanguage("cpp")) lang.aliases.push(...CPP_ALIASES); + + // if c and cpp are loaded after then they will reclaim these + // aliases for themselves + + return lang; +} + +module.exports = cLike; + + +/***/ }), + +/***/ 12142: +/***/ ((module) => { + +/* +Language: C/AL +Author: Kenneth Fuglsang Christensen +Description: Provides highlighting of Microsoft Dynamics NAV C/AL code files +Website: https://docs.microsoft.com/en-us/dynamics-nav/programming-in-c-al +*/ + +/** @type LanguageFn */ +function cal(hljs) { + const KEYWORDS = + 'div mod in and or not xor asserterror begin case do downto else end exit for if of repeat then to ' + + 'until while with var'; + const LITERALS = 'false true'; + const COMMENT_MODES = [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT( + /\{/, + /\}/, + { + relevance: 0 + } + ), + hljs.COMMENT( + /\(\*/, + /\*\)/, + { + relevance: 10 + } + ) + ]; + const STRING = { + className: 'string', + begin: /'/, + end: /'/, + contains: [{ + begin: /''/ + }] + }; + const CHAR_STRING = { + className: 'string', + begin: /(#\d+)+/ + }; + const DATE = { + className: 'number', + begin: '\\b\\d+(\\.\\d+)?(DT|D|T)', + relevance: 0 + }; + const DBL_QUOTED_VARIABLE = { + className: 'string', // not a string technically but makes sense to be highlighted in the same style + begin: '"', + end: '"' + }; + + const PROCEDURE = { + className: 'function', + beginKeywords: 'procedure', + end: /[:;]/, + keywords: 'procedure|10', + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ + STRING, + CHAR_STRING + ] + } + ].concat(COMMENT_MODES) + }; + + const OBJECT = { + className: 'class', + begin: 'OBJECT (Table|Form|Report|Dataport|Codeunit|XMLport|MenuSuite|Page|Query) (\\d+) ([^\\r\\n]+)', + returnBegin: true, + contains: [ + hljs.TITLE_MODE, + PROCEDURE + ] + }; + + return { + name: 'C/AL', + case_insensitive: true, + keywords: { + keyword: KEYWORDS, + literal: LITERALS + }, + illegal: /\/\*/, + contains: [ + STRING, + CHAR_STRING, + DATE, + DBL_QUOTED_VARIABLE, + hljs.NUMBER_MODE, + OBJECT, + PROCEDURE + ] + }; +} + +module.exports = cal; + + +/***/ }), + +/***/ 63346: +/***/ ((module) => { + +/* +Language: Cap’n Proto +Author: Oleg Efimov +Description: Cap’n Proto message definition format +Website: https://capnproto.org/capnp-tool.html +Category: protocols +*/ + +/** @type LanguageFn */ +function capnproto(hljs) { + return { + name: 'Cap’n Proto', + aliases: ['capnp'], + keywords: { + keyword: + 'struct enum interface union group import using const annotation extends in of on as with from fixed', + built_in: + 'Void Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Float64 ' + + 'Text Data AnyPointer AnyStruct Capability List', + literal: + 'true false' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.HASH_COMMENT_MODE, + { + className: 'meta', + begin: /@0x[\w\d]{16};/, + illegal: /\n/ + }, + { + className: 'symbol', + begin: /@\d+\b/ + }, + { + className: 'class', + beginKeywords: 'struct enum', + end: /\{/, + illegal: /\n/, + contains: [hljs.inherit(hljs.TITLE_MODE, { + starts: { + endsWithParent: true, + excludeEnd: true + } // hack: eating everything after the first title + })] + }, + { + className: 'class', + beginKeywords: 'interface', + end: /\{/, + illegal: /\n/, + contains: [hljs.inherit(hljs.TITLE_MODE, { + starts: { + endsWithParent: true, + excludeEnd: true + } // hack: eating everything after the first title + })] + } + ] + }; +} + +module.exports = capnproto; + + +/***/ }), + +/***/ 72312: +/***/ ((module) => { + +/* +Language: Ceylon +Author: Lucas Werkmeister +Website: https://ceylon-lang.org +*/ + +/** @type LanguageFn */ +function ceylon(hljs) { + // 2.3. Identifiers and keywords + const KEYWORDS = + 'assembly module package import alias class interface object given value ' + + 'assign void function new of extends satisfies abstracts in out return ' + + 'break continue throw assert dynamic if else switch case for while try ' + + 'catch finally then let this outer super is exists nonempty'; + // 7.4.1 Declaration Modifiers + const DECLARATION_MODIFIERS = + 'shared abstract formal default actual variable late native deprecated ' + + 'final sealed annotation suppressWarnings small'; + // 7.4.2 Documentation + const DOCUMENTATION = + 'doc by license see throws tagged'; + const SUBST = { + className: 'subst', + excludeBegin: true, + excludeEnd: true, + begin: /``/, + end: /``/, + keywords: KEYWORDS, + relevance: 10 + }; + const EXPRESSIONS = [ + { + // verbatim string + className: 'string', + begin: '"""', + end: '"""', + relevance: 10 + }, + { + // string literal or template + className: 'string', + begin: '"', + end: '"', + contains: [SUBST] + }, + { + // character literal + className: 'string', + begin: "'", + end: "'" + }, + { + // numeric literal + className: 'number', + begin: '#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?', + relevance: 0 + } + ]; + SUBST.contains = EXPRESSIONS; + + return { + name: 'Ceylon', + keywords: { + keyword: KEYWORDS + ' ' + DECLARATION_MODIFIERS, + meta: DOCUMENTATION + }, + illegal: '\\$[^01]|#[^0-9a-fA-F]', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT('/\\*', '\\*/', { + contains: ['self'] + }), + { + // compiler annotation + className: 'meta', + begin: '@[a-z]\\w*(?::"[^"]*")?' + } + ].concat(EXPRESSIONS) + }; +} + +module.exports = ceylon; + + +/***/ }), + +/***/ 40583: +/***/ ((module) => { + +/* +Language: Clean +Author: Camil Staps +Category: functional +Website: http://clean.cs.ru.nl +*/ + +/** @type LanguageFn */ +function clean(hljs) { + return { + name: 'Clean', + aliases: [ + 'icl', + 'dcl' + ], + keywords: { + keyword: + 'if let in with where case of class instance otherwise ' + + 'implementation definition system module from import qualified as ' + + 'special code inline foreign export ccall stdcall generic derive ' + + 'infix infixl infixr', + built_in: + 'Int Real Char Bool', + literal: + 'True False' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { // relevance booster + begin: '->|<-[|:]?|#!?|>>=|\\{\\||\\|\\}|:==|=:|<>' + } + ] + }; +} + +module.exports = clean; + + +/***/ }), + +/***/ 8430: +/***/ ((module) => { + +/* +Language: Clojure REPL +Description: Clojure REPL sessions +Author: Ivan Sagalaev +Requires: clojure.js +Website: https://clojure.org +Category: lisp +*/ + +/** @type LanguageFn */ +function clojureRepl(hljs) { + return { + name: 'Clojure REPL', + contains: [ + { + className: 'meta', + begin: /^([\w.-]+|\s*#_)?=>/, + starts: { + end: /$/, + subLanguage: 'clojure' + } + } + ] + }; +} + +module.exports = clojureRepl; + + +/***/ }), + +/***/ 83926: +/***/ ((module) => { + +/* +Language: Clojure +Description: Clojure syntax (based on lisp.js) +Author: mfornos +Website: https://clojure.org +Category: lisp +*/ + +/** @type LanguageFn */ +function clojure(hljs) { + const SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\''; + const SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*'; + const globals = 'def defonce defprotocol defstruct defmulti defmethod defn- defn defmacro deftype defrecord'; + const keywords = { + $pattern: SYMBOL_RE, + 'builtin-name': + // Clojure keywords + globals + ' ' + + 'cond apply if-not if-let if not not= =|0 <|0 >|0 <=|0 >=|0 ==|0 +|0 /|0 *|0 -|0 rem ' + + 'quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? ' + + 'set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? ' + + 'class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? ' + + 'string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . ' + + 'inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last ' + + 'drop-while while intern condp case reduced cycle split-at split-with repeat replicate ' + + 'iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext ' + + 'nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends ' + + 'add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler ' + + 'set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter ' + + 'monitor-exit macroexpand macroexpand-1 for dosync and or ' + + 'when when-not when-let comp juxt partial sequence memoize constantly complement identity assert ' + + 'peek pop doto proxy first rest cons cast coll last butlast ' + + 'sigs reify second ffirst fnext nfirst nnext meta with-meta ns in-ns create-ns import ' + + 'refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! ' + + 'assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger ' + + 'bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline ' + + 'flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking ' + + 'assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! ' + + 'reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! ' + + 'new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty ' + + 'hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list ' + + 'disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer ' + + 'chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate ' + + 'unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta ' + + 'lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize' + }; + + const SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?'; + + const SYMBOL = { + begin: SYMBOL_RE, + relevance: 0 + }; + const NUMBER = { + className: 'number', + begin: SIMPLE_NUMBER_RE, + relevance: 0 + }; + const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }); + const COMMENT = hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ); + const LITERAL = { + className: 'literal', + begin: /\b(true|false|nil)\b/ + }; + const COLLECTION = { + begin: '[\\[\\{]', + end: '[\\]\\}]' + }; + const HINT = { + className: 'comment', + begin: '\\^' + SYMBOL_RE + }; + const HINT_COL = hljs.COMMENT('\\^\\{', '\\}'); + const KEY = { + className: 'symbol', + begin: '[:]{1,2}' + SYMBOL_RE + }; + const LIST = { + begin: '\\(', + end: '\\)' + }; + const BODY = { + endsWithParent: true, + relevance: 0 + }; + const NAME = { + keywords: keywords, + className: 'name', + begin: SYMBOL_RE, + relevance: 0, + starts: BODY + }; + const DEFAULT_CONTAINS = [ + LIST, + STRING, + HINT, + HINT_COL, + COMMENT, + KEY, + COLLECTION, + NUMBER, + LITERAL, + SYMBOL + ]; + + const GLOBAL = { + beginKeywords: globals, + lexemes: SYMBOL_RE, + end: '(\\[|#|\\d|"|:|\\{|\\)|\\(|$)', + contains: [ + { + className: 'title', + begin: SYMBOL_RE, + relevance: 0, + excludeEnd: true, + // we can only have a single title + endsParent: true + } + ].concat(DEFAULT_CONTAINS) + }; + + LIST.contains = [ + hljs.COMMENT('comment', ''), + GLOBAL, + NAME, + BODY + ]; + BODY.contains = DEFAULT_CONTAINS; + COLLECTION.contains = DEFAULT_CONTAINS; + HINT_COL.contains = [ COLLECTION ]; + + return { + name: 'Clojure', + aliases: [ 'clj' ], + illegal: /\S/, + contains: [ + LIST, + STRING, + HINT, + HINT_COL, + COMMENT, + KEY, + COLLECTION, + NUMBER, + LITERAL + ] + }; +} + +module.exports = clojure; + + +/***/ }), + +/***/ 95765: +/***/ ((module) => { + +/* +Language: CMake +Description: CMake is an open-source cross-platform system for build automation. +Author: Igor Kalnitsky +Website: https://cmake.org +*/ + +/** @type LanguageFn */ +function cmake(hljs) { + return { + name: 'CMake', + aliases: ['cmake.in'], + case_insensitive: true, + keywords: { + keyword: + // scripting commands + 'break cmake_host_system_information cmake_minimum_required cmake_parse_arguments ' + + 'cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro ' + + 'endwhile execute_process file find_file find_library find_package find_path ' + + 'find_program foreach function get_cmake_property get_directory_property ' + + 'get_filename_component get_property if include include_guard list macro ' + + 'mark_as_advanced math message option return separate_arguments ' + + 'set_directory_properties set_property set site_name string unset variable_watch while ' + + // project commands + 'add_compile_definitions add_compile_options add_custom_command add_custom_target ' + + 'add_definitions add_dependencies add_executable add_library add_link_options ' + + 'add_subdirectory add_test aux_source_directory build_command create_test_sourcelist ' + + 'define_property enable_language enable_testing export fltk_wrap_ui ' + + 'get_source_file_property get_target_property get_test_property include_directories ' + + 'include_external_msproject include_regular_expression install link_directories ' + + 'link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions ' + + 'set_source_files_properties set_target_properties set_tests_properties source_group ' + + 'target_compile_definitions target_compile_features target_compile_options ' + + 'target_include_directories target_link_directories target_link_libraries ' + + 'target_link_options target_sources try_compile try_run ' + + // CTest commands + 'ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ' + + 'ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ' + + 'ctest_test ctest_update ctest_upload ' + + // deprecated commands + 'build_name exec_program export_library_dependencies install_files install_programs ' + + 'install_targets load_command make_directory output_required_files remove ' + + 'subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file ' + + 'qt5_use_modules qt5_use_package qt5_wrap_cpp ' + + // core keywords + 'on off true false and or not command policy target test exists is_newer_than ' + + 'is_directory is_symlink is_absolute matches less greater equal less_equal ' + + 'greater_equal strless strgreater strequal strless_equal strgreater_equal version_less ' + + 'version_greater version_equal version_less_equal version_greater_equal in_list defined' + }, + contains: [ + { + className: 'variable', + begin: /\$\{/, + end: /\}/ + }, + hljs.HASH_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = cmake; + + +/***/ }), + +/***/ 12007: +/***/ ((module) => { + +const KEYWORDS = [ + "as", // for exports + "in", + "of", + "if", + "for", + "while", + "finally", + "var", + "new", + "function", + "do", + "return", + "void", + "else", + "break", + "catch", + "instanceof", + "with", + "throw", + "case", + "default", + "try", + "switch", + "continue", + "typeof", + "delete", + "let", + "yield", + "const", + "class", + // JS handles these with a special rule + // "get", + // "set", + "debugger", + "async", + "await", + "static", + "import", + "from", + "export", + "extends" +]; +const LITERALS = [ + "true", + "false", + "null", + "undefined", + "NaN", + "Infinity" +]; + +const TYPES = [ + "Intl", + "DataView", + "Number", + "Math", + "Date", + "String", + "RegExp", + "Object", + "Function", + "Boolean", + "Error", + "Symbol", + "Set", + "Map", + "WeakSet", + "WeakMap", + "Proxy", + "Reflect", + "JSON", + "Promise", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Float32Array", + "Array", + "Uint8Array", + "Uint8ClampedArray", + "ArrayBuffer", + "BigInt64Array", + "BigUint64Array", + "BigInt" +]; + +const ERROR_TYPES = [ + "EvalError", + "InternalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError" +]; + +const BUILT_IN_GLOBALS = [ + "setInterval", + "setTimeout", + "clearInterval", + "clearTimeout", + + "require", + "exports", + + "eval", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape" +]; + +const BUILT_IN_VARIABLES = [ + "arguments", + "this", + "super", + "console", + "window", + "document", + "localStorage", + "module", + "global" // Node.js +]; + +const BUILT_INS = [].concat( + BUILT_IN_GLOBALS, + BUILT_IN_VARIABLES, + TYPES, + ERROR_TYPES +); + +/* +Language: CoffeeScript +Author: Dmytrii Nagirniak +Contributors: Oleg Efimov , Cédric Néhémie +Description: CoffeeScript is a programming language that transcompiles to JavaScript. For info about language see http://coffeescript.org/ +Category: common, scripting +Website: https://coffeescript.org +*/ + +/** @type LanguageFn */ +function coffeescript(hljs) { + const COFFEE_BUILT_INS = [ + 'npm', + 'print' + ]; + const COFFEE_LITERALS = [ + 'yes', + 'no', + 'on', + 'off' + ]; + const COFFEE_KEYWORDS = [ + 'then', + 'unless', + 'until', + 'loop', + 'by', + 'when', + 'and', + 'or', + 'is', + 'isnt', + 'not' + ]; + const NOT_VALID_KEYWORDS = [ + "var", + "const", + "let", + "function", + "static" + ]; + const excluding = (list) => + (kw) => !list.includes(kw); + const KEYWORDS$1 = { + keyword: KEYWORDS.concat(COFFEE_KEYWORDS).filter(excluding(NOT_VALID_KEYWORDS)), + literal: LITERALS.concat(COFFEE_LITERALS), + built_in: BUILT_INS.concat(COFFEE_BUILT_INS) + }; + const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: KEYWORDS$1 + }; + const EXPRESSIONS = [ + hljs.BINARY_NUMBER_MODE, + hljs.inherit(hljs.C_NUMBER_MODE, { + starts: { + end: '(\\s*/)?', + relevance: 0 + } + }), // a number tries to eat the following slash to prevent treating it as a regexp + { + className: 'string', + variants: [ + { + begin: /'''/, + end: /'''/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /'/, + end: /'/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /"""/, + end: /"""/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + }, + { + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + } + ] + }, + { + className: 'regexp', + variants: [ + { + begin: '///', + end: '///', + contains: [ + SUBST, + hljs.HASH_COMMENT_MODE + ] + }, + { + begin: '//[gim]{0,3}(?=\\W)', + relevance: 0 + }, + { + // regex can't start with space to parse x / 2 / 3 as two divisions + // regex can't start with *, and it supports an "illegal" in the main mode + begin: /\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/ + } + ] + }, + { + begin: '@' + JS_IDENT_RE // relevance booster + }, + { + subLanguage: 'javascript', + excludeBegin: true, + excludeEnd: true, + variants: [ + { + begin: '```', + end: '```' + }, + { + begin: '`', + end: '`' + } + ] + } + ]; + SUBST.contains = EXPRESSIONS; + + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: JS_IDENT_RE + }); + const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>'; + const PARAMS = { + className: 'params', + begin: '\\([^\\(]', + returnBegin: true, + /* We need another contained nameless mode to not have every nested + pair of parens to be called "params" */ + contains: [{ + begin: /\(/, + end: /\)/, + keywords: KEYWORDS$1, + contains: ['self'].concat(EXPRESSIONS) + }] + }; + + return { + name: 'CoffeeScript', + aliases: [ + 'coffee', + 'cson', + 'iced' + ], + keywords: KEYWORDS$1, + illegal: /\/\*/, + contains: EXPRESSIONS.concat([ + hljs.COMMENT('###', '###'), + hljs.HASH_COMMENT_MODE, + { + className: 'function', + begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [ + TITLE, + PARAMS + ] + }, + { + // anonymous function start + begin: /[:\(,=]\s*/, + relevance: 0, + contains: [{ + className: 'function', + begin: POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [PARAMS] + }] + }, + { + className: 'class', + beginKeywords: 'class', + end: '$', + illegal: /[:="\[\]]/, + contains: [ + { + beginKeywords: 'extends', + endsWithParent: true, + illegal: /[:="\[\]]/, + contains: [TITLE] + }, + TITLE + ] + }, + { + begin: JS_IDENT_RE + ':', + end: ':', + returnBegin: true, + returnEnd: true, + relevance: 0 + } + ]) + }; +} + +module.exports = coffeescript; + + +/***/ }), + +/***/ 61083: +/***/ ((module) => { + +/* +Language: Coq +Author: Stephan Boyer +Category: functional +Website: https://coq.inria.fr +*/ + +/** @type LanguageFn */ +function coq(hljs) { + return { + name: 'Coq', + keywords: { + keyword: + '_|0 as at cofix else end exists exists2 fix for forall fun if IF in let ' + + 'match mod Prop return Set then Type using where with ' + + 'Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo ' + + 'Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion ' + + 'Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture ' + + 'Conjectures Constant constr Constraint Constructors Context Corollary ' + + 'CreateHintDb Cut Declare Defined Definition Delimit Dependencies Dependent ' + + 'Derive Drop eauto End Equality Eval Example Existential Existentials ' + + 'Existing Export exporting Extern Extract Extraction Fact Field Fields File ' + + 'Fixpoint Focus for From Function Functional Generalizable Global Goal Grab ' + + 'Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident ' + + 'Identity If Immediate Implicit Import Include Inductive Infix Info Initial ' + + 'Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear ' + + 'Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML ' + + 'Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation ' + + 'Obligations Opaque Open Optimize Options Parameter Parameters Parametric ' + + 'Path Paths pattern Polymorphic Preterm Print Printing Program Projections ' + + 'Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark ' + + 'Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save ' + + 'Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern ' + + 'SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies ' + + 'Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time ' + + 'Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused ' + + 'Unfold Universe Universes Unset Unshelve using Variable Variables Variant ' + + 'Verbose Visibility where with', + built_in: + 'abstract absurd admit after apply as assert assumption at auto autorewrite ' + + 'autounfold before bottom btauto by case case_eq cbn cbv change ' + + 'classical_left classical_right clear clearbody cofix compare compute ' + + 'congruence constr_eq constructor contradict contradiction cut cutrewrite ' + + 'cycle decide decompose dependent destruct destruction dintuition ' + + 'discriminate discrR do double dtauto eapply eassumption eauto ecase ' + + 'econstructor edestruct ediscriminate eelim eexact eexists einduction ' + + 'einjection eleft elim elimtype enough equality erewrite eright ' + + 'esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail ' + + 'field field_simplify field_simplify_eq first firstorder fix fold fourier ' + + 'functional generalize generalizing gfail give_up has_evar hnf idtac in ' + + 'induction injection instantiate intro intro_pattern intros intuition ' + + 'inversion inversion_clear is_evar is_var lapply lazy left lia lra move ' + + 'native_compute nia nsatz omega once pattern pose progress proof psatz quote ' + + 'record red refine reflexivity remember rename repeat replace revert ' + + 'revgoals rewrite rewrite_strat right ring ring_simplify rtauto set ' + + 'setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry ' + + 'setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve ' + + 'specialize split split_Rabs split_Rmult stepl stepr subst sum swap ' + + 'symmetry tactic tauto time timeout top transitivity trivial try tryif ' + + 'unfold unify until using vm_compute with' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.COMMENT('\\(\\*', '\\*\\)'), + hljs.C_NUMBER_MODE, + { + className: 'type', + excludeBegin: true, + begin: '\\|\\s*', + end: '\\w+' + }, + { // relevance booster + begin: /[-=]>/ + } + ] + }; +} + +module.exports = coq; + + +/***/ }), + +/***/ 25501: +/***/ ((module) => { + +/* +Language: Caché Object Script +Author: Nikita Savchenko +Category: enterprise, scripting +Website: https://cedocs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls +*/ + +/** @type LanguageFn */ +function cos(hljs) { + const STRINGS = { + className: 'string', + variants: [{ + begin: '"', + end: '"', + contains: [{ // escaped + begin: "\"\"", + relevance: 0 + }] + }] + }; + + const NUMBERS = { + className: "number", + begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)", + relevance: 0 + }; + + const COS_KEYWORDS = + 'property parameter class classmethod clientmethod extends as break ' + + 'catch close continue do d|0 else elseif for goto halt hang h|0 if job ' + + 'j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 ' + + 'tcommit throw trollback try tstart use view while write w|0 xecute x|0 ' + + 'zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert ' + + 'zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit ' + + 'zsync ascii'; + + // registered function - no need in them due to all functions are highlighted, + // but I'll just leave this here. + + // "$bit", "$bitcount", + // "$bitfind", "$bitlogic", "$case", "$char", "$classmethod", "$classname", + // "$compile", "$data", "$decimal", "$double", "$extract", "$factor", + // "$find", "$fnumber", "$get", "$increment", "$inumber", "$isobject", + // "$isvaliddouble", "$isvalidnum", "$justify", "$length", "$list", + // "$listbuild", "$listdata", "$listfind", "$listfromstring", "$listget", + // "$listlength", "$listnext", "$listsame", "$listtostring", "$listvalid", + // "$locate", "$match", "$method", "$name", "$nconvert", "$next", + // "$normalize", "$now", "$number", "$order", "$parameter", "$piece", + // "$prefetchoff", "$prefetchon", "$property", "$qlength", "$qsubscript", + // "$query", "$random", "$replace", "$reverse", "$sconvert", "$select", + // "$sortbegin", "$sortend", "$stack", "$text", "$translate", "$view", + // "$wascii", "$wchar", "$wextract", "$wfind", "$wiswide", "$wlength", + // "$wreverse", "$xecute", "$zabs", "$zarccos", "$zarcsin", "$zarctan", + // "$zcos", "$zcot", "$zcsc", "$zdate", "$zdateh", "$zdatetime", + // "$zdatetimeh", "$zexp", "$zhex", "$zln", "$zlog", "$zpower", "$zsec", + // "$zsin", "$zsqr", "$ztan", "$ztime", "$ztimeh", "$zboolean", + // "$zconvert", "$zcrc", "$zcyc", "$zdascii", "$zdchar", "$zf", + // "$ziswide", "$zlascii", "$zlchar", "$zname", "$zposition", "$zqascii", + // "$zqchar", "$zsearch", "$zseek", "$zstrip", "$zwascii", "$zwchar", + // "$zwidth", "$zwpack", "$zwbpack", "$zwunpack", "$zwbunpack", "$zzenkaku", + // "$change", "$mv", "$mvat", "$mvfmt", "$mvfmts", "$mviconv", + // "$mviconvs", "$mvinmat", "$mvlover", "$mvoconv", "$mvoconvs", "$mvraise", + // "$mvtrans", "$mvv", "$mvname", "$zbitand", "$zbitcount", "$zbitfind", + // "$zbitget", "$zbitlen", "$zbitnot", "$zbitor", "$zbitset", "$zbitstr", + // "$zbitxor", "$zincrement", "$znext", "$zorder", "$zprevious", "$zsort", + // "device", "$ecode", "$estack", "$etrap", "$halt", "$horolog", + // "$io", "$job", "$key", "$namespace", "$principal", "$quit", "$roles", + // "$storage", "$system", "$test", "$this", "$tlevel", "$username", + // "$x", "$y", "$za", "$zb", "$zchild", "$zeof", "$zeos", "$zerror", + // "$zhorolog", "$zio", "$zjob", "$zmode", "$znspace", "$zparent", "$zpi", + // "$zpos", "$zreference", "$zstorage", "$ztimestamp", "$ztimezone", + // "$ztrap", "$zversion" + + return { + name: 'Caché Object Script', + case_insensitive: true, + aliases: [ + "cls" + ], + keywords: COS_KEYWORDS, + contains: [ + NUMBERS, + STRINGS, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: "comment", + begin: /;/, + end: "$", + relevance: 0 + }, + { // Functions and user-defined functions: write $ztime(60*60*3), $$myFunc(10), $$^Val(1) + className: "built_in", + begin: /(?:\$\$?|\.\.)\^?[a-zA-Z]+/ + }, + { // Macro command: quit $$$OK + className: "built_in", + begin: /\$\$\$[a-zA-Z]+/ + }, + { // Special (global) variables: write %request.Content; Built-in classes: %Library.Integer + className: "built_in", + begin: /%[a-z]+(?:\.[a-z]+)*/ + }, + { // Global variable: set ^globalName = 12 write ^globalName + className: "symbol", + begin: /\^%?[a-zA-Z][\w]*/ + }, + { // Some control constructions: do ##class(Package.ClassName).Method(), ##super() + className: "keyword", + begin: /##class|##super|#define|#dim/ + }, + // sub-languages: are not fully supported by hljs by 11/15/2015 + // left for the future implementation. + { + begin: /&sql\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + subLanguage: "sql" + }, + { + begin: /&(js|jscript|javascript)/, + excludeBegin: true, + excludeEnd: true, + subLanguage: "javascript" + }, + { + // this brakes first and last tag, but this is the only way to embed a valid html + begin: /&html<\s*\s*>/, + subLanguage: "xml" + } + ] + }; +} + +module.exports = cos; + + +/***/ }), + +/***/ 61309: +/***/ ((module) => { + +/* +Language: crmsh +Author: Kristoffer Gronlund +Website: http://crmsh.github.io +Description: Syntax Highlighting for the crmsh DSL +Category: config +*/ + +/** @type LanguageFn */ +function crmsh(hljs) { + const RESOURCES = 'primitive rsc_template'; + const COMMANDS = 'group clone ms master location colocation order fencing_topology ' + + 'rsc_ticket acl_target acl_group user role ' + + 'tag xml'; + const PROPERTY_SETS = 'property rsc_defaults op_defaults'; + const KEYWORDS = 'params meta operations op rule attributes utilization'; + const OPERATORS = 'read write deny defined not_defined in_range date spec in ' + + 'ref reference attribute type xpath version and or lt gt tag ' + + 'lte gte eq ne \\'; + const TYPES = 'number string'; + const LITERALS = 'Master Started Slave Stopped start promote demote stop monitor true false'; + + return { + name: 'crmsh', + aliases: [ + 'crm', + 'pcmk' + ], + case_insensitive: true, + keywords: { + keyword: KEYWORDS + ' ' + OPERATORS + ' ' + TYPES, + literal: LITERALS + }, + contains: [ + hljs.HASH_COMMENT_MODE, + { + beginKeywords: 'node', + starts: { + end: '\\s*([\\w_-]+:)?', + starts: { + className: 'title', + end: '\\s*[\\$\\w_][\\w_-]*' + } + } + }, + { + beginKeywords: RESOURCES, + starts: { + className: 'title', + end: '\\s*[\\$\\w_][\\w_-]*', + starts: { + end: '\\s*@?[\\w_][\\w_\\.:-]*' + } + } + }, + { + begin: '\\b(' + COMMANDS.split(' ').join('|') + ')\\s+', + keywords: COMMANDS, + starts: { + className: 'title', + end: '[\\$\\w_][\\w_-]*' + } + }, + { + beginKeywords: PROPERTY_SETS, + starts: { + className: 'title', + end: '\\s*([\\w_-]+:)?' + } + }, + hljs.QUOTE_STRING_MODE, + { + className: 'meta', + begin: '(ocf|systemd|service|lsb):[\\w_:-]+', + relevance: 0 + }, + { + className: 'number', + begin: '\\b\\d+(\\.\\d+)?(ms|s|h|m)?', + relevance: 0 + }, + { + className: 'literal', + begin: '[-]?(infinity|inf)', + relevance: 0 + }, + { + className: 'attr', + begin: /([A-Za-z$_#][\w_-]+)=/, + relevance: 0 + }, + { + className: 'tag', + begin: '', + relevance: 0 + } + ] + }; +} + +module.exports = crmsh; + + +/***/ }), + +/***/ 5356: +/***/ ((module) => { + +/* +Language: Crystal +Author: TSUYUSATO Kitsune +Website: https://crystal-lang.org +*/ + +/** @type LanguageFn */ +function crystal(hljs) { + const INT_SUFFIX = '(_?[ui](8|16|32|64|128))?'; + const FLOAT_SUFFIX = '(_?f(32|64))?'; + const CRYSTAL_IDENT_RE = '[a-zA-Z_]\\w*[!?=]?'; + const CRYSTAL_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|[=!]~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~|]|//|//=|&[-+*]=?|&\\*\\*|\\[\\][=?]?'; + const CRYSTAL_PATH_RE = '[A-Za-z_]\\w*(::\\w+)*(\\?|!)?'; + const CRYSTAL_KEYWORDS = { + $pattern: CRYSTAL_IDENT_RE, + keyword: + 'abstract alias annotation as as? asm begin break case class def do else elsif end ensure enum extend for fun if ' + + 'include instance_sizeof is_a? lib macro module next nil? of out pointerof private protected rescue responds_to? ' + + 'return require select self sizeof struct super then type typeof union uninitialized unless until verbatim when while with yield ' + + '__DIR__ __END_LINE__ __FILE__ __LINE__', + literal: 'false nil true' + }; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: CRYSTAL_KEYWORDS + }; + const EXPANSION = { + className: 'template-variable', + variants: [ + { + begin: '\\{\\{', + end: '\\}\\}' + }, + { + begin: '\\{%', + end: '%\\}' + } + ], + keywords: CRYSTAL_KEYWORDS + }; + + function recursiveParen(begin, end) { + const + contains = [ + { + begin: begin, + end: end + } + ]; + contains[0].contains = contains; + return contains; + } + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + }, + { + begin: /`/, + end: /`/ + }, + { + begin: '%[Qwi]?\\(', + end: '\\)', + contains: recursiveParen('\\(', '\\)') + }, + { + begin: '%[Qwi]?\\[', + end: '\\]', + contains: recursiveParen('\\[', '\\]') + }, + { + begin: '%[Qwi]?\\{', + end: /\}/, + contains: recursiveParen(/\{/, /\}/) + }, + { + begin: '%[Qwi]?<', + end: '>', + contains: recursiveParen('<', '>') + }, + { + begin: '%[Qwi]?\\|', + end: '\\|' + }, + { + begin: /<<-\w+$/, + end: /^\s*\w+$/ + } + ], + relevance: 0 + }; + const Q_STRING = { + className: 'string', + variants: [ + { + begin: '%q\\(', + end: '\\)', + contains: recursiveParen('\\(', '\\)') + }, + { + begin: '%q\\[', + end: '\\]', + contains: recursiveParen('\\[', '\\]') + }, + { + begin: '%q\\{', + end: /\}/, + contains: recursiveParen(/\{/, /\}/) + }, + { + begin: '%q<', + end: '>', + contains: recursiveParen('<', '>') + }, + { + begin: '%q\\|', + end: '\\|' + }, + { + begin: /<<-'\w+'$/, + end: /^\s*\w+$/ + } + ], + relevance: 0 + }; + const REGEXP = { + begin: '(?!%\\})(' + hljs.RE_STARTERS_RE + '|\\n|\\b(case|if|select|unless|until|when|while)\\b)\\s*', + keywords: 'case if select unless until when while', + contains: [ + { + className: 'regexp', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: '//[a-z]*', + relevance: 0 + }, + { + begin: '/(?!\\/)', + end: '/[a-z]*' + } + ] + } + ], + relevance: 0 + }; + const REGEXP2 = { + className: 'regexp', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: '%r\\(', + end: '\\)', + contains: recursiveParen('\\(', '\\)') + }, + { + begin: '%r\\[', + end: '\\]', + contains: recursiveParen('\\[', '\\]') + }, + { + begin: '%r\\{', + end: /\}/, + contains: recursiveParen(/\{/, /\}/) + }, + { + begin: '%r<', + end: '>', + contains: recursiveParen('<', '>') + }, + { + begin: '%r\\|', + end: '\\|' + } + ], + relevance: 0 + }; + const ATTRIBUTE = { + className: 'meta', + begin: '@\\[', + end: '\\]', + contains: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'meta-string' + }) + ] + }; + const CRYSTAL_DEFAULT_CONTAINS = [ + EXPANSION, + STRING, + Q_STRING, + REGEXP2, + REGEXP, + ATTRIBUTE, + hljs.HASH_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'class module struct', + end: '$|;', + illegal: /=/, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.inherit(hljs.TITLE_MODE, { + begin: CRYSTAL_PATH_RE + }), + { // relevance booster for inheritance + begin: '<' + } + ] + }, + { + className: 'class', + beginKeywords: 'lib enum union', + end: '$|;', + illegal: /=/, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.inherit(hljs.TITLE_MODE, { + begin: CRYSTAL_PATH_RE + }) + ] + }, + { + beginKeywords: 'annotation', + end: '$|;', + illegal: /=/, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.inherit(hljs.TITLE_MODE, { + begin: CRYSTAL_PATH_RE + }) + ], + relevance: 2 + }, + { + className: 'function', + beginKeywords: 'def', + end: /\B\b/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: CRYSTAL_METHOD_RE, + endsParent: true + }) + ] + }, + { + className: 'function', + beginKeywords: 'fun macro', + end: /\B\b/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: CRYSTAL_METHOD_RE, + endsParent: true + }) + ], + relevance: 2 + }, + { + className: 'symbol', + begin: hljs.UNDERSCORE_IDENT_RE + '(!|\\?)?:', + relevance: 0 + }, + { + className: 'symbol', + begin: ':', + contains: [ + STRING, + { + begin: CRYSTAL_METHOD_RE + } + ], + relevance: 0 + }, + { + className: 'number', + variants: [ + { + begin: '\\b0b([01_]+)' + INT_SUFFIX + }, + { + begin: '\\b0o([0-7_]+)' + INT_SUFFIX + }, + { + begin: '\\b0x([A-Fa-f0-9_]+)' + INT_SUFFIX + }, + { + begin: '\\b([1-9][0-9_]*[0-9]|[0-9])(\\.[0-9][0-9_]*)?([eE]_?[-+]?[0-9_]*)?' + FLOAT_SUFFIX + '(?!_)' + }, + { + begin: '\\b([1-9][0-9_]*|0)' + INT_SUFFIX + } + ], + relevance: 0 + } + ]; + SUBST.contains = CRYSTAL_DEFAULT_CONTAINS; + EXPANSION.contains = CRYSTAL_DEFAULT_CONTAINS.slice(1); // without EXPANSION + + return { + name: 'Crystal', + aliases: [ 'cr' ], + keywords: CRYSTAL_KEYWORDS, + contains: CRYSTAL_DEFAULT_CONTAINS + }; +} + +module.exports = crystal; + + +/***/ }), + +/***/ 22216: +/***/ ((module) => { + +/* +Language: CSP +Description: Content Security Policy definition highlighting +Author: Taras +Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP + +vim: ts=2 sw=2 st=2 +*/ + +/** @type LanguageFn */ +function csp(hljs) { + return { + name: 'CSP', + case_insensitive: false, + keywords: { + $pattern: '[a-zA-Z][a-zA-Z0-9_-]*', + keyword: 'base-uri child-src connect-src default-src font-src form-action ' + + 'frame-ancestors frame-src img-src media-src object-src plugin-types ' + + 'report-uri sandbox script-src style-src' + }, + contains: [ + { + className: 'string', + begin: "'", + end: "'" + }, + { + className: 'attribute', + begin: '^Content', + end: ':', + excludeEnd: true + } + ] + }; +} + +module.exports = csp; + + +/***/ }), + +/***/ 40961: +/***/ ((module) => { + +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: CSS +Category: common, css +Website: https://developer.mozilla.org/en-US/docs/Web/CSS +*/ + +/** @type LanguageFn */ +function css(hljs) { + const modes = MODES(hljs); + const FUNCTION_DISPATCH = { + className: "built_in", + begin: /[\w-]+(?=\()/ + }; + const VENDOR_PREFIX = { + begin: /-(webkit|moz|ms|o)-(?=[a-z])/ + }; + const AT_MODIFIERS = "and or not only"; + const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/; // @-webkit-keyframes + const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*'; + const STRINGS = [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ]; + + return { + name: 'CSS', + case_insensitive: true, + illegal: /[=|'\$]/, + keywords: { + keyframePosition: "from to" + }, + classNameAliases: { + // for visual continuity with `tag {}` and because we + // don't have a great class for this? + keyframePosition: "selector-tag" + }, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + VENDOR_PREFIX, + // to recognize keyframe 40% etc which are outside the scope of our + // attribute value mode + hljs.CSS_NUMBER_MODE, + { + className: 'selector-id', + begin: /#[A-Za-z0-9_-]+/, + relevance: 0 + }, + { + className: 'selector-class', + begin: '\\.' + IDENT_RE, + relevance: 0 + }, + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-pseudo', + variants: [ + { + begin: ':(' + PSEUDO_CLASSES.join('|') + ')' + }, + { + begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')' + } + ] + }, + // we may actually need this (12/2020) + // { // pseudo-selector params + // begin: /\(/, + // end: /\)/, + // contains: [ hljs.CSS_NUMBER_MODE ] + // }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b' + }, + // attribute values + { + begin: ':', + end: '[;}]', + contains: [ + modes.HEXCOLOR, + modes.IMPORTANT, + hljs.CSS_NUMBER_MODE, + ...STRINGS, + // needed to highlight these as strings and to avoid issues with + // illegal characters that might be inside urls that would tigger the + // languages illegal stack + { + begin: /(url|data-uri)\(/, + end: /\)/, + relevance: 0, // from keywords + keywords: { + built_in: "url data-uri" + }, + contains: [ + { + className: "string", + // any character other than `)` as in `url()` will be the start + // of a string, which ends with `)` (from the parent mode) + begin: /[^)]/, + endsWithParent: true, + excludeEnd: true + } + ] + }, + FUNCTION_DISPATCH + ] + }, + { + begin: lookahead(/@/), + end: '[{;]', + relevance: 0, + illegal: /:/, // break on Less variables @var: ... + contains: [ + { + className: 'keyword', + begin: AT_PROPERTY_RE + }, + { + begin: /\s/, + endsWithParent: true, + excludeEnd: true, + relevance: 0, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ + { + begin: /[a-z-]+(?=:)/, + className: "attribute" + }, + ...STRINGS, + hljs.CSS_NUMBER_MODE + ] + } + ] + }, + { + className: 'selector-tag', + begin: '\\b(' + TAGS.join('|') + ')\\b' + } + ] + }; +} + +module.exports = css; + + +/***/ }), + +/***/ 1782: +/***/ ((module) => { + +/* +Language: D +Author: Aleksandar Ruzicic +Description: D is a language with C-like syntax and static typing. It pragmatically combines efficiency, control, and modeling power, with safety and programmer productivity. +Version: 1.0a +Website: https://dlang.org +Date: 2012-04-08 +*/ + +/** + * Known issues: + * + * - invalid hex string literals will be recognized as a double quoted strings + * but 'x' at the beginning of string will not be matched + * + * - delimited string literals are not checked for matching end delimiter + * (not possible to do with js regexp) + * + * - content of token string is colored as a string (i.e. no keyword coloring inside a token string) + * also, content of token string is not validated to contain only valid D tokens + * + * - special token sequence rule is not strictly following D grammar (anything following #line + * up to the end of line is matched as special token sequence) + */ + +/** @type LanguageFn */ +function d(hljs) { + /** + * Language keywords + * + * @type {Object} + */ + const D_KEYWORDS = { + $pattern: hljs.UNDERSCORE_IDENT_RE, + keyword: + 'abstract alias align asm assert auto body break byte case cast catch class ' + + 'const continue debug default delete deprecated do else enum export extern final ' + + 'finally for foreach foreach_reverse|10 goto if immutable import in inout int ' + + 'interface invariant is lazy macro mixin module new nothrow out override package ' + + 'pragma private protected public pure ref return scope shared static struct ' + + 'super switch synchronized template this throw try typedef typeid typeof union ' + + 'unittest version void volatile while with __FILE__ __LINE__ __gshared|10 ' + + '__thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__', + built_in: + 'bool cdouble cent cfloat char creal dchar delegate double dstring float function ' + + 'idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar ' + + 'wstring', + literal: + 'false null true' + }; + + /** + * Number literal regexps + * + * @type {String} + */ + const decimal_integer_re = '(0|[1-9][\\d_]*)'; + const decimal_integer_nosus_re = '(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)'; + const binary_integer_re = '0[bB][01_]+'; + const hexadecimal_digits_re = '([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)'; + const hexadecimal_integer_re = '0[xX]' + hexadecimal_digits_re; + + const decimal_exponent_re = '([eE][+-]?' + decimal_integer_nosus_re + ')'; + const decimal_float_re = '(' + decimal_integer_nosus_re + '(\\.\\d*|' + decimal_exponent_re + ')|' + + '\\d+\\.' + decimal_integer_nosus_re + '|' + + '\\.' + decimal_integer_re + decimal_exponent_re + '?' + + ')'; + const hexadecimal_float_re = '(0[xX](' + + hexadecimal_digits_re + '\\.' + hexadecimal_digits_re + '|' + + '\\.?' + hexadecimal_digits_re + + ')[pP][+-]?' + decimal_integer_nosus_re + ')'; + + const integer_re = '(' + + decimal_integer_re + '|' + + binary_integer_re + '|' + + hexadecimal_integer_re + + ')'; + + const float_re = '(' + + hexadecimal_float_re + '|' + + decimal_float_re + + ')'; + + /** + * Escape sequence supported in D string and character literals + * + * @type {String} + */ + const escape_sequence_re = '\\\\(' + + '[\'"\\?\\\\abfnrtv]|' + // common escapes + 'u[\\dA-Fa-f]{4}|' + // four hex digit unicode codepoint + '[0-7]{1,3}|' + // one to three octal digit ascii char code + 'x[\\dA-Fa-f]{2}|' + // two hex digit ascii char code + 'U[\\dA-Fa-f]{8}' + // eight hex digit unicode codepoint + ')|' + + '&[a-zA-Z\\d]{2,};'; // named character entity + + /** + * D integer number literals + * + * @type {Object} + */ + const D_INTEGER_MODE = { + className: 'number', + begin: '\\b' + integer_re + '(L|u|U|Lu|LU|uL|UL)?', + relevance: 0 + }; + + /** + * [D_FLOAT_MODE description] + * @type {Object} + */ + const D_FLOAT_MODE = { + className: 'number', + begin: '\\b(' + + float_re + '([fF]|L|i|[fF]i|Li)?|' + + integer_re + '(i|[fF]i|Li)' + + ')', + relevance: 0 + }; + + /** + * D character literal + * + * @type {Object} + */ + const D_CHARACTER_MODE = { + className: 'string', + begin: '\'(' + escape_sequence_re + '|.)', + end: '\'', + illegal: '.' + }; + + /** + * D string escape sequence + * + * @type {Object} + */ + const D_ESCAPE_SEQUENCE = { + begin: escape_sequence_re, + relevance: 0 + }; + + /** + * D double quoted string literal + * + * @type {Object} + */ + const D_STRING_MODE = { + className: 'string', + begin: '"', + contains: [D_ESCAPE_SEQUENCE], + end: '"[cwd]?' + }; + + /** + * D wysiwyg and delimited string literals + * + * @type {Object} + */ + const D_WYSIWYG_DELIMITED_STRING_MODE = { + className: 'string', + begin: '[rq]"', + end: '"[cwd]?', + relevance: 5 + }; + + /** + * D alternate wysiwyg string literal + * + * @type {Object} + */ + const D_ALTERNATE_WYSIWYG_STRING_MODE = { + className: 'string', + begin: '`', + end: '`[cwd]?' + }; + + /** + * D hexadecimal string literal + * + * @type {Object} + */ + const D_HEX_STRING_MODE = { + className: 'string', + begin: 'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?', + relevance: 10 + }; + + /** + * D delimited string literal + * + * @type {Object} + */ + const D_TOKEN_STRING_MODE = { + className: 'string', + begin: 'q"\\{', + end: '\\}"' + }; + + /** + * Hashbang support + * + * @type {Object} + */ + const D_HASHBANG_MODE = { + className: 'meta', + begin: '^#!', + end: '$', + relevance: 5 + }; + + /** + * D special token sequence + * + * @type {Object} + */ + const D_SPECIAL_TOKEN_SEQUENCE_MODE = { + className: 'meta', + begin: '#(line)', + end: '$', + relevance: 5 + }; + + /** + * D attributes + * + * @type {Object} + */ + const D_ATTRIBUTE_MODE = { + className: 'keyword', + begin: '@[a-zA-Z_][a-zA-Z_\\d]*' + }; + + /** + * D nesting comment + * + * @type {Object} + */ + const D_NESTING_COMMENT_MODE = hljs.COMMENT( + '\\/\\+', + '\\+\\/', + { + contains: ['self'], + relevance: 10 + } + ); + + return { + name: 'D', + keywords: D_KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + D_NESTING_COMMENT_MODE, + D_HEX_STRING_MODE, + D_STRING_MODE, + D_WYSIWYG_DELIMITED_STRING_MODE, + D_ALTERNATE_WYSIWYG_STRING_MODE, + D_TOKEN_STRING_MODE, + D_FLOAT_MODE, + D_INTEGER_MODE, + D_CHARACTER_MODE, + D_HASHBANG_MODE, + D_SPECIAL_TOKEN_SEQUENCE_MODE, + D_ATTRIBUTE_MODE + ] + }; +} + +module.exports = d; + + +/***/ }), + +/***/ 5732: +/***/ ((module) => { + +/* +Language: Delphi +Website: https://www.embarcadero.com/products/delphi +*/ + +/** @type LanguageFn */ +function delphi(hljs) { + const KEYWORDS = + 'exports register file shl array record property for mod while set ally label uses raise not ' + + 'stored class safecall var interface or private static exit index inherited to else stdcall ' + + 'override shr asm far resourcestring finalization packed virtual out and protected library do ' + + 'xorwrite goto near function end div overload object unit begin string on inline repeat until ' + + 'destructor write message program with read initialization except default nil if case cdecl in ' + + 'downto threadvar of try pascal const external constructor type public then implementation ' + + 'finally published procedure absolute reintroduce operator as is abstract alias assembler ' + + 'bitpacked break continue cppdecl cvar enumerator experimental platform deprecated ' + + 'unimplemented dynamic export far16 forward generic helper implements interrupt iochecks ' + + 'local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat ' + + 'specialize strict unaligned varargs '; + const COMMENT_MODES = [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT(/\{/, /\}/, { + relevance: 0 + }), + hljs.COMMENT(/\(\*/, /\*\)/, { + relevance: 10 + }) + ]; + const DIRECTIVE = { + className: 'meta', + variants: [ + { + begin: /\{\$/, + end: /\}/ + }, + { + begin: /\(\*\$/, + end: /\*\)/ + } + ] + }; + const STRING = { + className: 'string', + begin: /'/, + end: /'/, + contains: [{ + begin: /''/ + }] + }; + const NUMBER = { + className: 'number', + relevance: 0, + // Source: https://www.freepascal.org/docs-html/ref/refse6.html + variants: [ + { + // Hexadecimal notation, e.g., $7F. + begin: '\\$[0-9A-Fa-f]+' + }, + { + // Octal notation, e.g., &42. + begin: '&[0-7]+' + }, + { + // Binary notation, e.g., %1010. + begin: '%[01]+' + } + ] + }; + const CHAR_STRING = { + className: 'string', + begin: /(#\d+)+/ + }; + const CLASS = { + begin: hljs.IDENT_RE + '\\s*=\\s*class\\s*\\(', + returnBegin: true, + contains: [hljs.TITLE_MODE] + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'function constructor destructor procedure', + end: /[:;]/, + keywords: 'function constructor|10 destructor|10 procedure|10', + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ + STRING, + CHAR_STRING, + DIRECTIVE + ].concat(COMMENT_MODES) + }, + DIRECTIVE + ].concat(COMMENT_MODES) + }; + return { + name: 'Delphi', + aliases: [ + 'dpr', + 'dfm', + 'pas', + 'pascal', + 'freepascal', + 'lazarus', + 'lpr', + 'lfm' + ], + case_insensitive: true, + keywords: KEYWORDS, + illegal: /"|\$[G-Zg-z]|\/\*|<\/|\|/, + contains: [ + STRING, + CHAR_STRING, + hljs.NUMBER_MODE, + NUMBER, + CLASS, + FUNCTION, + DIRECTIVE + ].concat(COMMENT_MODES) + }; +} + +module.exports = delphi; + + +/***/ }), + +/***/ 90775: +/***/ ((module) => { + +/* +Language: Diff +Description: Unified and context diff +Author: Vasily Polovnyov +Website: https://www.gnu.org/software/diffutils/ +Category: common +*/ + +/** @type LanguageFn */ +function diff(hljs) { + return { + name: 'Diff', + aliases: ['patch'], + contains: [ + { + className: 'meta', + relevance: 10, + variants: [ + { + begin: /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/ + }, + { + begin: /^\*\*\* +\d+,\d+ +\*\*\*\*$/ + }, + { + begin: /^--- +\d+,\d+ +----$/ + } + ] + }, + { + className: 'comment', + variants: [ + { + begin: /Index: /, + end: /$/ + }, + { + begin: /^index/, + end: /$/ + }, + { + begin: /={3,}/, + end: /$/ + }, + { + begin: /^-{3}/, + end: /$/ + }, + { + begin: /^\*{3} /, + end: /$/ + }, + { + begin: /^\+{3}/, + end: /$/ + }, + { + begin: /^\*{15}$/ + }, + { + begin: /^diff --git/, + end: /$/ + } + ] + }, + { + className: 'addition', + begin: /^\+/, + end: /$/ + }, + { + className: 'deletion', + begin: /^-/, + end: /$/ + }, + { + className: 'addition', + begin: /^!/, + end: /$/ + } + ] + }; +} + +module.exports = diff; + + +/***/ }), + +/***/ 46019: +/***/ ((module) => { + +/* +Language: Django +Description: Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. +Requires: xml.js +Author: Ivan Sagalaev +Contributors: Ilya Baryshev +Website: https://www.djangoproject.com +Category: template +*/ + +/** @type LanguageFn */ +function django(hljs) { + const FILTER = { + begin: /\|[A-Za-z]+:?/, + keywords: { + name: + 'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' + + 'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' + + 'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' + + 'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' + + 'dictsortreversed default_if_none pluralize lower join center default ' + + 'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' + + 'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' + + 'localtime utc timezone' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE + ] + }; + + return { + name: 'Django', + aliases: ['jinja'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + hljs.COMMENT(/\{%\s*comment\s*%\}/, /\{%\s*endcomment\s*%\}/), + hljs.COMMENT(/\{#/, /#\}/), + { + className: 'template-tag', + begin: /\{%/, + end: /%\}/, + contains: [{ + className: 'name', + begin: /\w+/, + keywords: { + name: + 'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' + + 'endfor ifnotequal endifnotequal widthratio extends include spaceless ' + + 'endspaceless regroup ifequal endifequal ssi now with cycle url filter ' + + 'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' + + 'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' + + 'plural get_current_language language get_available_languages ' + + 'get_current_language_bidi get_language_info get_language_info_list localize ' + + 'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' + + 'verbatim' + }, + starts: { + endsWithParent: true, + keywords: 'in by as', + contains: [FILTER], + relevance: 0 + } + }] + }, + { + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [FILTER] + } + ] + }; +} + +module.exports = django; + + +/***/ }), + +/***/ 86057: +/***/ ((module) => { + +/* +Language: DNS Zone +Author: Tim Schumacher +Category: config +Website: https://en.wikipedia.org/wiki/Zone_file +*/ + +/** @type LanguageFn */ +function dns(hljs) { + return { + name: 'DNS Zone', + aliases: [ + 'bind', + 'zone' + ], + keywords: { + keyword: + 'IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX ' + + 'LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT' + }, + contains: [ + hljs.COMMENT(';', '$', { + relevance: 0 + }), + { + className: 'meta', + begin: /^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/ + }, + // IPv6 + { + className: 'number', + begin: '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b' + }, + // IPv4 + { + className: 'number', + begin: '((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b' + }, + hljs.inherit(hljs.NUMBER_MODE, { + begin: /\b\d+[dhwm]?/ + }) + ] + }; +} + +module.exports = dns; + + +/***/ }), + +/***/ 1534: +/***/ ((module) => { + +/* +Language: Dockerfile +Requires: bash.js +Author: Alexis Hénaut +Description: language definition for Dockerfile files +Website: https://docs.docker.com/engine/reference/builder/ +Category: config +*/ + +/** @type LanguageFn */ +function dockerfile(hljs) { + return { + name: 'Dockerfile', + aliases: ['docker'], + case_insensitive: true, + keywords: 'from maintainer expose env arg user onbuild stopsignal', + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + { + beginKeywords: 'run cmd entrypoint volume add copy workdir label healthcheck shell', + starts: { + end: /[^\\]$/, + subLanguage: 'bash' + } + } + ], + illegal: ' { + +/* +Language: Batch file (DOS) +Author: Alexander Makarov +Contributors: Anton Kochkov +Website: https://en.wikipedia.org/wiki/Batch_file +*/ + +/** @type LanguageFn */ +function dos(hljs) { + const COMMENT = hljs.COMMENT( + /^\s*@?rem\b/, /$/, + { + relevance: 10 + } + ); + const LABEL = { + className: 'symbol', + begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)', + relevance: 0 + }; + return { + name: 'Batch file (DOS)', + aliases: [ + 'bat', + 'cmd' + ], + case_insensitive: true, + illegal: /\/\*/, + keywords: { + keyword: + 'if else goto for in do call exit not exist errorlevel defined ' + + 'equ neq lss leq gtr geq', + built_in: + 'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux ' + + 'shift cd dir echo setlocal endlocal set pause copy ' + + 'append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color ' + + 'comp compact convert date dir diskcomp diskcopy doskey erase fs ' + + 'find findstr format ftype graftabl help keyb label md mkdir mode more move path ' + + 'pause print popd pushd promt rd recover rem rename replace restore rmdir shift ' + + 'sort start subst time title tree type ver verify vol ' + + // winutils + 'ping net ipconfig taskkill xcopy ren del' + }, + contains: [ + { + className: 'variable', + begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/ + }, + { + className: 'function', + begin: LABEL.begin, + end: 'goto:eof', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*' + }), + COMMENT + ] + }, + { + className: 'number', + begin: '\\b\\d+', + relevance: 0 + }, + COMMENT + ] + }; +} + +module.exports = dos; + + +/***/ }), + +/***/ 15259: +/***/ ((module) => { + +/* + Language: dsconfig + Description: dsconfig batch configuration language for LDAP directory servers + Contributors: Jacob Childress + Category: enterprise, config + */ + + /** @type LanguageFn */ +function dsconfig(hljs) { + const QUOTED_PROPERTY = { + className: 'string', + begin: /"/, + end: /"/ + }; + const APOS_PROPERTY = { + className: 'string', + begin: /'/, + end: /'/ + }; + const UNQUOTED_PROPERTY = { + className: 'string', + begin: /[\w\-?]+:\w+/, + end: /\W/, + relevance: 0 + }; + const VALUELESS_PROPERTY = { + className: 'string', + begin: /\w+(\-\w+)*/, + end: /(?=\W)/, + relevance: 0 + }; + + return { + keywords: 'dsconfig', + contains: [ + { + className: 'keyword', + begin: '^dsconfig', + end: /\s/, + excludeEnd: true, + relevance: 10 + }, + { + className: 'built_in', + begin: /(list|create|get|set|delete)-(\w+)/, + end: /\s/, + excludeEnd: true, + illegal: '!@#$%^&*()', + relevance: 10 + }, + { + className: 'built_in', + begin: /--(\w+)/, + end: /\s/, + excludeEnd: true + }, + QUOTED_PROPERTY, + APOS_PROPERTY, + UNQUOTED_PROPERTY, + VALUELESS_PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = dsconfig; + + +/***/ }), + +/***/ 43991: +/***/ ((module) => { + +/* +Language: Device Tree +Description: *.dts files used in the Linux kernel +Author: Martin Braun , Moritz Fischer +Website: https://elinux.org/Device_Tree_Reference +Category: config +*/ + +/** @type LanguageFn */ +function dts(hljs) { + const STRINGS = { + className: 'string', + variants: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, { + begin: '((u8?|U)|L)?"' + }), + { + begin: '(u8?|U)?R"', + end: '"', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: '\'\\\\?.', + end: '\'', + illegal: '.' + } + ] + }; + + const NUMBERS = { + className: 'number', + variants: [ + { + begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)' + }, + { + begin: hljs.C_NUMBER_RE + } + ], + relevance: 0 + }; + + const PREPROCESSOR = { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'if else elif endif define undef ifdef ifndef' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + { + beginKeywords: 'include', + end: '$', + keywords: { + 'meta-keyword': 'include' + }, + contains: [ + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: '<', + end: '>', + illegal: '\\n' + } + ] + }, + STRINGS, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + const DTS_REFERENCE = { + className: 'variable', + begin: /&[a-z\d_]*\b/ + }; + + const DTS_KEYWORD = { + className: 'meta-keyword', + begin: '/[a-z][a-z\\d-]*/' + }; + + const DTS_LABEL = { + className: 'symbol', + begin: '^\\s*[a-zA-Z_][a-zA-Z\\d_]*:' + }; + + const DTS_CELL_PROPERTY = { + className: 'params', + begin: '<', + end: '>', + contains: [ + NUMBERS, + DTS_REFERENCE + ] + }; + + const DTS_NODE = { + className: 'class', + begin: /[a-zA-Z_][a-zA-Z\d_@]*\s\{/, + end: /[{;=]/, + returnBegin: true, + excludeEnd: true + }; + + const DTS_ROOT_NODE = { + className: 'class', + begin: '/\\s*\\{', + end: /\};/, + relevance: 10, + contains: [ + DTS_REFERENCE, + DTS_KEYWORD, + DTS_LABEL, + DTS_NODE, + DTS_CELL_PROPERTY, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS + ] + }; + + return { + name: 'Device Tree', + keywords: "", + contains: [ + DTS_ROOT_NODE, + DTS_REFERENCE, + DTS_KEYWORD, + DTS_LABEL, + DTS_NODE, + DTS_CELL_PROPERTY, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS, + PREPROCESSOR, + { + begin: hljs.IDENT_RE + '::', + keywords: "" + } + ] + }; +} + +module.exports = dts; + + +/***/ }), + +/***/ 32188: +/***/ ((module) => { + +/* +Language: Dust +Requires: xml.js +Author: Michael Allen +Description: Matcher for dust.js templates. +Website: https://www.dustjs.com +Category: template +*/ + +/** @type LanguageFn */ +function dust(hljs) { + const EXPRESSION_KEYWORDS = 'if eq ne lt lte gt gte select default math sep'; + return { + name: 'Dust', + aliases: ['dst'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + { + className: 'template-tag', + begin: /\{[#\/]/, + end: /\}/, + illegal: /;/, + contains: [{ + className: 'name', + begin: /[a-zA-Z\.-]+/, + starts: { + endsWithParent: true, + relevance: 0, + contains: [hljs.QUOTE_STRING_MODE] + } + }] + }, + { + className: 'template-variable', + begin: /\{/, + end: /\}/, + illegal: /;/, + keywords: EXPRESSION_KEYWORDS + } + ] + }; +} + +module.exports = dust; + + +/***/ }), + +/***/ 35603: +/***/ ((module) => { + +/* +Language: Extended Backus-Naur Form +Author: Alex McKibben +Website: https://en.wikipedia.org/wiki/Extended_Backus–Naur_form +*/ + +/** @type LanguageFn */ +function ebnf(hljs) { + const commentMode = hljs.COMMENT(/\(\*/, /\*\)/); + + const nonTerminalMode = { + className: "attribute", + begin: /^[ ]*[a-zA-Z]+([\s_-]+[a-zA-Z]+)*/ + }; + + const specialSequenceMode = { + className: "meta", + begin: /\?.*\?/ + }; + + const ruleBodyMode = { + begin: /=/, + end: /[.;]/, + contains: [ + commentMode, + specialSequenceMode, + { + // terminals + className: 'string', + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '`', + end: '`' + } + ] + } + ] + }; + + return { + name: 'Extended Backus-Naur Form', + illegal: /\S/, + contains: [ + commentMode, + nonTerminalMode, + ruleBodyMode + ] + }; +} + +module.exports = ebnf; + + +/***/ }), + +/***/ 61755: +/***/ ((module) => { + +/* +Language: Elixir +Author: Josh Adams +Description: language definition for Elixir source code files (.ex and .exs). Based on ruby language support. +Category: functional +Website: https://elixir-lang.org +*/ + +/** @type LanguageFn */ +function elixir(hljs) { + const ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(!|\\?)?'; + const ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?'; + const ELIXIR_KEYWORDS = { + $pattern: ELIXIR_IDENT_RE, + keyword: 'and false then defined module in return redo retry end for true self when ' + + 'next until do begin unless nil break not case cond alias while ensure or ' + + 'include use alias fn quote require import with|0' + }; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: ELIXIR_KEYWORDS + }; + const NUMBER = { + className: 'number', + begin: '(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[1-9][0-9_]*(\\.[0-9_]+([eE][-+]?[0-9]+)?)?)', + relevance: 0 + }; + const SIGIL_DELIMITERS = '[/|([{<"\']'; + const LOWERCASE_SIGIL = { + className: 'string', + begin: '~[a-z]' + '(?=' + SIGIL_DELIMITERS + ')', + contains: [ + { + endsParent: true, + contains: [ + { + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /\//, + end: /\// + }, + { + begin: /\|/, + end: /\|/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + }, + { + begin: /\{/, + end: /\}/ + }, + { + begin: // + } + ] + } + ] + } + ] + }; + + const UPCASE_SIGIL = { + className: 'string', + begin: '~[A-Z]' + '(?=' + SIGIL_DELIMITERS + ')', + contains: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /\//, + end: /\// + }, + { + begin: /\|/, + end: /\|/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + }, + { + begin: /\{/, + end: /\}/ + }, + { + begin: // + } + ] + }; + + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: /"""/, + end: /"""/ + }, + { + begin: /'''/, + end: /'''/ + }, + { + begin: /~S"""/, + end: /"""/, + contains: [] // override default + }, + { + begin: /~S"/, + end: /"/, + contains: [] // override default + }, + { + begin: /~S'''/, + end: /'''/, + contains: [] // override default + }, + { + begin: /~S'/, + end: /'/, + contains: [] // override default + }, + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + } + ] + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'def defp defmacro', + end: /\B\b/, // the mode is ended by the title + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: ELIXIR_IDENT_RE, + endsParent: true + }) + ] + }; + const CLASS = hljs.inherit(FUNCTION, { + className: 'class', + beginKeywords: 'defimpl defmodule defprotocol defrecord', + end: /\bdo\b|$|;/ + }); + const ELIXIR_DEFAULT_CONTAINS = [ + STRING, + UPCASE_SIGIL, + LOWERCASE_SIGIL, + hljs.HASH_COMMENT_MODE, + CLASS, + FUNCTION, + { + begin: '::' + }, + { + className: 'symbol', + begin: ':(?![\\s:])', + contains: [ + STRING, + { + begin: ELIXIR_METHOD_RE + } + ], + relevance: 0 + }, + { + className: 'symbol', + begin: ELIXIR_IDENT_RE + ':(?!:)', + relevance: 0 + }, + NUMBER, + { + className: 'variable', + begin: '(\\$\\W)|((\\$|@@?)(\\w+))' + }, + { + begin: '->' + }, + { // regexp container + begin: '(' + hljs.RE_STARTERS_RE + ')\\s*', + contains: [ + hljs.HASH_COMMENT_MODE, + { + // to prevent false regex triggers for the division function: + // /: + begin: /\/: (?=\d+\s*[,\]])/, + relevance: 0, + contains: [NUMBER] + }, + { + className: 'regexp', + illegal: '\\n', + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ], + variants: [ + { + begin: '/', + end: '/[a-z]*' + }, + { + begin: '%r\\[', + end: '\\][a-z]*' + } + ] + } + ], + relevance: 0 + } + ]; + SUBST.contains = ELIXIR_DEFAULT_CONTAINS; + + return { + name: 'Elixir', + keywords: ELIXIR_KEYWORDS, + contains: ELIXIR_DEFAULT_CONTAINS + }; +} + +module.exports = elixir; + + +/***/ }), + +/***/ 79046: +/***/ ((module) => { + +/* +Language: Elm +Author: Janis Voigtlaender +Website: https://elm-lang.org +Category: functional +*/ + +/** @type LanguageFn */ +function elm(hljs) { + const COMMENT = { + variants: [ + hljs.COMMENT('--', '$'), + hljs.COMMENT( + /\{-/, + /-\}/, + { + contains: ['self'] + } + ) + ] + }; + + const CONSTRUCTOR = { + className: 'type', + begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (built-in, infix). + relevance: 0 + }; + + const LIST = { + begin: '\\(', + end: '\\)', + illegal: '"', + contains: [ + { + className: 'type', + begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?' + }, + COMMENT + ] + }; + + const RECORD = { + begin: /\{/, + end: /\}/, + contains: LIST.contains + }; + + const CHARACTER = { + className: 'string', + begin: '\'\\\\?.', + end: '\'', + illegal: '.' + }; + + return { + name: 'Elm', + keywords: + 'let in if then else case of where module import exposing ' + + 'type alias as infix infixl infixr port effect command subscription', + contains: [ + + // Top-level constructions. + + { + beginKeywords: 'port effect module', + end: 'exposing', + keywords: 'port effect module where command subscription exposing', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: 'import', + end: '$', + keywords: 'import as exposing', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: 'type', + end: '$', + keywords: 'type alias', + contains: [ + CONSTRUCTOR, + LIST, + RECORD, + COMMENT + ] + }, + { + beginKeywords: 'infix infixl infixr', + end: '$', + contains: [ + hljs.C_NUMBER_MODE, + COMMENT + ] + }, + { + begin: 'port', + end: '$', + keywords: 'port', + contains: [COMMENT] + }, + + // Literals and names. + + CHARACTER, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + CONSTRUCTOR, + hljs.inherit(hljs.TITLE_MODE, { + begin: '^[_a-z][\\w\']*' + }), + COMMENT, + + { + begin: '->|<-' + } // No markup, relevance booster + ], + illegal: /;/ + }; +} + +module.exports = elm; + + +/***/ }), + +/***/ 36193: +/***/ ((module) => { + +/* +Language: ERB (Embedded Ruby) +Requires: xml.js, ruby.js +Author: Lucas Mazza +Contributors: Kassio Borges +Description: "Bridge" language defining fragments of Ruby in HTML within <% .. %> +Website: https://ruby-doc.org/stdlib-2.6.5/libdoc/erb/rdoc/ERB.html +Category: template +*/ + +/** @type LanguageFn */ +function erb(hljs) { + return { + name: 'ERB', + subLanguage: 'xml', + contains: [ + hljs.COMMENT('<%#', '%>'), + { + begin: '<%[%=-]?', + end: '[%-]?%>', + subLanguage: 'ruby', + excludeBegin: true, + excludeEnd: true + } + ] + }; +} + +module.exports = erb; + + +/***/ }), + +/***/ 37497: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Erlang REPL +Author: Sergey Ignatov +Website: https://www.erlang.org +Category: functional +*/ + +/** @type LanguageFn */ +function erlangRepl(hljs) { + return { + name: 'Erlang REPL', + keywords: { + built_in: + 'spawn spawn_link self', + keyword: + 'after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if ' + + 'let not of or orelse|10 query receive rem try when xor' + }, + contains: [ + { + className: 'meta', + begin: '^[0-9]+> ', + relevance: 10 + }, + hljs.COMMENT('%', '$'), + { + className: 'number', + begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)', + relevance: 0 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: concat( + /\?(::)?/, + /([A-Z]\w*)/, // at least one identifier + /((::)[A-Z]\w*)*/ // perhaps more + ) + }, + { + begin: '->' + }, + { + begin: 'ok' + }, + { + begin: '!' + }, + { + begin: '(\\b[a-z\'][a-zA-Z0-9_\']*:[a-z\'][a-zA-Z0-9_\']*)|(\\b[a-z\'][a-zA-Z0-9_\']*)', + relevance: 0 + }, + { + begin: '[A-Z][a-zA-Z0-9_\']*', + relevance: 0 + } + ] + }; +} + +module.exports = erlangRepl; + + +/***/ }), + +/***/ 89843: +/***/ ((module) => { + +/* +Language: Erlang +Description: Erlang is a general-purpose functional language, with strict evaluation, single assignment, and dynamic typing. +Author: Nikolay Zakharov , Dmitry Kovega +Website: https://www.erlang.org +Category: functional +*/ + +/** @type LanguageFn */ +function erlang(hljs) { + const BASIC_ATOM_RE = '[a-z\'][a-zA-Z0-9_\']*'; + const FUNCTION_NAME_RE = '(' + BASIC_ATOM_RE + ':' + BASIC_ATOM_RE + '|' + BASIC_ATOM_RE + ')'; + const ERLANG_RESERVED = { + keyword: + 'after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if ' + + 'let not of orelse|10 query receive rem try when xor', + literal: + 'false true' + }; + + const COMMENT = hljs.COMMENT('%', '$'); + const NUMBER = { + className: 'number', + begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)', + relevance: 0 + }; + const NAMED_FUN = { + begin: 'fun\\s+' + BASIC_ATOM_RE + '/\\d+' + }; + const FUNCTION_CALL = { + begin: FUNCTION_NAME_RE + '\\(', + end: '\\)', + returnBegin: true, + relevance: 0, + contains: [ + { + begin: FUNCTION_NAME_RE, + relevance: 0 + }, + { + begin: '\\(', + end: '\\)', + endsWithParent: true, + returnEnd: true, + relevance: 0 + // "contains" defined later + } + ] + }; + const TUPLE = { + begin: /\{/, + end: /\}/, + relevance: 0 + // "contains" defined later + }; + const VAR1 = { + begin: '\\b_([A-Z][A-Za-z0-9_]*)?', + relevance: 0 + }; + const VAR2 = { + begin: '[A-Z][a-zA-Z0-9_]*', + relevance: 0 + }; + const RECORD_ACCESS = { + begin: '#' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0, + returnBegin: true, + contains: [ + { + begin: '#' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }, + { + begin: /\{/, + end: /\}/, + relevance: 0 + // "contains" defined later + } + ] + }; + + const BLOCK_STATEMENTS = { + beginKeywords: 'fun receive if try case', + end: 'end', + keywords: ERLANG_RESERVED + }; + BLOCK_STATEMENTS.contains = [ + COMMENT, + NAMED_FUN, + hljs.inherit(hljs.APOS_STRING_MODE, { + className: '' + }), + BLOCK_STATEMENTS, + FUNCTION_CALL, + hljs.QUOTE_STRING_MODE, + NUMBER, + TUPLE, + VAR1, + VAR2, + RECORD_ACCESS + ]; + + const BASIC_MODES = [ + COMMENT, + NAMED_FUN, + BLOCK_STATEMENTS, + FUNCTION_CALL, + hljs.QUOTE_STRING_MODE, + NUMBER, + TUPLE, + VAR1, + VAR2, + RECORD_ACCESS + ]; + FUNCTION_CALL.contains[1].contains = BASIC_MODES; + TUPLE.contains = BASIC_MODES; + RECORD_ACCESS.contains[1].contains = BASIC_MODES; + + const DIRECTIVES = [ + "-module", + "-record", + "-undef", + "-export", + "-ifdef", + "-ifndef", + "-author", + "-copyright", + "-doc", + "-vsn", + "-import", + "-include", + "-include_lib", + "-compile", + "-define", + "-else", + "-endif", + "-file", + "-behaviour", + "-behavior", + "-spec" + ]; + + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)', + contains: BASIC_MODES + }; + return { + name: 'Erlang', + aliases: ['erl'], + keywords: ERLANG_RESERVED, + illegal: '(', + returnBegin: true, + illegal: '\\(|#|//|/\\*|\\\\|:|;', + contains: [ + PARAMS, + hljs.inherit(hljs.TITLE_MODE, { + begin: BASIC_ATOM_RE + }) + ], + starts: { + end: ';|\\.', + keywords: ERLANG_RESERVED, + contains: BASIC_MODES + } + }, + COMMENT, + { + begin: '^-', + end: '\\.', + relevance: 0, + excludeEnd: true, + returnBegin: true, + keywords: { + $pattern: '-' + hljs.IDENT_RE, + keyword: DIRECTIVES.map(x => `${x}|1.5`).join(" ") + }, + contains: [PARAMS] + }, + NUMBER, + hljs.QUOTE_STRING_MODE, + RECORD_ACCESS, + VAR1, + VAR2, + TUPLE, + { + begin: /\.$/ + } // relevance booster + ] + }; +} + +module.exports = erlang; + + +/***/ }), + +/***/ 8553: +/***/ ((module) => { + +/* +Language: Excel formulae +Author: Victor Zhou +Description: Excel formulae +Website: https://products.office.com/en-us/excel/ +*/ + +/** @type LanguageFn */ +function excel(hljs) { + return { + name: 'Excel formulae', + aliases: [ + 'xlsx', + 'xls' + ], + case_insensitive: true, + // built-in functions imported from https://web.archive.org/web/20160513042710/https://support.office.com/en-us/article/Excel-functions-alphabetical-b3944572-255d-4efb-bb96-c6d90033e188 + keywords: { + $pattern: /[a-zA-Z][\w\.]*/, + built_in: 'ABS ACCRINT ACCRINTM ACOS ACOSH ACOT ACOTH AGGREGATE ADDRESS AMORDEGRC AMORLINC AND ARABIC AREAS ASC ASIN ASINH ATAN ATAN2 ATANH AVEDEV AVERAGE AVERAGEA AVERAGEIF AVERAGEIFS BAHTTEXT BASE BESSELI BESSELJ BESSELK BESSELY BETADIST BETA.DIST BETAINV BETA.INV BIN2DEC BIN2HEX BIN2OCT BINOMDIST BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CALL CEILING CEILING.MATH CEILING.PRECISE CELL CHAR CHIDIST CHIINV CHITEST CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSE CLEAN CODE COLUMN COLUMNS COMBIN COMBINA COMPLEX CONCAT CONCATENATE CONFIDENCE CONFIDENCE.NORM CONFIDENCE.T CONVERT CORREL COS COSH COT COTH COUNT COUNTA COUNTBLANK COUNTIF COUNTIFS COUPDAYBS COUPDAYS COUPDAYSNC COUPNCD COUPNUM COUPPCD COVAR COVARIANCE.P COVARIANCE.S CRITBINOM CSC CSCH CUBEKPIMEMBER CUBEMEMBER CUBEMEMBERPROPERTY CUBERANKEDMEMBER CUBESET CUBESETCOUNT CUBEVALUE CUMIPMT CUMPRINC DATE DATEDIF DATEVALUE DAVERAGE DAY DAYS DAYS360 DB DBCS DCOUNT DCOUNTA DDB DEC2BIN DEC2HEX DEC2OCT DECIMAL DEGREES DELTA DEVSQ DGET DISC DMAX DMIN DOLLAR DOLLARDE DOLLARFR DPRODUCT DSTDEV DSTDEVP DSUM DURATION DVAR DVARP EDATE EFFECT ENCODEURL EOMONTH ERF ERF.PRECISE ERFC ERFC.PRECISE ERROR.TYPE EUROCONVERT EVEN EXACT EXP EXPON.DIST EXPONDIST FACT FACTDOUBLE FALSE|0 F.DIST FDIST F.DIST.RT FILTERXML FIND FINDB F.INV F.INV.RT FINV FISHER FISHERINV FIXED FLOOR FLOOR.MATH FLOOR.PRECISE FORECAST FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT FREQUENCY F.TEST FTEST FV FVSCHEDULE GAMMA GAMMA.DIST GAMMADIST GAMMA.INV GAMMAINV GAMMALN GAMMALN.PRECISE GAUSS GCD GEOMEAN GESTEP GETPIVOTDATA GROWTH HARMEAN HEX2BIN HEX2DEC HEX2OCT HLOOKUP HOUR HYPERLINK HYPGEOM.DIST HYPGEOMDIST IF IFERROR IFNA IFS IMABS IMAGINARY IMARGUMENT IMCONJUGATE IMCOS IMCOSH IMCOT IMCSC IMCSCH IMDIV IMEXP IMLN IMLOG10 IMLOG2 IMPOWER IMPRODUCT IMREAL IMSEC IMSECH IMSIN IMSINH IMSQRT IMSUB IMSUM IMTAN INDEX INDIRECT INFO INT INTERCEPT INTRATE IPMT IRR ISBLANK ISERR ISERROR ISEVEN ISFORMULA ISLOGICAL ISNA ISNONTEXT ISNUMBER ISODD ISREF ISTEXT ISO.CEILING ISOWEEKNUM ISPMT JIS KURT LARGE LCM LEFT LEFTB LEN LENB LINEST LN LOG LOG10 LOGEST LOGINV LOGNORM.DIST LOGNORMDIST LOGNORM.INV LOOKUP LOWER MATCH MAX MAXA MAXIFS MDETERM MDURATION MEDIAN MID MIDBs MIN MINIFS MINA MINUTE MINVERSE MIRR MMULT MOD MODE MODE.MULT MODE.SNGL MONTH MROUND MULTINOMIAL MUNIT N NA NEGBINOM.DIST NEGBINOMDIST NETWORKDAYS NETWORKDAYS.INTL NOMINAL NORM.DIST NORMDIST NORMINV NORM.INV NORM.S.DIST NORMSDIST NORM.S.INV NORMSINV NOT NOW NPER NPV NUMBERVALUE OCT2BIN OCT2DEC OCT2HEX ODD ODDFPRICE ODDFYIELD ODDLPRICE ODDLYIELD OFFSET OR PDURATION PEARSON PERCENTILE.EXC PERCENTILE.INC PERCENTILE PERCENTRANK.EXC PERCENTRANK.INC PERCENTRANK PERMUT PERMUTATIONA PHI PHONETIC PI PMT POISSON.DIST POISSON POWER PPMT PRICE PRICEDISC PRICEMAT PROB PRODUCT PROPER PV QUARTILE QUARTILE.EXC QUARTILE.INC QUOTIENT RADIANS RAND RANDBETWEEN RANK.AVG RANK.EQ RANK RATE RECEIVED REGISTER.ID REPLACE REPLACEB REPT RIGHT RIGHTB ROMAN ROUND ROUNDDOWN ROUNDUP ROW ROWS RRI RSQ RTD SEARCH SEARCHB SEC SECH SECOND SERIESSUM SHEET SHEETS SIGN SIN SINH SKEW SKEW.P SLN SLOPE SMALL SQL.REQUEST SQRT SQRTPI STANDARDIZE STDEV STDEV.P STDEV.S STDEVA STDEVP STDEVPA STEYX SUBSTITUTE SUBTOTAL SUM SUMIF SUMIFS SUMPRODUCT SUMSQ SUMX2MY2 SUMX2PY2 SUMXMY2 SWITCH SYD T TAN TANH TBILLEQ TBILLPRICE TBILLYIELD T.DIST T.DIST.2T T.DIST.RT TDIST TEXT TEXTJOIN TIME TIMEVALUE T.INV T.INV.2T TINV TODAY TRANSPOSE TREND TRIM TRIMMEAN TRUE|0 TRUNC T.TEST TTEST TYPE UNICHAR UNICODE UPPER VALUE VAR VAR.P VAR.S VARA VARP VARPA VDB VLOOKUP WEBSERVICE WEEKDAY WEEKNUM WEIBULL WEIBULL.DIST WORKDAY WORKDAY.INTL XIRR XNPV XOR YEAR YEARFRAC YIELD YIELDDISC YIELDMAT Z.TEST ZTEST' + }, + contains: [ + { + /* matches a beginning equal sign found in Excel formula examples */ + begin: /^=/, + end: /[^=]/, + returnEnd: true, + illegal: /=/, /* only allow single equal sign at front of line */ + relevance: 10 + }, + /* technically, there can be more than 2 letters in column names, but this prevents conflict with some keywords */ + { + /* matches a reference to a single cell */ + className: 'symbol', + begin: /\b[A-Z]{1,2}\d+\b/, + end: /[^\d]/, + excludeEnd: true, + relevance: 0 + }, + { + /* matches a reference to a range of cells */ + className: 'symbol', + begin: /[A-Z]{0,2}\d*:[A-Z]{0,2}\d*/, + relevance: 0 + }, + hljs.BACKSLASH_ESCAPE, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + begin: hljs.NUMBER_RE + '(%)?', + relevance: 0 + }, + /* Excel formula comments are done by putting the comment in a function call to N() */ + hljs.COMMENT(/\bN\(/, /\)/, + { + excludeBegin: true, + excludeEnd: true, + illegal: /\n/ + }) + ] + }; +} + +module.exports = excel; + + +/***/ }), + +/***/ 56137: +/***/ ((module) => { + +/* +Language: FIX +Author: Brent Bradbury +*/ + +/** @type LanguageFn */ +function fix(hljs) { + return { + name: 'FIX', + contains: [{ + begin: /[^\u2401\u0001]+/, + end: /[\u2401\u0001]/, + excludeEnd: true, + returnBegin: true, + returnEnd: false, + contains: [ + { + begin: /([^\u2401\u0001=]+)/, + end: /=([^\u2401\u0001=]+)/, + returnEnd: true, + returnBegin: false, + className: 'attr' + }, + { + begin: /=/, + end: /([\u2401\u0001])/, + excludeEnd: true, + excludeBegin: true, + className: 'string' + } + ] + }], + case_insensitive: true + }; +} + +module.exports = fix; + + +/***/ }), + +/***/ 94215: +/***/ ((module) => { + +/* + Language: Flix + Category: functional + Author: Magnus Madsen + Website: https://flix.dev/ + */ + + /** @type LanguageFn */ +function flix(hljs) { + const CHAR = { + className: 'string', + begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/ + }; + + const STRING = { + className: 'string', + variants: [{ + begin: '"', + end: '"' + }] + }; + + const NAME = { + className: 'title', + relevance: 0, + begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/ + }; + + const METHOD = { + className: 'function', + beginKeywords: 'def', + end: /[:={\[(\n;]/, + excludeEnd: true, + contains: [NAME] + }; + + return { + name: 'Flix', + keywords: { + literal: 'true false', + keyword: 'case class def else enum if impl import in lat rel index let match namespace switch type yield with' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + CHAR, + STRING, + METHOD, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = flix; + + +/***/ }), + +/***/ 79368: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Fortran +Author: Anthony Scemama +Website: https://en.wikipedia.org/wiki/Fortran +Category: scientific +*/ + +/** @type LanguageFn */ +function fortran(hljs) { + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)' + }; + + const COMMENT = { + variants: [ + hljs.COMMENT('!', '$', { + relevance: 0 + }), + // allow FORTRAN 77 style comments + hljs.COMMENT('^C[ ]', '$', { + relevance: 0 + }), + hljs.COMMENT('^C$', '$', { + relevance: 0 + }) + ] + }; + + // regex in both fortran and irpf90 should match + const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/; + const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/; + const NUMBER = { + className: 'number', + variants: [ + { + begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + } + ], + relevance: 0 + }; + + const FUNCTION_DEF = { + className: 'function', + beginKeywords: 'subroutine function program', + illegal: '[${=\\n]', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }; + + const STRING = { + className: 'string', + relevance: 0, + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }; + + const KEYWORDS = { + literal: '.False. .True.', + keyword: 'kind do concurrent local shared while private call intrinsic where elsewhere ' + + 'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then block endblock endassociate ' + + 'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' + + 'goto save else use module select case ' + + 'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' + + 'continue format pause cycle exit ' + + 'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' + + 'synchronous nopass non_overridable pass protected volatile abstract extends import ' + + 'non_intrinsic value deferred generic final enumerator class associate bind enum ' + + 'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' + + 'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' + + 'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' + + 'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer ' + + 'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' + + 'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' + + 'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' + + 'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure impure ' + + 'integer real character complex logical codimension dimension allocatable|10 parameter ' + + 'external implicit|10 none double precision assign intent optional pointer ' + + 'target in out common equivalence data', + built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' + + 'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' + + 'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' + + 'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' + + 'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' + + 'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' + + 'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' + + 'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' + + 'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' + + 'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' + + 'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' + + 'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' + + 'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' + + 'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' + + 'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' + + 'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' + + 'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' + + 'num_images parity popcnt poppar shifta shiftl shiftr this_image sync change team co_broadcast co_max co_min co_sum co_reduce' + }; + return { + name: 'Fortran', + case_insensitive: true, + aliases: [ + 'f90', + 'f95' + ], + keywords: KEYWORDS, + illegal: /\/\*/, + contains: [ + STRING, + FUNCTION_DEF, + // allow `C = value` for assignments so they aren't misdetected + // as Fortran 77 style comments + { + begin: /^C\s*=(?!=)/, + relevance: 0 + }, + COMMENT, + NUMBER + ] + }; +} + +module.exports = fortran; + + +/***/ }), + +/***/ 990: +/***/ ((module) => { + +/* +Language: F# +Author: Jonas Follesø +Contributors: Troy Kershaw , Henrik Feldt +Website: https://docs.microsoft.com/en-us/dotnet/fsharp/ +Category: functional +*/ + +/** @type LanguageFn */ +function fsharp(hljs) { + const TYPEPARAM = { + begin: '<', + end: '>', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: /'[a-zA-Z0-9_]+/ + }) + ] + }; + + return { + name: 'F#', + aliases: ['fs'], + keywords: + 'abstract and as assert base begin class default delegate do done ' + + 'downcast downto elif else end exception extern false finally for ' + + 'fun function global if in inherit inline interface internal lazy let ' + + 'match member module mutable namespace new null of open or ' + + 'override private public rec return sig static struct then to ' + + 'true try type upcast use val void when while with yield', + illegal: /\/\*/, + contains: [ + { + // monad builder keywords (matches before non-bang kws) + className: 'keyword', + begin: /\b(yield|return|let|do)!/ + }, + { + className: 'string', + begin: '@"', + end: '"', + contains: [ + { + begin: '""' + } + ] + }, + { + className: 'string', + begin: '"""', + end: '"""' + }, + hljs.COMMENT('\\(\\*(\\s)', '\\*\\)', { + contains: ["self"] + }), + { + className: 'class', + beginKeywords: 'type', + end: '\\(|=|$', + excludeEnd: true, + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + TYPEPARAM + ] + }, + { + className: 'meta', + begin: '\\[<', + end: '>\\]', + relevance: 10 + }, + { + className: 'symbol', + begin: '\\B(\'[A-Za-z])\\b', + contains: [hljs.BACKSLASH_ESCAPE] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = fsharp; + + +/***/ }), + +/***/ 18916: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** @type LanguageFn */ +function gams(hljs) { + const KEYWORDS = { + keyword: + 'abort acronym acronyms alias all and assign binary card diag display ' + + 'else eq file files for free ge gt if integer le loop lt maximizing ' + + 'minimizing model models ne negative no not option options or ord ' + + 'positive prod put putpage puttl repeat sameas semicont semiint smax ' + + 'smin solve sos1 sos2 sum system table then until using while xor yes', + literal: + 'eps inf na', + built_in: + 'abs arccos arcsin arctan arctan2 Beta betaReg binomial ceil centropy ' + + 'cos cosh cvPower div div0 eDist entropy errorf execSeed exp fact ' + + 'floor frac gamma gammaReg log logBeta logGamma log10 log2 mapVal max ' + + 'min mod ncpCM ncpF ncpVUpow ncpVUsin normal pi poly power ' + + 'randBinomial randLinear randTriangle round rPower sigmoid sign ' + + 'signPower sin sinh slexp sllog10 slrec sqexp sqlog10 sqr sqrec sqrt ' + + 'tan tanh trunc uniform uniformInt vcPower bool_and bool_eqv bool_imp ' + + 'bool_not bool_or bool_xor ifThen rel_eq rel_ge rel_gt rel_le rel_lt ' + + 'rel_ne gday gdow ghour gleap gmillisec gminute gmonth gsecond gyear ' + + 'jdate jnow jstart jtime errorLevel execError gamsRelease gamsVersion ' + + 'handleCollect handleDelete handleStatus handleSubmit heapFree ' + + 'heapLimit heapSize jobHandle jobKill jobStatus jobTerminate ' + + 'licenseLevel licenseStatus maxExecError sleep timeClose timeComp ' + + 'timeElapsed timeExec timeStart' + }; + const PARAMS = { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true + }; + const SYMBOLS = { + className: 'symbol', + variants: [ + { + begin: /=[lgenxc]=/ + }, + { + begin: /\$/ + } + ] + }; + const QSTR = { // One-line quoted comment string + className: 'comment', + variants: [ + { + begin: '\'', + end: '\'' + }, + { + begin: '"', + end: '"' + } + ], + illegal: '\\n', + contains: [hljs.BACKSLASH_ESCAPE] + }; + const ASSIGNMENT = { + begin: '/', + end: '/', + keywords: KEYWORDS, + contains: [ + QSTR, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; + const COMMENT_WORD = /[a-z0-9&#*=?@\\><:,()$[\]_.{}!+%^-]+/; + const DESCTEXT = { // Parameter/set/variable description text + begin: /[a-z][a-z0-9_]*(\([a-z0-9_, ]*\))?[ \t]+/, + excludeBegin: true, + end: '$', + endsWithParent: true, + contains: [ + QSTR, + ASSIGNMENT, + { + className: 'comment', + // one comment word, then possibly more + begin: concat( + COMMENT_WORD, + // [ ] because \s would be too broad (matching newlines) + anyNumberOfTimes(concat(/[ ]+/, COMMENT_WORD)) + ), + relevance: 0 + } + ] + }; + + return { + name: 'GAMS', + aliases: ['gms'], + case_insensitive: true, + keywords: KEYWORDS, + contains: [ + hljs.COMMENT(/^\$ontext/, /^\$offtext/), + { + className: 'meta', + begin: '^\\$[a-z0-9]+', + end: '$', + returnBegin: true, + contains: [ + { + className: 'meta-keyword', + begin: '^\\$[a-z0-9]+' + } + ] + }, + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + // Declarations + { + beginKeywords: + 'set sets parameter parameters variable variables ' + + 'scalar scalars equation equations', + end: ';', + contains: [ + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + ASSIGNMENT, + DESCTEXT + ] + }, + { // table environment + beginKeywords: 'table', + end: ';', + returnBegin: true, + contains: [ + { // table header row + beginKeywords: 'table', + end: '$', + contains: [DESCTEXT] + }, + hljs.COMMENT('^\\*', '$'), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + hljs.C_NUMBER_MODE + // Table does not contain DESCTEXT or ASSIGNMENT + ] + }, + // Function definitions + { + className: 'function', + begin: /^[a-z][a-z0-9_,\-+' ()$]+\.{2}/, + returnBegin: true, + contains: [ + { // Function title + className: 'title', + begin: /^[a-z0-9_]+/ + }, + PARAMS, + SYMBOLS + ] + }, + hljs.C_NUMBER_MODE, + SYMBOLS + ] + }; +} + +module.exports = gams; + + +/***/ }), + +/***/ 25875: +/***/ ((module) => { + +/* +Language: GAUSS +Author: Matt Evans +Description: GAUSS Mathematical and Statistical language +Website: https://www.aptech.com +Category: scientific +*/ +function gauss(hljs) { + const KEYWORDS = { + keyword: 'bool break call callexe checkinterrupt clear clearg closeall cls comlog compile ' + + 'continue create debug declare delete disable dlibrary dllcall do dos ed edit else ' + + 'elseif enable end endfor endif endp endo errorlog errorlogat expr external fn ' + + 'for format goto gosub graph if keyword let lib library line load loadarray loadexe ' + + 'loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow ' + + 'matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print ' + + 'printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen ' + + 'scroll setarray show sparse stop string struct system trace trap threadfor ' + + 'threadendfor threadbegin threadjoin threadstat threadend until use while winprint ' + + 'ne ge le gt lt and xor or not eq eqv', + built_in: 'abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol ' + + 'AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks ' + + 'AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults ' + + 'annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness ' + + 'annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd ' + + 'astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar ' + + 'base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 ' + + 'cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv ' + + 'cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn ' + + 'cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi ' + + 'cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ' + + 'ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated ' + + 'complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs ' + + 'cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos ' + + 'datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd ' + + 'dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName ' + + 'dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy ' + + 'dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen ' + + 'dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA ' + + 'dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField ' + + 'dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition ' + + 'dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows ' + + 'dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly ' + + 'dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy ' + + 'dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl ' + + 'dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt ' + + 'dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday ' + + 'dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays ' + + 'endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error ' + + 'etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut ' + + 'EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol ' + + 'EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq ' + + 'feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt ' + + 'floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC ' + + 'gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders ' + + 'gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse ' + + 'gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray ' + + 'getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders ' + + 'getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT ' + + 'gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm ' + + 'hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 ' + + 'indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 ' + + 'inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf ' + + 'isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv ' + + 'lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn ' + + 'lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind ' + + 'loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars ' + + 'makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli ' + + 'mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave ' + + 'movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate ' + + 'olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto ' + + 'pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox ' + + 'plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea ' + + 'plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout ' + + 'plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill ' + + 'plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol ' + + 'plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange ' + + 'plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel ' + + 'plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot ' + + 'pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames ' + + 'pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector ' + + 'pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate ' + + 'qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr ' + + 'real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn ' + + 'rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel ' + + 'rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn ' + + 'rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh ' + + 'rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind ' + + 'scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa ' + + 'setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind ' + + 'sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL ' + + 'spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense ' + + 'spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet ' + + 'sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt ' + + 'strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr ' + + 'surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname ' + + 'time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk ' + + 'trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt ' + + 'utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs ' + + 'vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window ' + + 'writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM ' + + 'xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute ' + + 'h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels ' + + 'plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester ' + + 'strtrim', + literal: 'DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS ' + + 'DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 ' + + 'DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS ' + + 'DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES ' + + 'DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR' + }; + + const AT_COMMENT_MODE = hljs.COMMENT('@', '@'); + + const PREPROCESSOR = + { + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + { + beginKeywords: 'include', + end: '$', + keywords: { + 'meta-keyword': 'include' + }, + contains: [ + { + className: 'meta-string', + begin: '"', + end: '"', + illegal: '\\n' + } + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE + ] + }; + + const STRUCT_TYPE = + { + begin: /\bstruct\s+/, + end: /\s/, + keywords: "struct", + contains: [ + { + className: "type", + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; + + // only for definitions + const PARSE_PARAMS = [ + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + endsWithParent: true, + relevance: 0, + contains: [ + { // dots + className: 'literal', + begin: /\.\.\./ + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + STRUCT_TYPE + ] + } + ]; + + const FUNCTION_DEF = + { + className: "title", + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + }; + + const DEFINITION = function(beginKeywords, end, inherits) { + const mode = hljs.inherit( + { + className: "function", + beginKeywords: beginKeywords, + end: end, + excludeEnd: true, + contains: [].concat(PARSE_PARAMS) + }, + inherits || {} + ); + mode.contains.push(FUNCTION_DEF); + mode.contains.push(hljs.C_NUMBER_MODE); + mode.contains.push(hljs.C_BLOCK_COMMENT_MODE); + mode.contains.push(AT_COMMENT_MODE); + return mode; + }; + + const BUILT_IN_REF = + { // these are explicitly named internal function calls + className: 'built_in', + begin: '\\b(' + KEYWORDS.built_in.split(' ').join('|') + ')\\b' + }; + + const STRING_REF = + { + className: 'string', + begin: '"', + end: '"', + contains: [hljs.BACKSLASH_ESCAPE], + relevance: 0 + }; + + const FUNCTION_REF = + { + // className: "fn_ref", + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', + returnBegin: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + { + beginKeywords: KEYWORDS.keyword + }, + BUILT_IN_REF, + { // ambiguously named function calls get a relevance of 0 + className: 'built_in', + begin: hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; + + const FUNCTION_REF_PARAMS = + { + // className: "fn_ref_params", + begin: /\(/, + end: /\)/, + relevance: 0, + keywords: { + built_in: KEYWORDS.built_in, + literal: KEYWORDS.literal + }, + contains: [ + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + BUILT_IN_REF, + FUNCTION_REF, + STRING_REF, + 'self' + ] + }; + + FUNCTION_REF.contains.push(FUNCTION_REF_PARAMS); + + return { + name: 'GAUSS', + aliases: ['gss'], + case_insensitive: true, // language is case-insensitive + keywords: KEYWORDS, + illegal: /(\{[%#]|[%#]\}| <- )/, + contains: [ + hljs.C_NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + STRING_REF, + PREPROCESSOR, + { + className: 'keyword', + begin: /\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/ + }, + DEFINITION('proc keyword', ';'), + DEFINITION('fn', '='), + { + beginKeywords: 'for threadfor', + end: /;/, + // end: /\(/, + relevance: 0, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + AT_COMMENT_MODE, + FUNCTION_REF_PARAMS + ] + }, + { // custom method guard + // excludes method names from keyword processing + variants: [ + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\.' + hljs.UNDERSCORE_IDENT_RE + }, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s*=' + } + ], + relevance: 0 + }, + FUNCTION_REF, + STRUCT_TYPE + ] + }; +} + +module.exports = gauss; + + +/***/ }), + +/***/ 83306: +/***/ ((module) => { + +/* + Language: G-code (ISO 6983) + Contributors: Adam Joseph Cook + Description: G-code syntax highlighter for Fanuc and other common CNC machine tool controls. + Website: https://www.sis.se/api/document/preview/911952/ + */ + +function gcode(hljs) { + const GCODE_IDENT_RE = '[A-Z_][A-Z0-9_.]*'; + const GCODE_CLOSE_RE = '%'; + const GCODE_KEYWORDS = { + $pattern: GCODE_IDENT_RE, + keyword: 'IF DO WHILE ENDWHILE CALL ENDIF SUB ENDSUB GOTO REPEAT ENDREPEAT ' + + 'EQ LT GT NE GE LE OR XOR' + }; + const GCODE_START = { + className: 'meta', + begin: '([O])([0-9]+)' + }; + const NUMBER = hljs.inherit(hljs.C_NUMBER_MODE, { + begin: '([-+]?((\\.\\d+)|(\\d+)(\\.\\d*)?))|' + hljs.C_NUMBER_RE + }); + const GCODE_CODE = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT(/\(/, /\)/), + NUMBER, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'name', + begin: '([G])([0-9]+\\.?[0-9]?)' + }, + { + className: 'name', + begin: '([M])([0-9]+\\.?[0-9]?)' + }, + { + className: 'attr', + begin: '(VC|VS|#)', + end: '(\\d+)' + }, + { + className: 'attr', + begin: '(VZOFX|VZOFY|VZOFZ)' + }, + { + className: 'built_in', + begin: '(ATAN|ABS|ACOS|ASIN|SIN|COS|EXP|FIX|FUP|ROUND|LN|TAN)(\\[)', + contains: [ + NUMBER + ], + end: '\\]' + }, + { + className: 'symbol', + variants: [ + { + begin: 'N', + end: '\\d+', + illegal: '\\W' + } + ] + } + ]; + + return { + name: 'G-code (ISO 6983)', + aliases: ['nc'], + // Some implementations (CNC controls) of G-code are interoperable with uppercase and lowercase letters seamlessly. + // However, most prefer all uppercase and uppercase is customary. + case_insensitive: true, + keywords: GCODE_KEYWORDS, + contains: [ + { + className: 'meta', + begin: GCODE_CLOSE_RE + }, + GCODE_START + ].concat(GCODE_CODE) + }; +} + +module.exports = gcode; + + +/***/ }), + +/***/ 20412: +/***/ ((module) => { + +/* + Language: Gherkin + Author: Sam Pikesley (@pikesley) + Description: Gherkin is the format for cucumber specifications. It is a domain specific language which helps you to describe business behavior without the need to go into detail of implementation. + Website: https://cucumber.io/docs/gherkin/ + */ + +function gherkin(hljs) { + return { + name: 'Gherkin', + aliases: ['feature'], + keywords: 'Feature Background Ability Business\ Need Scenario Scenarios Scenario\ Outline Scenario\ Template Examples Given And Then But When', + contains: [ + { + className: 'symbol', + begin: '\\*', + relevance: 0 + }, + { + className: 'meta', + begin: '@[^@\\s]+' + }, + { + begin: '\\|', + end: '\\|\\w*$', + contains: [ + { + className: 'string', + begin: '[^|]+' + } + ] + }, + { + className: 'variable', + begin: '<', + end: '>' + }, + hljs.HASH_COMMENT_MODE, + { + className: 'string', + begin: '"""', + end: '"""' + }, + hljs.QUOTE_STRING_MODE + ] + }; +} + +module.exports = gherkin; + + +/***/ }), + +/***/ 76836: +/***/ ((module) => { + +/* +Language: GLSL +Description: OpenGL Shading Language +Author: Sergey Tikhomirov +Website: https://en.wikipedia.org/wiki/OpenGL_Shading_Language +Category: graphics +*/ + +function glsl(hljs) { + return { + name: 'GLSL', + keywords: { + keyword: + // Statements + 'break continue discard do else for if return while switch case default ' + + // Qualifiers + 'attribute binding buffer ccw centroid centroid varying coherent column_major const cw ' + + 'depth_any depth_greater depth_less depth_unchanged early_fragment_tests equal_spacing ' + + 'flat fractional_even_spacing fractional_odd_spacing highp in index inout invariant ' + + 'invocations isolines layout line_strip lines lines_adjacency local_size_x local_size_y ' + + 'local_size_z location lowp max_vertices mediump noperspective offset origin_upper_left ' + + 'out packed patch pixel_center_integer point_mode points precise precision quads r11f_g11f_b10f ' + + 'r16 r16_snorm r16f r16i r16ui r32f r32i r32ui r8 r8_snorm r8i r8ui readonly restrict ' + + 'rg16 rg16_snorm rg16f rg16i rg16ui rg32f rg32i rg32ui rg8 rg8_snorm rg8i rg8ui rgb10_a2 ' + + 'rgb10_a2ui rgba16 rgba16_snorm rgba16f rgba16i rgba16ui rgba32f rgba32i rgba32ui rgba8 ' + + 'rgba8_snorm rgba8i rgba8ui row_major sample shared smooth std140 std430 stream triangle_strip ' + + 'triangles triangles_adjacency uniform varying vertices volatile writeonly', + type: + 'atomic_uint bool bvec2 bvec3 bvec4 dmat2 dmat2x2 dmat2x3 dmat2x4 dmat3 dmat3x2 dmat3x3 ' + + 'dmat3x4 dmat4 dmat4x2 dmat4x3 dmat4x4 double dvec2 dvec3 dvec4 float iimage1D iimage1DArray ' + + 'iimage2D iimage2DArray iimage2DMS iimage2DMSArray iimage2DRect iimage3D iimageBuffer ' + + 'iimageCube iimageCubeArray image1D image1DArray image2D image2DArray image2DMS image2DMSArray ' + + 'image2DRect image3D imageBuffer imageCube imageCubeArray int isampler1D isampler1DArray ' + + 'isampler2D isampler2DArray isampler2DMS isampler2DMSArray isampler2DRect isampler3D ' + + 'isamplerBuffer isamplerCube isamplerCubeArray ivec2 ivec3 ivec4 mat2 mat2x2 mat2x3 ' + + 'mat2x4 mat3 mat3x2 mat3x3 mat3x4 mat4 mat4x2 mat4x3 mat4x4 sampler1D sampler1DArray ' + + 'sampler1DArrayShadow sampler1DShadow sampler2D sampler2DArray sampler2DArrayShadow ' + + 'sampler2DMS sampler2DMSArray sampler2DRect sampler2DRectShadow sampler2DShadow sampler3D ' + + 'samplerBuffer samplerCube samplerCubeArray samplerCubeArrayShadow samplerCubeShadow ' + + 'image1D uimage1DArray uimage2D uimage2DArray uimage2DMS uimage2DMSArray uimage2DRect ' + + 'uimage3D uimageBuffer uimageCube uimageCubeArray uint usampler1D usampler1DArray ' + + 'usampler2D usampler2DArray usampler2DMS usampler2DMSArray usampler2DRect usampler3D ' + + 'samplerBuffer usamplerCube usamplerCubeArray uvec2 uvec3 uvec4 vec2 vec3 vec4 void', + built_in: + // Constants + 'gl_MaxAtomicCounterBindings gl_MaxAtomicCounterBufferSize gl_MaxClipDistances gl_MaxClipPlanes ' + + 'gl_MaxCombinedAtomicCounterBuffers gl_MaxCombinedAtomicCounters gl_MaxCombinedImageUniforms ' + + 'gl_MaxCombinedImageUnitsAndFragmentOutputs gl_MaxCombinedTextureImageUnits gl_MaxComputeAtomicCounterBuffers ' + + 'gl_MaxComputeAtomicCounters gl_MaxComputeImageUniforms gl_MaxComputeTextureImageUnits ' + + 'gl_MaxComputeUniformComponents gl_MaxComputeWorkGroupCount gl_MaxComputeWorkGroupSize ' + + 'gl_MaxDrawBuffers gl_MaxFragmentAtomicCounterBuffers gl_MaxFragmentAtomicCounters ' + + 'gl_MaxFragmentImageUniforms gl_MaxFragmentInputComponents gl_MaxFragmentInputVectors ' + + 'gl_MaxFragmentUniformComponents gl_MaxFragmentUniformVectors gl_MaxGeometryAtomicCounterBuffers ' + + 'gl_MaxGeometryAtomicCounters gl_MaxGeometryImageUniforms gl_MaxGeometryInputComponents ' + + 'gl_MaxGeometryOutputComponents gl_MaxGeometryOutputVertices gl_MaxGeometryTextureImageUnits ' + + 'gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents gl_MaxGeometryVaryingComponents ' + + 'gl_MaxImageSamples gl_MaxImageUnits gl_MaxLights gl_MaxPatchVertices gl_MaxProgramTexelOffset ' + + 'gl_MaxTessControlAtomicCounterBuffers gl_MaxTessControlAtomicCounters gl_MaxTessControlImageUniforms ' + + 'gl_MaxTessControlInputComponents gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits ' + + 'gl_MaxTessControlTotalOutputComponents gl_MaxTessControlUniformComponents ' + + 'gl_MaxTessEvaluationAtomicCounterBuffers gl_MaxTessEvaluationAtomicCounters ' + + 'gl_MaxTessEvaluationImageUniforms gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents ' + + 'gl_MaxTessEvaluationTextureImageUnits gl_MaxTessEvaluationUniformComponents ' + + 'gl_MaxTessGenLevel gl_MaxTessPatchComponents gl_MaxTextureCoords gl_MaxTextureImageUnits ' + + 'gl_MaxTextureUnits gl_MaxVaryingComponents gl_MaxVaryingFloats gl_MaxVaryingVectors ' + + 'gl_MaxVertexAtomicCounterBuffers gl_MaxVertexAtomicCounters gl_MaxVertexAttribs gl_MaxVertexImageUniforms ' + + 'gl_MaxVertexOutputComponents gl_MaxVertexOutputVectors gl_MaxVertexTextureImageUnits ' + + 'gl_MaxVertexUniformComponents gl_MaxVertexUniformVectors gl_MaxViewports gl_MinProgramTexelOffset ' + + // Variables + 'gl_BackColor gl_BackLightModelProduct gl_BackLightProduct gl_BackMaterial ' + + 'gl_BackSecondaryColor gl_ClipDistance gl_ClipPlane gl_ClipVertex gl_Color ' + + 'gl_DepthRange gl_EyePlaneQ gl_EyePlaneR gl_EyePlaneS gl_EyePlaneT gl_Fog gl_FogCoord ' + + 'gl_FogFragCoord gl_FragColor gl_FragCoord gl_FragData gl_FragDepth gl_FrontColor ' + + 'gl_FrontFacing gl_FrontLightModelProduct gl_FrontLightProduct gl_FrontMaterial ' + + 'gl_FrontSecondaryColor gl_GlobalInvocationID gl_InstanceID gl_InvocationID gl_Layer gl_LightModel ' + + 'gl_LightSource gl_LocalInvocationID gl_LocalInvocationIndex gl_ModelViewMatrix ' + + 'gl_ModelViewMatrixInverse gl_ModelViewMatrixInverseTranspose gl_ModelViewMatrixTranspose ' + + 'gl_ModelViewProjectionMatrix gl_ModelViewProjectionMatrixInverse gl_ModelViewProjectionMatrixInverseTranspose ' + + 'gl_ModelViewProjectionMatrixTranspose gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 ' + + 'gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 ' + + 'gl_Normal gl_NormalMatrix gl_NormalScale gl_NumSamples gl_NumWorkGroups gl_ObjectPlaneQ ' + + 'gl_ObjectPlaneR gl_ObjectPlaneS gl_ObjectPlaneT gl_PatchVerticesIn gl_Point gl_PointCoord ' + + 'gl_PointSize gl_Position gl_PrimitiveID gl_PrimitiveIDIn gl_ProjectionMatrix gl_ProjectionMatrixInverse ' + + 'gl_ProjectionMatrixInverseTranspose gl_ProjectionMatrixTranspose gl_SampleID gl_SampleMask ' + + 'gl_SampleMaskIn gl_SamplePosition gl_SecondaryColor gl_TessCoord gl_TessLevelInner gl_TessLevelOuter ' + + 'gl_TexCoord gl_TextureEnvColor gl_TextureMatrix gl_TextureMatrixInverse gl_TextureMatrixInverseTranspose ' + + 'gl_TextureMatrixTranspose gl_Vertex gl_VertexID gl_ViewportIndex gl_WorkGroupID gl_WorkGroupSize gl_in gl_out ' + + // Functions + 'EmitStreamVertex EmitVertex EndPrimitive EndStreamPrimitive abs acos acosh all any asin ' + + 'asinh atan atanh atomicAdd atomicAnd atomicCompSwap atomicCounter atomicCounterDecrement ' + + 'atomicCounterIncrement atomicExchange atomicMax atomicMin atomicOr atomicXor barrier ' + + 'bitCount bitfieldExtract bitfieldInsert bitfieldReverse ceil clamp cos cosh cross ' + + 'dFdx dFdy degrees determinant distance dot equal exp exp2 faceforward findLSB findMSB ' + + 'floatBitsToInt floatBitsToUint floor fma fract frexp ftransform fwidth greaterThan ' + + 'greaterThanEqual groupMemoryBarrier imageAtomicAdd imageAtomicAnd imageAtomicCompSwap ' + + 'imageAtomicExchange imageAtomicMax imageAtomicMin imageAtomicOr imageAtomicXor imageLoad ' + + 'imageSize imageStore imulExtended intBitsToFloat interpolateAtCentroid interpolateAtOffset ' + + 'interpolateAtSample inverse inversesqrt isinf isnan ldexp length lessThan lessThanEqual log ' + + 'log2 matrixCompMult max memoryBarrier memoryBarrierAtomicCounter memoryBarrierBuffer ' + + 'memoryBarrierImage memoryBarrierShared min mix mod modf noise1 noise2 noise3 noise4 ' + + 'normalize not notEqual outerProduct packDouble2x32 packHalf2x16 packSnorm2x16 packSnorm4x8 ' + + 'packUnorm2x16 packUnorm4x8 pow radians reflect refract round roundEven shadow1D shadow1DLod ' + + 'shadow1DProj shadow1DProjLod shadow2D shadow2DLod shadow2DProj shadow2DProjLod sign sin sinh ' + + 'smoothstep sqrt step tan tanh texelFetch texelFetchOffset texture texture1D texture1DLod ' + + 'texture1DProj texture1DProjLod texture2D texture2DLod texture2DProj texture2DProjLod ' + + 'texture3D texture3DLod texture3DProj texture3DProjLod textureCube textureCubeLod ' + + 'textureGather textureGatherOffset textureGatherOffsets textureGrad textureGradOffset ' + + 'textureLod textureLodOffset textureOffset textureProj textureProjGrad textureProjGradOffset ' + + 'textureProjLod textureProjLodOffset textureProjOffset textureQueryLevels textureQueryLod ' + + 'textureSize transpose trunc uaddCarry uintBitsToFloat umulExtended unpackDouble2x32 ' + + 'unpackHalf2x16 unpackSnorm2x16 unpackSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 usubBorrow', + literal: 'true false' + }, + illegal: '"', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '#', + end: '$' + } + ] + }; +} + +module.exports = glsl; + + +/***/ }), + +/***/ 27646: +/***/ ((module) => { + +/* +Language: GML +Author: Meseta +Description: Game Maker Language for GameMaker Studio 2 +Website: https://docs2.yoyogames.com +Category: scripting +*/ + +function gml(hljs) { + const GML_KEYWORDS = { + keyword: 'begin end if then else while do for break continue with until ' + + 'repeat exit and or xor not return mod div switch case default var ' + + 'globalvar enum function constructor delete #macro #region #endregion', + built_in: 'is_real is_string is_array is_undefined is_int32 is_int64 is_ptr ' + + 'is_vec3 is_vec4 is_matrix is_bool is_method is_struct is_infinity is_nan ' + + 'is_numeric typeof variable_global_exists variable_global_get variable_global_set ' + + 'variable_instance_exists variable_instance_get variable_instance_set ' + + 'variable_instance_get_names variable_struct_exists variable_struct_get ' + + 'variable_struct_get_names variable_struct_names_count variable_struct_remove ' + + 'variable_struct_set array_delete array_insert array_length array_length_1d ' + + 'array_length_2d array_height_2d array_equals array_create ' + + 'array_copy array_pop array_push array_resize array_sort ' + + 'random random_range irandom irandom_range random_set_seed random_get_seed ' + + 'randomize randomise choose abs round floor ceil sign frac sqrt sqr ' + + 'exp ln log2 log10 sin cos tan arcsin arccos arctan arctan2 dsin dcos ' + + 'dtan darcsin darccos darctan darctan2 degtorad radtodeg power logn ' + + 'min max mean median clamp lerp dot_product dot_product_3d ' + + 'dot_product_normalised dot_product_3d_normalised ' + + 'dot_product_normalized dot_product_3d_normalized math_set_epsilon ' + + 'math_get_epsilon angle_difference point_distance_3d point_distance ' + + 'point_direction lengthdir_x lengthdir_y real string int64 ptr ' + + 'string_format chr ansi_char ord string_length string_byte_length ' + + 'string_pos string_copy string_char_at string_ord_at string_byte_at ' + + 'string_set_byte_at string_delete string_insert string_lower ' + + 'string_upper string_repeat string_letters string_digits ' + + 'string_lettersdigits string_replace string_replace_all string_count ' + + 'string_hash_to_newline clipboard_has_text clipboard_set_text ' + + 'clipboard_get_text date_current_datetime date_create_datetime ' + + 'date_valid_datetime date_inc_year date_inc_month date_inc_week ' + + 'date_inc_day date_inc_hour date_inc_minute date_inc_second ' + + 'date_get_year date_get_month date_get_week date_get_day ' + + 'date_get_hour date_get_minute date_get_second date_get_weekday ' + + 'date_get_day_of_year date_get_hour_of_year date_get_minute_of_year ' + + 'date_get_second_of_year date_year_span date_month_span ' + + 'date_week_span date_day_span date_hour_span date_minute_span ' + + 'date_second_span date_compare_datetime date_compare_date ' + + 'date_compare_time date_date_of date_time_of date_datetime_string ' + + 'date_date_string date_time_string date_days_in_month ' + + 'date_days_in_year date_leap_year date_is_today date_set_timezone ' + + 'date_get_timezone game_set_speed game_get_speed motion_set ' + + 'motion_add place_free place_empty place_meeting place_snapped ' + + 'move_random move_snap move_towards_point move_contact_solid ' + + 'move_contact_all move_outside_solid move_outside_all ' + + 'move_bounce_solid move_bounce_all move_wrap distance_to_point ' + + 'distance_to_object position_empty position_meeting path_start ' + + 'path_end mp_linear_step mp_potential_step mp_linear_step_object ' + + 'mp_potential_step_object mp_potential_settings mp_linear_path ' + + 'mp_potential_path mp_linear_path_object mp_potential_path_object ' + + 'mp_grid_create mp_grid_destroy mp_grid_clear_all mp_grid_clear_cell ' + + 'mp_grid_clear_rectangle mp_grid_add_cell mp_grid_get_cell ' + + 'mp_grid_add_rectangle mp_grid_add_instances mp_grid_path ' + + 'mp_grid_draw mp_grid_to_ds_grid collision_point collision_rectangle ' + + 'collision_circle collision_ellipse collision_line ' + + 'collision_point_list collision_rectangle_list collision_circle_list ' + + 'collision_ellipse_list collision_line_list instance_position_list ' + + 'instance_place_list point_in_rectangle ' + + 'point_in_triangle point_in_circle rectangle_in_rectangle ' + + 'rectangle_in_triangle rectangle_in_circle instance_find ' + + 'instance_exists instance_number instance_position instance_nearest ' + + 'instance_furthest instance_place instance_create_depth ' + + 'instance_create_layer instance_copy instance_change instance_destroy ' + + 'position_destroy position_change instance_id_get ' + + 'instance_deactivate_all instance_deactivate_object ' + + 'instance_deactivate_region instance_activate_all ' + + 'instance_activate_object instance_activate_region room_goto ' + + 'room_goto_previous room_goto_next room_previous room_next ' + + 'room_restart game_end game_restart game_load game_save ' + + 'game_save_buffer game_load_buffer event_perform event_user ' + + 'event_perform_object event_inherited show_debug_message ' + + 'show_debug_overlay debug_event debug_get_callstack alarm_get ' + + 'alarm_set font_texture_page_size keyboard_set_map keyboard_get_map ' + + 'keyboard_unset_map keyboard_check keyboard_check_pressed ' + + 'keyboard_check_released keyboard_check_direct keyboard_get_numlock ' + + 'keyboard_set_numlock keyboard_key_press keyboard_key_release ' + + 'keyboard_clear io_clear mouse_check_button ' + + 'mouse_check_button_pressed mouse_check_button_released ' + + 'mouse_wheel_up mouse_wheel_down mouse_clear draw_self draw_sprite ' + + 'draw_sprite_pos draw_sprite_ext draw_sprite_stretched ' + + 'draw_sprite_stretched_ext draw_sprite_tiled draw_sprite_tiled_ext ' + + 'draw_sprite_part draw_sprite_part_ext draw_sprite_general draw_clear ' + + 'draw_clear_alpha draw_point draw_line draw_line_width draw_rectangle ' + + 'draw_roundrect draw_roundrect_ext draw_triangle draw_circle ' + + 'draw_ellipse draw_set_circle_precision draw_arrow draw_button ' + + 'draw_path draw_healthbar draw_getpixel draw_getpixel_ext ' + + 'draw_set_colour draw_set_color draw_set_alpha draw_get_colour ' + + 'draw_get_color draw_get_alpha merge_colour make_colour_rgb ' + + 'make_colour_hsv colour_get_red colour_get_green colour_get_blue ' + + 'colour_get_hue colour_get_saturation colour_get_value merge_color ' + + 'make_color_rgb make_color_hsv color_get_red color_get_green ' + + 'color_get_blue color_get_hue color_get_saturation color_get_value ' + + 'merge_color screen_save screen_save_part draw_set_font ' + + 'draw_set_halign draw_set_valign draw_text draw_text_ext string_width ' + + 'string_height string_width_ext string_height_ext ' + + 'draw_text_transformed draw_text_ext_transformed draw_text_colour ' + + 'draw_text_ext_colour draw_text_transformed_colour ' + + 'draw_text_ext_transformed_colour draw_text_color draw_text_ext_color ' + + 'draw_text_transformed_color draw_text_ext_transformed_color ' + + 'draw_point_colour draw_line_colour draw_line_width_colour ' + + 'draw_rectangle_colour draw_roundrect_colour ' + + 'draw_roundrect_colour_ext draw_triangle_colour draw_circle_colour ' + + 'draw_ellipse_colour draw_point_color draw_line_color ' + + 'draw_line_width_color draw_rectangle_color draw_roundrect_color ' + + 'draw_roundrect_color_ext draw_triangle_color draw_circle_color ' + + 'draw_ellipse_color draw_primitive_begin draw_vertex ' + + 'draw_vertex_colour draw_vertex_color draw_primitive_end ' + + 'sprite_get_uvs font_get_uvs sprite_get_texture font_get_texture ' + + 'texture_get_width texture_get_height texture_get_uvs ' + + 'draw_primitive_begin_texture draw_vertex_texture ' + + 'draw_vertex_texture_colour draw_vertex_texture_color ' + + 'texture_global_scale surface_create surface_create_ext ' + + 'surface_resize surface_free surface_exists surface_get_width ' + + 'surface_get_height surface_get_texture surface_set_target ' + + 'surface_set_target_ext surface_reset_target surface_depth_disable ' + + 'surface_get_depth_disable draw_surface draw_surface_stretched ' + + 'draw_surface_tiled draw_surface_part draw_surface_ext ' + + 'draw_surface_stretched_ext draw_surface_tiled_ext ' + + 'draw_surface_part_ext draw_surface_general surface_getpixel ' + + 'surface_getpixel_ext surface_save surface_save_part surface_copy ' + + 'surface_copy_part application_surface_draw_enable ' + + 'application_get_position application_surface_enable ' + + 'application_surface_is_enabled display_get_width display_get_height ' + + 'display_get_orientation display_get_gui_width display_get_gui_height ' + + 'display_reset display_mouse_get_x display_mouse_get_y ' + + 'display_mouse_set display_set_ui_visibility ' + + 'window_set_fullscreen window_get_fullscreen ' + + 'window_set_caption window_set_min_width window_set_max_width ' + + 'window_set_min_height window_set_max_height window_get_visible_rects ' + + 'window_get_caption window_set_cursor window_get_cursor ' + + 'window_set_colour window_get_colour window_set_color ' + + 'window_get_color window_set_position window_set_size ' + + 'window_set_rectangle window_center window_get_x window_get_y ' + + 'window_get_width window_get_height window_mouse_get_x ' + + 'window_mouse_get_y window_mouse_set window_view_mouse_get_x ' + + 'window_view_mouse_get_y window_views_mouse_get_x ' + + 'window_views_mouse_get_y audio_listener_position ' + + 'audio_listener_velocity audio_listener_orientation ' + + 'audio_emitter_position audio_emitter_create audio_emitter_free ' + + 'audio_emitter_exists audio_emitter_pitch audio_emitter_velocity ' + + 'audio_emitter_falloff audio_emitter_gain audio_play_sound ' + + 'audio_play_sound_on audio_play_sound_at audio_stop_sound ' + + 'audio_resume_music audio_music_is_playing audio_resume_sound ' + + 'audio_pause_sound audio_pause_music audio_channel_num ' + + 'audio_sound_length audio_get_type audio_falloff_set_model ' + + 'audio_play_music audio_stop_music audio_master_gain audio_music_gain ' + + 'audio_sound_gain audio_sound_pitch audio_stop_all audio_resume_all ' + + 'audio_pause_all audio_is_playing audio_is_paused audio_exists ' + + 'audio_sound_set_track_position audio_sound_get_track_position ' + + 'audio_emitter_get_gain audio_emitter_get_pitch audio_emitter_get_x ' + + 'audio_emitter_get_y audio_emitter_get_z audio_emitter_get_vx ' + + 'audio_emitter_get_vy audio_emitter_get_vz ' + + 'audio_listener_set_position audio_listener_set_velocity ' + + 'audio_listener_set_orientation audio_listener_get_data ' + + 'audio_set_master_gain audio_get_master_gain audio_sound_get_gain ' + + 'audio_sound_get_pitch audio_get_name audio_sound_set_track_position ' + + 'audio_sound_get_track_position audio_create_stream ' + + 'audio_destroy_stream audio_create_sync_group ' + + 'audio_destroy_sync_group audio_play_in_sync_group ' + + 'audio_start_sync_group audio_stop_sync_group audio_pause_sync_group ' + + 'audio_resume_sync_group audio_sync_group_get_track_pos ' + + 'audio_sync_group_debug audio_sync_group_is_playing audio_debug ' + + 'audio_group_load audio_group_unload audio_group_is_loaded ' + + 'audio_group_load_progress audio_group_name audio_group_stop_all ' + + 'audio_group_set_gain audio_create_buffer_sound ' + + 'audio_free_buffer_sound audio_create_play_queue ' + + 'audio_free_play_queue audio_queue_sound audio_get_recorder_count ' + + 'audio_get_recorder_info audio_start_recording audio_stop_recording ' + + 'audio_sound_get_listener_mask audio_emitter_get_listener_mask ' + + 'audio_get_listener_mask audio_sound_set_listener_mask ' + + 'audio_emitter_set_listener_mask audio_set_listener_mask ' + + 'audio_get_listener_count audio_get_listener_info audio_system ' + + 'show_message show_message_async clickable_add clickable_add_ext ' + + 'clickable_change clickable_change_ext clickable_delete ' + + 'clickable_exists clickable_set_style show_question ' + + 'show_question_async get_integer get_string get_integer_async ' + + 'get_string_async get_login_async get_open_filename get_save_filename ' + + 'get_open_filename_ext get_save_filename_ext show_error ' + + 'highscore_clear highscore_add highscore_value highscore_name ' + + 'draw_highscore sprite_exists sprite_get_name sprite_get_number ' + + 'sprite_get_width sprite_get_height sprite_get_xoffset ' + + 'sprite_get_yoffset sprite_get_bbox_left sprite_get_bbox_right ' + + 'sprite_get_bbox_top sprite_get_bbox_bottom sprite_save ' + + 'sprite_save_strip sprite_set_cache_size sprite_set_cache_size_ext ' + + 'sprite_get_tpe sprite_prefetch sprite_prefetch_multi sprite_flush ' + + 'sprite_flush_multi sprite_set_speed sprite_get_speed_type ' + + 'sprite_get_speed font_exists font_get_name font_get_fontname ' + + 'font_get_bold font_get_italic font_get_first font_get_last ' + + 'font_get_size font_set_cache_size path_exists path_get_name ' + + 'path_get_length path_get_time path_get_kind path_get_closed ' + + 'path_get_precision path_get_number path_get_point_x path_get_point_y ' + + 'path_get_point_speed path_get_x path_get_y path_get_speed ' + + 'script_exists script_get_name timeline_add timeline_delete ' + + 'timeline_clear timeline_exists timeline_get_name ' + + 'timeline_moment_clear timeline_moment_add_script timeline_size ' + + 'timeline_max_moment object_exists object_get_name object_get_sprite ' + + 'object_get_solid object_get_visible object_get_persistent ' + + 'object_get_mask object_get_parent object_get_physics ' + + 'object_is_ancestor room_exists room_get_name sprite_set_offset ' + + 'sprite_duplicate sprite_assign sprite_merge sprite_add ' + + 'sprite_replace sprite_create_from_surface sprite_add_from_surface ' + + 'sprite_delete sprite_set_alpha_from_sprite sprite_collision_mask ' + + 'font_add_enable_aa font_add_get_enable_aa font_add font_add_sprite ' + + 'font_add_sprite_ext font_replace font_replace_sprite ' + + 'font_replace_sprite_ext font_delete path_set_kind path_set_closed ' + + 'path_set_precision path_add path_assign path_duplicate path_append ' + + 'path_delete path_add_point path_insert_point path_change_point ' + + 'path_delete_point path_clear_points path_reverse path_mirror ' + + 'path_flip path_rotate path_rescale path_shift script_execute ' + + 'object_set_sprite object_set_solid object_set_visible ' + + 'object_set_persistent object_set_mask room_set_width room_set_height ' + + 'room_set_persistent room_set_background_colour ' + + 'room_set_background_color room_set_view room_set_viewport ' + + 'room_get_viewport room_set_view_enabled room_add room_duplicate ' + + 'room_assign room_instance_add room_instance_clear room_get_camera ' + + 'room_set_camera asset_get_index asset_get_type ' + + 'file_text_open_from_string file_text_open_read file_text_open_write ' + + 'file_text_open_append file_text_close file_text_write_string ' + + 'file_text_write_real file_text_writeln file_text_read_string ' + + 'file_text_read_real file_text_readln file_text_eof file_text_eoln ' + + 'file_exists file_delete file_rename file_copy directory_exists ' + + 'directory_create directory_destroy file_find_first file_find_next ' + + 'file_find_close file_attributes filename_name filename_path ' + + 'filename_dir filename_drive filename_ext filename_change_ext ' + + 'file_bin_open file_bin_rewrite file_bin_close file_bin_position ' + + 'file_bin_size file_bin_seek file_bin_write_byte file_bin_read_byte ' + + 'parameter_count parameter_string environment_get_variable ' + + 'ini_open_from_string ini_open ini_close ini_read_string ' + + 'ini_read_real ini_write_string ini_write_real ini_key_exists ' + + 'ini_section_exists ini_key_delete ini_section_delete ' + + 'ds_set_precision ds_exists ds_stack_create ds_stack_destroy ' + + 'ds_stack_clear ds_stack_copy ds_stack_size ds_stack_empty ' + + 'ds_stack_push ds_stack_pop ds_stack_top ds_stack_write ds_stack_read ' + + 'ds_queue_create ds_queue_destroy ds_queue_clear ds_queue_copy ' + + 'ds_queue_size ds_queue_empty ds_queue_enqueue ds_queue_dequeue ' + + 'ds_queue_head ds_queue_tail ds_queue_write ds_queue_read ' + + 'ds_list_create ds_list_destroy ds_list_clear ds_list_copy ' + + 'ds_list_size ds_list_empty ds_list_add ds_list_insert ' + + 'ds_list_replace ds_list_delete ds_list_find_index ds_list_find_value ' + + 'ds_list_mark_as_list ds_list_mark_as_map ds_list_sort ' + + 'ds_list_shuffle ds_list_write ds_list_read ds_list_set ds_map_create ' + + 'ds_map_destroy ds_map_clear ds_map_copy ds_map_size ds_map_empty ' + + 'ds_map_add ds_map_add_list ds_map_add_map ds_map_replace ' + + 'ds_map_replace_map ds_map_replace_list ds_map_delete ds_map_exists ' + + 'ds_map_find_value ds_map_find_previous ds_map_find_next ' + + 'ds_map_find_first ds_map_find_last ds_map_write ds_map_read ' + + 'ds_map_secure_save ds_map_secure_load ds_map_secure_load_buffer ' + + 'ds_map_secure_save_buffer ds_map_set ds_priority_create ' + + 'ds_priority_destroy ds_priority_clear ds_priority_copy ' + + 'ds_priority_size ds_priority_empty ds_priority_add ' + + 'ds_priority_change_priority ds_priority_find_priority ' + + 'ds_priority_delete_value ds_priority_delete_min ds_priority_find_min ' + + 'ds_priority_delete_max ds_priority_find_max ds_priority_write ' + + 'ds_priority_read ds_grid_create ds_grid_destroy ds_grid_copy ' + + 'ds_grid_resize ds_grid_width ds_grid_height ds_grid_clear ' + + 'ds_grid_set ds_grid_add ds_grid_multiply ds_grid_set_region ' + + 'ds_grid_add_region ds_grid_multiply_region ds_grid_set_disk ' + + 'ds_grid_add_disk ds_grid_multiply_disk ds_grid_set_grid_region ' + + 'ds_grid_add_grid_region ds_grid_multiply_grid_region ds_grid_get ' + + 'ds_grid_get_sum ds_grid_get_max ds_grid_get_min ds_grid_get_mean ' + + 'ds_grid_get_disk_sum ds_grid_get_disk_min ds_grid_get_disk_max ' + + 'ds_grid_get_disk_mean ds_grid_value_exists ds_grid_value_x ' + + 'ds_grid_value_y ds_grid_value_disk_exists ds_grid_value_disk_x ' + + 'ds_grid_value_disk_y ds_grid_shuffle ds_grid_write ds_grid_read ' + + 'ds_grid_sort ds_grid_set ds_grid_get effect_create_below ' + + 'effect_create_above effect_clear part_type_create part_type_destroy ' + + 'part_type_exists part_type_clear part_type_shape part_type_sprite ' + + 'part_type_size part_type_scale part_type_orientation part_type_life ' + + 'part_type_step part_type_death part_type_speed part_type_direction ' + + 'part_type_gravity part_type_colour1 part_type_colour2 ' + + 'part_type_colour3 part_type_colour_mix part_type_colour_rgb ' + + 'part_type_colour_hsv part_type_color1 part_type_color2 ' + + 'part_type_color3 part_type_color_mix part_type_color_rgb ' + + 'part_type_color_hsv part_type_alpha1 part_type_alpha2 ' + + 'part_type_alpha3 part_type_blend part_system_create ' + + 'part_system_create_layer part_system_destroy part_system_exists ' + + 'part_system_clear part_system_draw_order part_system_depth ' + + 'part_system_position part_system_automatic_update ' + + 'part_system_automatic_draw part_system_update part_system_drawit ' + + 'part_system_get_layer part_system_layer part_particles_create ' + + 'part_particles_create_colour part_particles_create_color ' + + 'part_particles_clear part_particles_count part_emitter_create ' + + 'part_emitter_destroy part_emitter_destroy_all part_emitter_exists ' + + 'part_emitter_clear part_emitter_region part_emitter_burst ' + + 'part_emitter_stream external_call external_define external_free ' + + 'window_handle window_device matrix_get matrix_set ' + + 'matrix_build_identity matrix_build matrix_build_lookat ' + + 'matrix_build_projection_ortho matrix_build_projection_perspective ' + + 'matrix_build_projection_perspective_fov matrix_multiply ' + + 'matrix_transform_vertex matrix_stack_push matrix_stack_pop ' + + 'matrix_stack_multiply matrix_stack_set matrix_stack_clear ' + + 'matrix_stack_top matrix_stack_is_empty browser_input_capture ' + + 'os_get_config os_get_info os_get_language os_get_region ' + + 'os_lock_orientation display_get_dpi_x display_get_dpi_y ' + + 'display_set_gui_size display_set_gui_maximise ' + + 'display_set_gui_maximize device_mouse_dbclick_enable ' + + 'display_set_timing_method display_get_timing_method ' + + 'display_set_sleep_margin display_get_sleep_margin virtual_key_add ' + + 'virtual_key_hide virtual_key_delete virtual_key_show ' + + 'draw_enable_drawevent draw_enable_swf_aa draw_set_swf_aa_level ' + + 'draw_get_swf_aa_level draw_texture_flush draw_flush ' + + 'gpu_set_blendenable gpu_set_ztestenable gpu_set_zfunc ' + + 'gpu_set_zwriteenable gpu_set_lightingenable gpu_set_fog ' + + 'gpu_set_cullmode gpu_set_blendmode gpu_set_blendmode_ext ' + + 'gpu_set_blendmode_ext_sepalpha gpu_set_colorwriteenable ' + + 'gpu_set_colourwriteenable gpu_set_alphatestenable ' + + 'gpu_set_alphatestref gpu_set_alphatestfunc gpu_set_texfilter ' + + 'gpu_set_texfilter_ext gpu_set_texrepeat gpu_set_texrepeat_ext ' + + 'gpu_set_tex_filter gpu_set_tex_filter_ext gpu_set_tex_repeat ' + + 'gpu_set_tex_repeat_ext gpu_set_tex_mip_filter ' + + 'gpu_set_tex_mip_filter_ext gpu_set_tex_mip_bias ' + + 'gpu_set_tex_mip_bias_ext gpu_set_tex_min_mip gpu_set_tex_min_mip_ext ' + + 'gpu_set_tex_max_mip gpu_set_tex_max_mip_ext gpu_set_tex_max_aniso ' + + 'gpu_set_tex_max_aniso_ext gpu_set_tex_mip_enable ' + + 'gpu_set_tex_mip_enable_ext gpu_get_blendenable gpu_get_ztestenable ' + + 'gpu_get_zfunc gpu_get_zwriteenable gpu_get_lightingenable ' + + 'gpu_get_fog gpu_get_cullmode gpu_get_blendmode gpu_get_blendmode_ext ' + + 'gpu_get_blendmode_ext_sepalpha gpu_get_blendmode_src ' + + 'gpu_get_blendmode_dest gpu_get_blendmode_srcalpha ' + + 'gpu_get_blendmode_destalpha gpu_get_colorwriteenable ' + + 'gpu_get_colourwriteenable gpu_get_alphatestenable ' + + 'gpu_get_alphatestref gpu_get_alphatestfunc gpu_get_texfilter ' + + 'gpu_get_texfilter_ext gpu_get_texrepeat gpu_get_texrepeat_ext ' + + 'gpu_get_tex_filter gpu_get_tex_filter_ext gpu_get_tex_repeat ' + + 'gpu_get_tex_repeat_ext gpu_get_tex_mip_filter ' + + 'gpu_get_tex_mip_filter_ext gpu_get_tex_mip_bias ' + + 'gpu_get_tex_mip_bias_ext gpu_get_tex_min_mip gpu_get_tex_min_mip_ext ' + + 'gpu_get_tex_max_mip gpu_get_tex_max_mip_ext gpu_get_tex_max_aniso ' + + 'gpu_get_tex_max_aniso_ext gpu_get_tex_mip_enable ' + + 'gpu_get_tex_mip_enable_ext gpu_push_state gpu_pop_state ' + + 'gpu_get_state gpu_set_state draw_light_define_ambient ' + + 'draw_light_define_direction draw_light_define_point ' + + 'draw_light_enable draw_set_lighting draw_light_get_ambient ' + + 'draw_light_get draw_get_lighting shop_leave_rating url_get_domain ' + + 'url_open url_open_ext url_open_full get_timer achievement_login ' + + 'achievement_logout achievement_post achievement_increment ' + + 'achievement_post_score achievement_available ' + + 'achievement_show_achievements achievement_show_leaderboards ' + + 'achievement_load_friends achievement_load_leaderboard ' + + 'achievement_send_challenge achievement_load_progress ' + + 'achievement_reset achievement_login_status achievement_get_pic ' + + 'achievement_show_challenge_notifications achievement_get_challenges ' + + 'achievement_event achievement_show achievement_get_info ' + + 'cloud_file_save cloud_string_save cloud_synchronise ads_enable ' + + 'ads_disable ads_setup ads_engagement_launch ads_engagement_available ' + + 'ads_engagement_active ads_event ads_event_preload ' + + 'ads_set_reward_callback ads_get_display_height ads_get_display_width ' + + 'ads_move ads_interstitial_available ads_interstitial_display ' + + 'device_get_tilt_x device_get_tilt_y device_get_tilt_z ' + + 'device_is_keypad_open device_mouse_check_button ' + + 'device_mouse_check_button_pressed device_mouse_check_button_released ' + + 'device_mouse_x device_mouse_y device_mouse_raw_x device_mouse_raw_y ' + + 'device_mouse_x_to_gui device_mouse_y_to_gui iap_activate iap_status ' + + 'iap_enumerate_products iap_restore_all iap_acquire iap_consume ' + + 'iap_product_details iap_purchase_details facebook_init ' + + 'facebook_login facebook_status facebook_graph_request ' + + 'facebook_dialog facebook_logout facebook_launch_offerwall ' + + 'facebook_post_message facebook_send_invite facebook_user_id ' + + 'facebook_accesstoken facebook_check_permission ' + + 'facebook_request_read_permissions ' + + 'facebook_request_publish_permissions gamepad_is_supported ' + + 'gamepad_get_device_count gamepad_is_connected ' + + 'gamepad_get_description gamepad_get_button_threshold ' + + 'gamepad_set_button_threshold gamepad_get_axis_deadzone ' + + 'gamepad_set_axis_deadzone gamepad_button_count gamepad_button_check ' + + 'gamepad_button_check_pressed gamepad_button_check_released ' + + 'gamepad_button_value gamepad_axis_count gamepad_axis_value ' + + 'gamepad_set_vibration gamepad_set_colour gamepad_set_color ' + + 'os_is_paused window_has_focus code_is_compiled http_get ' + + 'http_get_file http_post_string http_request json_encode json_decode ' + + 'zip_unzip load_csv base64_encode base64_decode md5_string_unicode ' + + 'md5_string_utf8 md5_file os_is_network_connected sha1_string_unicode ' + + 'sha1_string_utf8 sha1_file os_powersave_enable analytics_event ' + + 'analytics_event_ext win8_livetile_tile_notification ' + + 'win8_livetile_tile_clear win8_livetile_badge_notification ' + + 'win8_livetile_badge_clear win8_livetile_queue_enable ' + + 'win8_secondarytile_pin win8_secondarytile_badge_notification ' + + 'win8_secondarytile_delete win8_livetile_notification_begin ' + + 'win8_livetile_notification_secondary_begin ' + + 'win8_livetile_notification_expiry win8_livetile_notification_tag ' + + 'win8_livetile_notification_text_add ' + + 'win8_livetile_notification_image_add win8_livetile_notification_end ' + + 'win8_appbar_enable win8_appbar_add_element ' + + 'win8_appbar_remove_element win8_settingscharm_add_entry ' + + 'win8_settingscharm_add_html_entry win8_settingscharm_add_xaml_entry ' + + 'win8_settingscharm_set_xaml_property ' + + 'win8_settingscharm_get_xaml_property win8_settingscharm_remove_entry ' + + 'win8_share_image win8_share_screenshot win8_share_file ' + + 'win8_share_url win8_share_text win8_search_enable ' + + 'win8_search_disable win8_search_add_suggestions ' + + 'win8_device_touchscreen_available win8_license_initialize_sandbox ' + + 'win8_license_trial_version winphone_license_trial_version ' + + 'winphone_tile_title winphone_tile_count winphone_tile_back_title ' + + 'winphone_tile_back_content winphone_tile_back_content_wide ' + + 'winphone_tile_front_image winphone_tile_front_image_small ' + + 'winphone_tile_front_image_wide winphone_tile_back_image ' + + 'winphone_tile_back_image_wide winphone_tile_background_colour ' + + 'winphone_tile_background_color winphone_tile_icon_image ' + + 'winphone_tile_small_icon_image winphone_tile_wide_content ' + + 'winphone_tile_cycle_images winphone_tile_small_background_image ' + + 'physics_world_create physics_world_gravity ' + + 'physics_world_update_speed physics_world_update_iterations ' + + 'physics_world_draw_debug physics_pause_enable physics_fixture_create ' + + 'physics_fixture_set_kinematic physics_fixture_set_density ' + + 'physics_fixture_set_awake physics_fixture_set_restitution ' + + 'physics_fixture_set_friction physics_fixture_set_collision_group ' + + 'physics_fixture_set_sensor physics_fixture_set_linear_damping ' + + 'physics_fixture_set_angular_damping physics_fixture_set_circle_shape ' + + 'physics_fixture_set_box_shape physics_fixture_set_edge_shape ' + + 'physics_fixture_set_polygon_shape physics_fixture_set_chain_shape ' + + 'physics_fixture_add_point physics_fixture_bind ' + + 'physics_fixture_bind_ext physics_fixture_delete physics_apply_force ' + + 'physics_apply_impulse physics_apply_angular_impulse ' + + 'physics_apply_local_force physics_apply_local_impulse ' + + 'physics_apply_torque physics_mass_properties physics_draw_debug ' + + 'physics_test_overlap physics_remove_fixture physics_set_friction ' + + 'physics_set_density physics_set_restitution physics_get_friction ' + + 'physics_get_density physics_get_restitution ' + + 'physics_joint_distance_create physics_joint_rope_create ' + + 'physics_joint_revolute_create physics_joint_prismatic_create ' + + 'physics_joint_pulley_create physics_joint_wheel_create ' + + 'physics_joint_weld_create physics_joint_friction_create ' + + 'physics_joint_gear_create physics_joint_enable_motor ' + + 'physics_joint_get_value physics_joint_set_value physics_joint_delete ' + + 'physics_particle_create physics_particle_delete ' + + 'physics_particle_delete_region_circle ' + + 'physics_particle_delete_region_box ' + + 'physics_particle_delete_region_poly physics_particle_set_flags ' + + 'physics_particle_set_category_flags physics_particle_draw ' + + 'physics_particle_draw_ext physics_particle_count ' + + 'physics_particle_get_data physics_particle_get_data_particle ' + + 'physics_particle_group_begin physics_particle_group_circle ' + + 'physics_particle_group_box physics_particle_group_polygon ' + + 'physics_particle_group_add_point physics_particle_group_end ' + + 'physics_particle_group_join physics_particle_group_delete ' + + 'physics_particle_group_count physics_particle_group_get_data ' + + 'physics_particle_group_get_mass physics_particle_group_get_inertia ' + + 'physics_particle_group_get_centre_x ' + + 'physics_particle_group_get_centre_y physics_particle_group_get_vel_x ' + + 'physics_particle_group_get_vel_y physics_particle_group_get_ang_vel ' + + 'physics_particle_group_get_x physics_particle_group_get_y ' + + 'physics_particle_group_get_angle physics_particle_set_group_flags ' + + 'physics_particle_get_group_flags physics_particle_get_max_count ' + + 'physics_particle_get_radius physics_particle_get_density ' + + 'physics_particle_get_damping physics_particle_get_gravity_scale ' + + 'physics_particle_set_max_count physics_particle_set_radius ' + + 'physics_particle_set_density physics_particle_set_damping ' + + 'physics_particle_set_gravity_scale network_create_socket ' + + 'network_create_socket_ext network_create_server ' + + 'network_create_server_raw network_connect network_connect_raw ' + + 'network_send_packet network_send_raw network_send_broadcast ' + + 'network_send_udp network_send_udp_raw network_set_timeout ' + + 'network_set_config network_resolve network_destroy buffer_create ' + + 'buffer_write buffer_read buffer_seek buffer_get_surface ' + + 'buffer_set_surface buffer_delete buffer_exists buffer_get_type ' + + 'buffer_get_alignment buffer_poke buffer_peek buffer_save ' + + 'buffer_save_ext buffer_load buffer_load_ext buffer_load_partial ' + + 'buffer_copy buffer_fill buffer_get_size buffer_tell buffer_resize ' + + 'buffer_md5 buffer_sha1 buffer_base64_encode buffer_base64_decode ' + + 'buffer_base64_decode_ext buffer_sizeof buffer_get_address ' + + 'buffer_create_from_vertex_buffer ' + + 'buffer_create_from_vertex_buffer_ext buffer_copy_from_vertex_buffer ' + + 'buffer_async_group_begin buffer_async_group_option ' + + 'buffer_async_group_end buffer_load_async buffer_save_async ' + + 'gml_release_mode gml_pragma steam_activate_overlay ' + + 'steam_is_overlay_enabled steam_is_overlay_activated ' + + 'steam_get_persona_name steam_initialised ' + + 'steam_is_cloud_enabled_for_app steam_is_cloud_enabled_for_account ' + + 'steam_file_persisted steam_get_quota_total steam_get_quota_free ' + + 'steam_file_write steam_file_write_file steam_file_read ' + + 'steam_file_delete steam_file_exists steam_file_size steam_file_share ' + + 'steam_is_screenshot_requested steam_send_screenshot ' + + 'steam_is_user_logged_on steam_get_user_steam_id steam_user_owns_dlc ' + + 'steam_user_installed_dlc steam_set_achievement steam_get_achievement ' + + 'steam_clear_achievement steam_set_stat_int steam_set_stat_float ' + + 'steam_set_stat_avg_rate steam_get_stat_int steam_get_stat_float ' + + 'steam_get_stat_avg_rate steam_reset_all_stats ' + + 'steam_reset_all_stats_achievements steam_stats_ready ' + + 'steam_create_leaderboard steam_upload_score steam_upload_score_ext ' + + 'steam_download_scores_around_user steam_download_scores ' + + 'steam_download_friends_scores steam_upload_score_buffer ' + + 'steam_upload_score_buffer_ext steam_current_game_language ' + + 'steam_available_languages steam_activate_overlay_browser ' + + 'steam_activate_overlay_user steam_activate_overlay_store ' + + 'steam_get_user_persona_name steam_get_app_id ' + + 'steam_get_user_account_id steam_ugc_download steam_ugc_create_item ' + + 'steam_ugc_start_item_update steam_ugc_set_item_title ' + + 'steam_ugc_set_item_description steam_ugc_set_item_visibility ' + + 'steam_ugc_set_item_tags steam_ugc_set_item_content ' + + 'steam_ugc_set_item_preview steam_ugc_submit_item_update ' + + 'steam_ugc_get_item_update_progress steam_ugc_subscribe_item ' + + 'steam_ugc_unsubscribe_item steam_ugc_num_subscribed_items ' + + 'steam_ugc_get_subscribed_items steam_ugc_get_item_install_info ' + + 'steam_ugc_get_item_update_info steam_ugc_request_item_details ' + + 'steam_ugc_create_query_user steam_ugc_create_query_user_ex ' + + 'steam_ugc_create_query_all steam_ugc_create_query_all_ex ' + + 'steam_ugc_query_set_cloud_filename_filter ' + + 'steam_ugc_query_set_match_any_tag steam_ugc_query_set_search_text ' + + 'steam_ugc_query_set_ranked_by_trend_days ' + + 'steam_ugc_query_add_required_tag steam_ugc_query_add_excluded_tag ' + + 'steam_ugc_query_set_return_long_description ' + + 'steam_ugc_query_set_return_total_only ' + + 'steam_ugc_query_set_allow_cached_response steam_ugc_send_query ' + + 'shader_set shader_get_name shader_reset shader_current ' + + 'shader_is_compiled shader_get_sampler_index shader_get_uniform ' + + 'shader_set_uniform_i shader_set_uniform_i_array shader_set_uniform_f ' + + 'shader_set_uniform_f_array shader_set_uniform_matrix ' + + 'shader_set_uniform_matrix_array shader_enable_corner_id ' + + 'texture_set_stage texture_get_texel_width texture_get_texel_height ' + + 'shaders_are_supported vertex_format_begin vertex_format_end ' + + 'vertex_format_delete vertex_format_add_position ' + + 'vertex_format_add_position_3d vertex_format_add_colour ' + + 'vertex_format_add_color vertex_format_add_normal ' + + 'vertex_format_add_texcoord vertex_format_add_textcoord ' + + 'vertex_format_add_custom vertex_create_buffer ' + + 'vertex_create_buffer_ext vertex_delete_buffer vertex_begin ' + + 'vertex_end vertex_position vertex_position_3d vertex_colour ' + + 'vertex_color vertex_argb vertex_texcoord vertex_normal vertex_float1 ' + + 'vertex_float2 vertex_float3 vertex_float4 vertex_ubyte4 ' + + 'vertex_submit vertex_freeze vertex_get_number vertex_get_buffer_size ' + + 'vertex_create_buffer_from_buffer ' + + 'vertex_create_buffer_from_buffer_ext push_local_notification ' + + 'push_get_first_local_notification push_get_next_local_notification ' + + 'push_cancel_local_notification skeleton_animation_set ' + + 'skeleton_animation_get skeleton_animation_mix ' + + 'skeleton_animation_set_ext skeleton_animation_get_ext ' + + 'skeleton_animation_get_duration skeleton_animation_get_frames ' + + 'skeleton_animation_clear skeleton_skin_set skeleton_skin_get ' + + 'skeleton_attachment_set skeleton_attachment_get ' + + 'skeleton_attachment_create skeleton_collision_draw_set ' + + 'skeleton_bone_data_get skeleton_bone_data_set ' + + 'skeleton_bone_state_get skeleton_bone_state_set skeleton_get_minmax ' + + 'skeleton_get_num_bounds skeleton_get_bounds ' + + 'skeleton_animation_get_frame skeleton_animation_set_frame ' + + 'draw_skeleton draw_skeleton_time draw_skeleton_instance ' + + 'draw_skeleton_collision skeleton_animation_list skeleton_skin_list ' + + 'skeleton_slot_data layer_get_id layer_get_id_at_depth ' + + 'layer_get_depth layer_create layer_destroy layer_destroy_instances ' + + 'layer_add_instance layer_has_instance layer_set_visible ' + + 'layer_get_visible layer_exists layer_x layer_y layer_get_x ' + + 'layer_get_y layer_hspeed layer_vspeed layer_get_hspeed ' + + 'layer_get_vspeed layer_script_begin layer_script_end layer_shader ' + + 'layer_get_script_begin layer_get_script_end layer_get_shader ' + + 'layer_set_target_room layer_get_target_room layer_reset_target_room ' + + 'layer_get_all layer_get_all_elements layer_get_name layer_depth ' + + 'layer_get_element_layer layer_get_element_type layer_element_move ' + + 'layer_force_draw_depth layer_is_draw_depth_forced ' + + 'layer_get_forced_depth layer_background_get_id ' + + 'layer_background_exists layer_background_create ' + + 'layer_background_destroy layer_background_visible ' + + 'layer_background_change layer_background_sprite ' + + 'layer_background_htiled layer_background_vtiled ' + + 'layer_background_stretch layer_background_yscale ' + + 'layer_background_xscale layer_background_blend ' + + 'layer_background_alpha layer_background_index layer_background_speed ' + + 'layer_background_get_visible layer_background_get_sprite ' + + 'layer_background_get_htiled layer_background_get_vtiled ' + + 'layer_background_get_stretch layer_background_get_yscale ' + + 'layer_background_get_xscale layer_background_get_blend ' + + 'layer_background_get_alpha layer_background_get_index ' + + 'layer_background_get_speed layer_sprite_get_id layer_sprite_exists ' + + 'layer_sprite_create layer_sprite_destroy layer_sprite_change ' + + 'layer_sprite_index layer_sprite_speed layer_sprite_xscale ' + + 'layer_sprite_yscale layer_sprite_angle layer_sprite_blend ' + + 'layer_sprite_alpha layer_sprite_x layer_sprite_y ' + + 'layer_sprite_get_sprite layer_sprite_get_index ' + + 'layer_sprite_get_speed layer_sprite_get_xscale ' + + 'layer_sprite_get_yscale layer_sprite_get_angle ' + + 'layer_sprite_get_blend layer_sprite_get_alpha layer_sprite_get_x ' + + 'layer_sprite_get_y layer_tilemap_get_id layer_tilemap_exists ' + + 'layer_tilemap_create layer_tilemap_destroy tilemap_tileset tilemap_x ' + + 'tilemap_y tilemap_set tilemap_set_at_pixel tilemap_get_tileset ' + + 'tilemap_get_tile_width tilemap_get_tile_height tilemap_get_width ' + + 'tilemap_get_height tilemap_get_x tilemap_get_y tilemap_get ' + + 'tilemap_get_at_pixel tilemap_get_cell_x_at_pixel ' + + 'tilemap_get_cell_y_at_pixel tilemap_clear draw_tilemap draw_tile ' + + 'tilemap_set_global_mask tilemap_get_global_mask tilemap_set_mask ' + + 'tilemap_get_mask tilemap_get_frame tile_set_empty tile_set_index ' + + 'tile_set_flip tile_set_mirror tile_set_rotate tile_get_empty ' + + 'tile_get_index tile_get_flip tile_get_mirror tile_get_rotate ' + + 'layer_tile_exists layer_tile_create layer_tile_destroy ' + + 'layer_tile_change layer_tile_xscale layer_tile_yscale ' + + 'layer_tile_blend layer_tile_alpha layer_tile_x layer_tile_y ' + + 'layer_tile_region layer_tile_visible layer_tile_get_sprite ' + + 'layer_tile_get_xscale layer_tile_get_yscale layer_tile_get_blend ' + + 'layer_tile_get_alpha layer_tile_get_x layer_tile_get_y ' + + 'layer_tile_get_region layer_tile_get_visible ' + + 'layer_instance_get_instance instance_activate_layer ' + + 'instance_deactivate_layer camera_create camera_create_view ' + + 'camera_destroy camera_apply camera_get_active camera_get_default ' + + 'camera_set_default camera_set_view_mat camera_set_proj_mat ' + + 'camera_set_update_script camera_set_begin_script ' + + 'camera_set_end_script camera_set_view_pos camera_set_view_size ' + + 'camera_set_view_speed camera_set_view_border camera_set_view_angle ' + + 'camera_set_view_target camera_get_view_mat camera_get_proj_mat ' + + 'camera_get_update_script camera_get_begin_script ' + + 'camera_get_end_script camera_get_view_x camera_get_view_y ' + + 'camera_get_view_width camera_get_view_height camera_get_view_speed_x ' + + 'camera_get_view_speed_y camera_get_view_border_x ' + + 'camera_get_view_border_y camera_get_view_angle ' + + 'camera_get_view_target view_get_camera view_get_visible ' + + 'view_get_xport view_get_yport view_get_wport view_get_hport ' + + 'view_get_surface_id view_set_camera view_set_visible view_set_xport ' + + 'view_set_yport view_set_wport view_set_hport view_set_surface_id ' + + 'gesture_drag_time gesture_drag_distance gesture_flick_speed ' + + 'gesture_double_tap_time gesture_double_tap_distance ' + + 'gesture_pinch_distance gesture_pinch_angle_towards ' + + 'gesture_pinch_angle_away gesture_rotate_time gesture_rotate_angle ' + + 'gesture_tap_count gesture_get_drag_time gesture_get_drag_distance ' + + 'gesture_get_flick_speed gesture_get_double_tap_time ' + + 'gesture_get_double_tap_distance gesture_get_pinch_distance ' + + 'gesture_get_pinch_angle_towards gesture_get_pinch_angle_away ' + + 'gesture_get_rotate_time gesture_get_rotate_angle ' + + 'gesture_get_tap_count keyboard_virtual_show keyboard_virtual_hide ' + + 'keyboard_virtual_status keyboard_virtual_height', + literal: 'self other all noone global local undefined pointer_invalid ' + + 'pointer_null path_action_stop path_action_restart ' + + 'path_action_continue path_action_reverse true false pi GM_build_date ' + + 'GM_version GM_runtime_version timezone_local timezone_utc ' + + 'gamespeed_fps gamespeed_microseconds ev_create ev_destroy ev_step ' + + 'ev_alarm ev_keyboard ev_mouse ev_collision ev_other ev_draw ' + + 'ev_draw_begin ev_draw_end ev_draw_pre ev_draw_post ev_keypress ' + + 'ev_keyrelease ev_trigger ev_left_button ev_right_button ' + + 'ev_middle_button ev_no_button ev_left_press ev_right_press ' + + 'ev_middle_press ev_left_release ev_right_release ev_middle_release ' + + 'ev_mouse_enter ev_mouse_leave ev_mouse_wheel_up ev_mouse_wheel_down ' + + 'ev_global_left_button ev_global_right_button ev_global_middle_button ' + + 'ev_global_left_press ev_global_right_press ev_global_middle_press ' + + 'ev_global_left_release ev_global_right_release ' + + 'ev_global_middle_release ev_joystick1_left ev_joystick1_right ' + + 'ev_joystick1_up ev_joystick1_down ev_joystick1_button1 ' + + 'ev_joystick1_button2 ev_joystick1_button3 ev_joystick1_button4 ' + + 'ev_joystick1_button5 ev_joystick1_button6 ev_joystick1_button7 ' + + 'ev_joystick1_button8 ev_joystick2_left ev_joystick2_right ' + + 'ev_joystick2_up ev_joystick2_down ev_joystick2_button1 ' + + 'ev_joystick2_button2 ev_joystick2_button3 ev_joystick2_button4 ' + + 'ev_joystick2_button5 ev_joystick2_button6 ev_joystick2_button7 ' + + 'ev_joystick2_button8 ev_outside ev_boundary ev_game_start ' + + 'ev_game_end ev_room_start ev_room_end ev_no_more_lives ' + + 'ev_animation_end ev_end_of_path ev_no_more_health ev_close_button ' + + 'ev_user0 ev_user1 ev_user2 ev_user3 ev_user4 ev_user5 ev_user6 ' + + 'ev_user7 ev_user8 ev_user9 ev_user10 ev_user11 ev_user12 ev_user13 ' + + 'ev_user14 ev_user15 ev_step_normal ev_step_begin ev_step_end ev_gui ' + + 'ev_gui_begin ev_gui_end ev_cleanup ev_gesture ev_gesture_tap ' + + 'ev_gesture_double_tap ev_gesture_drag_start ev_gesture_dragging ' + + 'ev_gesture_drag_end ev_gesture_flick ev_gesture_pinch_start ' + + 'ev_gesture_pinch_in ev_gesture_pinch_out ev_gesture_pinch_end ' + + 'ev_gesture_rotate_start ev_gesture_rotating ev_gesture_rotate_end ' + + 'ev_global_gesture_tap ev_global_gesture_double_tap ' + + 'ev_global_gesture_drag_start ev_global_gesture_dragging ' + + 'ev_global_gesture_drag_end ev_global_gesture_flick ' + + 'ev_global_gesture_pinch_start ev_global_gesture_pinch_in ' + + 'ev_global_gesture_pinch_out ev_global_gesture_pinch_end ' + + 'ev_global_gesture_rotate_start ev_global_gesture_rotating ' + + 'ev_global_gesture_rotate_end vk_nokey vk_anykey vk_enter vk_return ' + + 'vk_shift vk_control vk_alt vk_escape vk_space vk_backspace vk_tab ' + + 'vk_pause vk_printscreen vk_left vk_right vk_up vk_down vk_home ' + + 'vk_end vk_delete vk_insert vk_pageup vk_pagedown vk_f1 vk_f2 vk_f3 ' + + 'vk_f4 vk_f5 vk_f6 vk_f7 vk_f8 vk_f9 vk_f10 vk_f11 vk_f12 vk_numpad0 ' + + 'vk_numpad1 vk_numpad2 vk_numpad3 vk_numpad4 vk_numpad5 vk_numpad6 ' + + 'vk_numpad7 vk_numpad8 vk_numpad9 vk_divide vk_multiply vk_subtract ' + + 'vk_add vk_decimal vk_lshift vk_lcontrol vk_lalt vk_rshift ' + + 'vk_rcontrol vk_ralt mb_any mb_none mb_left mb_right mb_middle ' + + 'c_aqua c_black c_blue c_dkgray c_fuchsia c_gray c_green c_lime ' + + 'c_ltgray c_maroon c_navy c_olive c_purple c_red c_silver c_teal ' + + 'c_white c_yellow c_orange fa_left fa_center fa_right fa_top ' + + 'fa_middle fa_bottom pr_pointlist pr_linelist pr_linestrip ' + + 'pr_trianglelist pr_trianglestrip pr_trianglefan bm_complex bm_normal ' + + 'bm_add bm_max bm_subtract bm_zero bm_one bm_src_colour ' + + 'bm_inv_src_colour bm_src_color bm_inv_src_color bm_src_alpha ' + + 'bm_inv_src_alpha bm_dest_alpha bm_inv_dest_alpha bm_dest_colour ' + + 'bm_inv_dest_colour bm_dest_color bm_inv_dest_color bm_src_alpha_sat ' + + 'tf_point tf_linear tf_anisotropic mip_off mip_on mip_markedonly ' + + 'audio_falloff_none audio_falloff_inverse_distance ' + + 'audio_falloff_inverse_distance_clamped audio_falloff_linear_distance ' + + 'audio_falloff_linear_distance_clamped ' + + 'audio_falloff_exponent_distance ' + + 'audio_falloff_exponent_distance_clamped audio_old_system ' + + 'audio_new_system audio_mono audio_stereo audio_3d cr_default cr_none ' + + 'cr_arrow cr_cross cr_beam cr_size_nesw cr_size_ns cr_size_nwse ' + + 'cr_size_we cr_uparrow cr_hourglass cr_drag cr_appstart cr_handpoint ' + + 'cr_size_all spritespeed_framespersecond ' + + 'spritespeed_framespergameframe asset_object asset_unknown ' + + 'asset_sprite asset_sound asset_room asset_path asset_script ' + + 'asset_font asset_timeline asset_tiles asset_shader fa_readonly ' + + 'fa_hidden fa_sysfile fa_volumeid fa_directory fa_archive ' + + 'ds_type_map ds_type_list ds_type_stack ds_type_queue ds_type_grid ' + + 'ds_type_priority ef_explosion ef_ring ef_ellipse ef_firework ' + + 'ef_smoke ef_smokeup ef_star ef_spark ef_flare ef_cloud ef_rain ' + + 'ef_snow pt_shape_pixel pt_shape_disk pt_shape_square pt_shape_line ' + + 'pt_shape_star pt_shape_circle pt_shape_ring pt_shape_sphere ' + + 'pt_shape_flare pt_shape_spark pt_shape_explosion pt_shape_cloud ' + + 'pt_shape_smoke pt_shape_snow ps_distr_linear ps_distr_gaussian ' + + 'ps_distr_invgaussian ps_shape_rectangle ps_shape_ellipse ' + + 'ps_shape_diamond ps_shape_line ty_real ty_string dll_cdecl ' + + 'dll_stdcall matrix_view matrix_projection matrix_world os_win32 ' + + 'os_windows os_macosx os_ios os_android os_symbian os_linux ' + + 'os_unknown os_winphone os_tizen os_win8native ' + + 'os_wiiu os_3ds os_psvita os_bb10 os_ps4 os_xboxone ' + + 'os_ps3 os_xbox360 os_uwp os_tvos os_switch ' + + 'browser_not_a_browser browser_unknown browser_ie browser_firefox ' + + 'browser_chrome browser_safari browser_safari_mobile browser_opera ' + + 'browser_tizen browser_edge browser_windows_store browser_ie_mobile ' + + 'device_ios_unknown device_ios_iphone device_ios_iphone_retina ' + + 'device_ios_ipad device_ios_ipad_retina device_ios_iphone5 ' + + 'device_ios_iphone6 device_ios_iphone6plus device_emulator ' + + 'device_tablet display_landscape display_landscape_flipped ' + + 'display_portrait display_portrait_flipped tm_sleep tm_countvsyncs ' + + 'of_challenge_win of_challen ge_lose of_challenge_tie ' + + 'leaderboard_type_number leaderboard_type_time_mins_secs ' + + 'cmpfunc_never cmpfunc_less cmpfunc_equal cmpfunc_lessequal ' + + 'cmpfunc_greater cmpfunc_notequal cmpfunc_greaterequal cmpfunc_always ' + + 'cull_noculling cull_clockwise cull_counterclockwise lighttype_dir ' + + 'lighttype_point iap_ev_storeload iap_ev_product iap_ev_purchase ' + + 'iap_ev_consume iap_ev_restore iap_storeload_ok iap_storeload_failed ' + + 'iap_status_uninitialised iap_status_unavailable iap_status_loading ' + + 'iap_status_available iap_status_processing iap_status_restoring ' + + 'iap_failed iap_unavailable iap_available iap_purchased iap_canceled ' + + 'iap_refunded fb_login_default fb_login_fallback_to_webview ' + + 'fb_login_no_fallback_to_webview fb_login_forcing_webview ' + + 'fb_login_use_system_account fb_login_forcing_safari ' + + 'phy_joint_anchor_1_x phy_joint_anchor_1_y phy_joint_anchor_2_x ' + + 'phy_joint_anchor_2_y phy_joint_reaction_force_x ' + + 'phy_joint_reaction_force_y phy_joint_reaction_torque ' + + 'phy_joint_motor_speed phy_joint_angle phy_joint_motor_torque ' + + 'phy_joint_max_motor_torque phy_joint_translation phy_joint_speed ' + + 'phy_joint_motor_force phy_joint_max_motor_force phy_joint_length_1 ' + + 'phy_joint_length_2 phy_joint_damping_ratio phy_joint_frequency ' + + 'phy_joint_lower_angle_limit phy_joint_upper_angle_limit ' + + 'phy_joint_angle_limits phy_joint_max_length phy_joint_max_torque ' + + 'phy_joint_max_force phy_debug_render_aabb ' + + 'phy_debug_render_collision_pairs phy_debug_render_coms ' + + 'phy_debug_render_core_shapes phy_debug_render_joints ' + + 'phy_debug_render_obb phy_debug_render_shapes ' + + 'phy_particle_flag_water phy_particle_flag_zombie ' + + 'phy_particle_flag_wall phy_particle_flag_spring ' + + 'phy_particle_flag_elastic phy_particle_flag_viscous ' + + 'phy_particle_flag_powder phy_particle_flag_tensile ' + + 'phy_particle_flag_colourmixing phy_particle_flag_colormixing ' + + 'phy_particle_group_flag_solid phy_particle_group_flag_rigid ' + + 'phy_particle_data_flag_typeflags phy_particle_data_flag_position ' + + 'phy_particle_data_flag_velocity phy_particle_data_flag_colour ' + + 'phy_particle_data_flag_color phy_particle_data_flag_category ' + + 'achievement_our_info achievement_friends_info ' + + 'achievement_leaderboard_info achievement_achievement_info ' + + 'achievement_filter_all_players achievement_filter_friends_only ' + + 'achievement_filter_favorites_only ' + + 'achievement_type_achievement_challenge ' + + 'achievement_type_score_challenge achievement_pic_loaded ' + + 'achievement_show_ui achievement_show_profile ' + + 'achievement_show_leaderboard achievement_show_achievement ' + + 'achievement_show_bank achievement_show_friend_picker ' + + 'achievement_show_purchase_prompt network_socket_tcp ' + + 'network_socket_udp network_socket_bluetooth network_type_connect ' + + 'network_type_disconnect network_type_data ' + + 'network_type_non_blocking_connect network_config_connect_timeout ' + + 'network_config_use_non_blocking_socket ' + + 'network_config_enable_reliable_udp ' + + 'network_config_disable_reliable_udp buffer_fixed buffer_grow ' + + 'buffer_wrap buffer_fast buffer_vbuffer buffer_network buffer_u8 ' + + 'buffer_s8 buffer_u16 buffer_s16 buffer_u32 buffer_s32 buffer_u64 ' + + 'buffer_f16 buffer_f32 buffer_f64 buffer_bool buffer_text ' + + 'buffer_string buffer_surface_copy buffer_seek_start ' + + 'buffer_seek_relative buffer_seek_end ' + + 'buffer_generalerror buffer_outofspace buffer_outofbounds ' + + 'buffer_invalidtype text_type button_type input_type ANSI_CHARSET ' + + 'DEFAULT_CHARSET EASTEUROPE_CHARSET RUSSIAN_CHARSET SYMBOL_CHARSET ' + + 'SHIFTJIS_CHARSET HANGEUL_CHARSET GB2312_CHARSET CHINESEBIG5_CHARSET ' + + 'JOHAB_CHARSET HEBREW_CHARSET ARABIC_CHARSET GREEK_CHARSET ' + + 'TURKISH_CHARSET VIETNAMESE_CHARSET THAI_CHARSET MAC_CHARSET ' + + 'BALTIC_CHARSET OEM_CHARSET gp_face1 gp_face2 gp_face3 gp_face4 ' + + 'gp_shoulderl gp_shoulderr gp_shoulderlb gp_shoulderrb gp_select ' + + 'gp_start gp_stickl gp_stickr gp_padu gp_padd gp_padl gp_padr ' + + 'gp_axislh gp_axislv gp_axisrh gp_axisrv ov_friends ov_community ' + + 'ov_players ov_settings ov_gamegroup ov_achievements lb_sort_none ' + + 'lb_sort_ascending lb_sort_descending lb_disp_none lb_disp_numeric ' + + 'lb_disp_time_sec lb_disp_time_ms ugc_result_success ' + + 'ugc_filetype_community ugc_filetype_microtrans ugc_visibility_public ' + + 'ugc_visibility_friends_only ugc_visibility_private ' + + 'ugc_query_RankedByVote ugc_query_RankedByPublicationDate ' + + 'ugc_query_AcceptedForGameRankedByAcceptanceDate ' + + 'ugc_query_RankedByTrend ' + + 'ugc_query_FavoritedByFriendsRankedByPublicationDate ' + + 'ugc_query_CreatedByFriendsRankedByPublicationDate ' + + 'ugc_query_RankedByNumTimesReported ' + + 'ugc_query_CreatedByFollowedUsersRankedByPublicationDate ' + + 'ugc_query_NotYetRated ugc_query_RankedByTotalVotesAsc ' + + 'ugc_query_RankedByVotesUp ugc_query_RankedByTextSearch ' + + 'ugc_sortorder_CreationOrderDesc ugc_sortorder_CreationOrderAsc ' + + 'ugc_sortorder_TitleAsc ugc_sortorder_LastUpdatedDesc ' + + 'ugc_sortorder_SubscriptionDateDesc ugc_sortorder_VoteScoreDesc ' + + 'ugc_sortorder_ForModeration ugc_list_Published ugc_list_VotedOn ' + + 'ugc_list_VotedUp ugc_list_VotedDown ugc_list_WillVoteLater ' + + 'ugc_list_Favorited ugc_list_Subscribed ugc_list_UsedOrPlayed ' + + 'ugc_list_Followed ugc_match_Items ugc_match_Items_Mtx ' + + 'ugc_match_Items_ReadyToUse ugc_match_Collections ugc_match_Artwork ' + + 'ugc_match_Videos ugc_match_Screenshots ugc_match_AllGuides ' + + 'ugc_match_WebGuides ugc_match_IntegratedGuides ' + + 'ugc_match_UsableInGame ugc_match_ControllerBindings ' + + 'vertex_usage_position vertex_usage_colour vertex_usage_color ' + + 'vertex_usage_normal vertex_usage_texcoord vertex_usage_textcoord ' + + 'vertex_usage_blendweight vertex_usage_blendindices ' + + 'vertex_usage_psize vertex_usage_tangent vertex_usage_binormal ' + + 'vertex_usage_fog vertex_usage_depth vertex_usage_sample ' + + 'vertex_type_float1 vertex_type_float2 vertex_type_float3 ' + + 'vertex_type_float4 vertex_type_colour vertex_type_color ' + + 'vertex_type_ubyte4 layerelementtype_undefined ' + + 'layerelementtype_background layerelementtype_instance ' + + 'layerelementtype_oldtilemap layerelementtype_sprite ' + + 'layerelementtype_tilemap layerelementtype_particlesystem ' + + 'layerelementtype_tile tile_rotate tile_flip tile_mirror ' + + 'tile_index_mask kbv_type_default kbv_type_ascii kbv_type_url ' + + 'kbv_type_email kbv_type_numbers kbv_type_phone kbv_type_phone_name ' + + 'kbv_returnkey_default kbv_returnkey_go kbv_returnkey_google ' + + 'kbv_returnkey_join kbv_returnkey_next kbv_returnkey_route ' + + 'kbv_returnkey_search kbv_returnkey_send kbv_returnkey_yahoo ' + + 'kbv_returnkey_done kbv_returnkey_continue kbv_returnkey_emergency ' + + 'kbv_autocapitalize_none kbv_autocapitalize_words ' + + 'kbv_autocapitalize_sentences kbv_autocapitalize_characters', + symbol: 'argument_relative argument argument0 argument1 argument2 ' + + 'argument3 argument4 argument5 argument6 argument7 argument8 ' + + 'argument9 argument10 argument11 argument12 argument13 argument14 ' + + 'argument15 argument_count x|0 y|0 xprevious yprevious xstart ystart ' + + 'hspeed vspeed direction speed friction gravity gravity_direction ' + + 'path_index path_position path_positionprevious path_speed ' + + 'path_scale path_orientation path_endaction object_index id solid ' + + 'persistent mask_index instance_count instance_id room_speed fps ' + + 'fps_real current_time current_year current_month current_day ' + + 'current_weekday current_hour current_minute current_second alarm ' + + 'timeline_index timeline_position timeline_speed timeline_running ' + + 'timeline_loop room room_first room_last room_width room_height ' + + 'room_caption room_persistent score lives health show_score ' + + 'show_lives show_health caption_score caption_lives caption_health ' + + 'event_type event_number event_object event_action ' + + 'application_surface gamemaker_pro gamemaker_registered ' + + 'gamemaker_version error_occurred error_last debug_mode ' + + 'keyboard_key keyboard_lastkey keyboard_lastchar keyboard_string ' + + 'mouse_x mouse_y mouse_button mouse_lastbutton cursor_sprite ' + + 'visible sprite_index sprite_width sprite_height sprite_xoffset ' + + 'sprite_yoffset image_number image_index image_speed depth ' + + 'image_xscale image_yscale image_angle image_alpha image_blend ' + + 'bbox_left bbox_right bbox_top bbox_bottom layer background_colour ' + + 'background_showcolour background_color background_showcolor ' + + 'view_enabled view_current view_visible view_xview view_yview ' + + 'view_wview view_hview view_xport view_yport view_wport view_hport ' + + 'view_angle view_hborder view_vborder view_hspeed view_vspeed ' + + 'view_object view_surface_id view_camera game_id game_display_name ' + + 'game_project_name game_save_id working_directory temp_directory ' + + 'program_directory browser_width browser_height os_type os_device ' + + 'os_browser os_version display_aa async_load delta_time ' + + 'webgl_enabled event_data iap_data phy_rotation phy_position_x ' + + 'phy_position_y phy_angular_velocity phy_linear_velocity_x ' + + 'phy_linear_velocity_y phy_speed_x phy_speed_y phy_speed ' + + 'phy_angular_damping phy_linear_damping phy_bullet ' + + 'phy_fixed_rotation phy_active phy_mass phy_inertia phy_com_x ' + + 'phy_com_y phy_dynamic phy_kinematic phy_sleeping ' + + 'phy_collision_points phy_collision_x phy_collision_y ' + + 'phy_col_normal_x phy_col_normal_y phy_position_xprevious ' + + 'phy_position_yprevious' + }; + + return { + name: 'GML', + case_insensitive: false, // language is case-insensitive + keywords: GML_KEYWORDS, + + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = gml; + + +/***/ }), + +/***/ 46831: +/***/ ((module) => { + +/* +Language: Golo +Author: Philippe Charriere +Description: a lightweight dynamic language for the JVM +Website: http://golo-lang.org/ +*/ + +function golo(hljs) { + return { + name: 'Golo', + keywords: { + keyword: + 'println readln print import module function local return let var ' + + 'while for foreach times in case when match with break continue ' + + 'augment augmentation each find filter reduce ' + + 'if then else otherwise try catch finally raise throw orIfNull ' + + 'DynamicObject|10 DynamicVariable struct Observable map set vector list array', + literal: + 'true false null' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '@[A-Za-z]+' + } + ] + }; +} + +module.exports = golo; + + +/***/ }), + +/***/ 41787: +/***/ ((module) => { + +/* +Language: Gradle +Description: Gradle is an open-source build automation tool focused on flexibility and performance. +Website: https://gradle.org +Author: Damian Mee +*/ + +function gradle(hljs) { + return { + name: 'Gradle', + case_insensitive: true, + keywords: { + keyword: + 'task project allprojects subprojects artifacts buildscript configurations ' + + 'dependencies repositories sourceSets description delete from into include ' + + 'exclude source classpath destinationDir includes options sourceCompatibility ' + + 'targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant ' + + 'def abstract break case catch continue default do else extends final finally ' + + 'for if implements instanceof native new private protected public return static ' + + 'switch synchronized throw throws transient try volatile while strictfp package ' + + 'import false null super this true antlrtask checkstyle codenarc copy boolean ' + + 'byte char class double float int interface long short void compile runTime ' + + 'file fileTree abs any append asList asWritable call collect compareTo count ' + + 'div dump each eachByte eachFile eachLine every find findAll flatten getAt ' + + 'getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods ' + + 'isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter ' + + 'newReader newWriter next plus pop power previous print println push putAt read ' + + 'readBytes readLines reverse reverseEach round size sort splitEachLine step subMap ' + + 'times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader ' + + 'withStream withWriter withWriterAppend write writeLine' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.REGEXP_MODE + + ] + }; +} + +module.exports = gradle; + + +/***/ }), + +/***/ 90458: +/***/ ((module) => { + +/* +Language: HAML +Requires: ruby.js +Author: Dan Allen +Website: http://haml.info +Category: template +*/ + +// TODO support filter tags like :javascript, support inline HTML +function haml(hljs) { + return { + name: 'HAML', + case_insensitive: true, + contains: [ + { + className: 'meta', + begin: '^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$', + relevance: 10 + }, + // FIXME these comments should be allowed to span indented lines + hljs.COMMENT( + '^\\s*(!=#|=#|-#|/).*$', + false, + { + relevance: 0 + } + ), + { + begin: '^\\s*(-|=|!=)(?!#)', + starts: { + end: '\\n', + subLanguage: 'ruby' + } + }, + { + className: 'tag', + begin: '^\\s*%', + contains: [ + { + className: 'selector-tag', + begin: '\\w+' + }, + { + className: 'selector-id', + begin: '#[\\w-]+' + }, + { + className: 'selector-class', + begin: '\\.[\\w-]+' + }, + { + begin: /\{\s*/, + end: /\s*\}/, + contains: [ + { + begin: ':\\w+\\s*=>', + end: ',\\s+', + returnBegin: true, + endsWithParent: true, + contains: [ + { + className: 'attr', + begin: ':\\w+' + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '\\w+', + relevance: 0 + } + ] + } + ] + }, + { + begin: '\\(\\s*', + end: '\\s*\\)', + excludeEnd: true, + contains: [ + { + begin: '\\w+\\s*=', + end: '\\s+', + returnBegin: true, + endsWithParent: true, + contains: [ + { + className: 'attr', + begin: '\\w+', + relevance: 0 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + begin: '\\w+', + relevance: 0 + } + ] + } + ] + } + ] + }, + { + begin: '^\\s*[=~]\\s*' + }, + { + begin: /#\{/, + starts: { + end: /\}/, + subLanguage: 'ruby' + } + } + ] + }; +} + +module.exports = haml; + + +/***/ }), + +/***/ 77168: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Handlebars +Requires: xml.js +Author: Robin Ward +Description: Matcher for Handlebars as well as EmberJS additions. +Website: https://handlebarsjs.com +Category: template +*/ + +function handlebars(hljs) { + const BUILT_INS = { + 'builtin-name': [ + 'action', + 'bindattr', + 'collection', + 'component', + 'concat', + 'debugger', + 'each', + 'each-in', + 'get', + 'hash', + 'if', + 'in', + 'input', + 'link-to', + 'loc', + 'log', + 'lookup', + 'mut', + 'outlet', + 'partial', + 'query-params', + 'render', + 'template', + 'textarea', + 'unbound', + 'unless', + 'view', + 'with', + 'yield' + ] + }; + + const LITERALS = { + literal: [ + 'true', + 'false', + 'undefined', + 'null' + ] + }; + + // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments + // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths + // like a/b, ./abc/cde, and abc.bcd + + const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/; + const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/; + const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/; + const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/; + const PATH_DELIMITER_REGEX = /(\.|\/)/; + const ANY_ID = either( + DOUBLE_QUOTED_ID_REGEX, + SINGLE_QUOTED_ID_REGEX, + BRACKET_QUOTED_ID_REGEX, + PLAIN_ID_REGEX + ); + + const IDENTIFIER_REGEX = concat( + optional(/\.|\.\/|\//), // relative or absolute path + ANY_ID, + anyNumberOfTimes(concat( + PATH_DELIMITER_REGEX, + ANY_ID + )) + ); + + // identifier followed by a equal-sign (without the equal sign) + const HASH_PARAM_REGEX = concat( + '(', + BRACKET_QUOTED_ID_REGEX, '|', + PLAIN_ID_REGEX, + ')(?==)' + ); + + const HELPER_NAME_OR_PATH_EXPRESSION = { + begin: IDENTIFIER_REGEX, + lexemes: /[\w.\/]+/ + }; + + const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: LITERALS + }); + + const SUB_EXPRESSION = { + begin: /\(/, + end: /\)/ + // the "contains" is added below when all necessary sub-modes are defined + }; + + const HASH = { + // fka "attribute-assignment", parameters of the form 'key=value' + className: 'attr', + begin: HASH_PARAM_REGEX, + relevance: 0, + starts: { + begin: /=/, + end: /=/, + starts: { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + HELPER_PARAMETER, + SUB_EXPRESSION + ] + } + } + }; + + const BLOCK_PARAMS = { + // parameters of the form '{{#with x as | y |}}...{{/with}}' + begin: /as\s+\|/, + keywords: { + keyword: 'as' + }, + end: /\|/, + contains: [ + { + // define sub-mode in order to prevent highlighting of block-parameter named "as" + begin: /\w+/ + } + ] + }; + + const HELPER_PARAMETERS = { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BLOCK_PARAMS, + HASH, + HELPER_PARAMETER, + SUB_EXPRESSION + ], + returnEnd: true + // the property "end" is defined through inheritance when the mode is used. If depends + // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the + // end-token of the surrounding mode) + }; + + const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\)/ + }) + }); + + SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS]; + + const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name', + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name' + }); + + const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = { + begin: /\\\{\{/, + skip: true + }; + const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = { + begin: /\\\\(?=\{\{)/, + skip: true + }; + + return { + name: 'Handlebars', + aliases: [ + 'hbs', + 'html.hbs', + 'html.handlebars', + 'htmlbars' + ], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH, + PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH, + hljs.COMMENT(/\{\{!--/, /--\}\}/), + hljs.COMMENT(/\{\{!/, /\}\}/), + { + // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}" + className: 'template-tag', + begin: /\{\{\{\{(?!\/)/, + end: /\}\}\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS], + starts: { + end: /\{\{\{\{\//, + returnEnd: true, + subLanguage: 'xml' + } + }, + { + // close raw block + className: 'template-tag', + begin: /\{\{\{\{\//, + end: /\}\}\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // open block statement + className: 'template-tag', + begin: /\{\{#/, + end: /\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS] + }, + { + className: 'template-tag', + begin: /\{\{(?=else\}\})/, + end: /\}\}/, + keywords: 'else' + }, + { + className: 'template-tag', + begin: /\{\{(?=else if)/, + end: /\}\}/, + keywords: 'else if' + }, + { + // closing block statement + className: 'template-tag', + begin: /\{\{\//, + end: /\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is NOT html-escaped + className: 'template-variable', + begin: /\{\{\{/, + end: /\}\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is html-escaped + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + } + ] + }; +} + +module.exports = handlebars; + + +/***/ }), + +/***/ 84994: +/***/ ((module) => { + +/* +Language: Haskell +Author: Jeremy Hull +Contributors: Zena Treep +Website: https://www.haskell.org +Category: functional +*/ + +function haskell(hljs) { + const COMMENT = { + variants: [ + hljs.COMMENT('--', '$'), + hljs.COMMENT( + /\{-/, + /-\}/, + { + contains: ['self'] + } + ) + ] + }; + + const PRAGMA = { + className: 'meta', + begin: /\{-#/, + end: /#-\}/ + }; + + const PREPROCESSOR = { + className: 'meta', + begin: '^#', + end: '$' + }; + + const CONSTRUCTOR = { + className: 'type', + begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (build-in, infix). + relevance: 0 + }; + + const LIST = { + begin: '\\(', + end: '\\)', + illegal: '"', + contains: [ + PRAGMA, + PREPROCESSOR, + { + className: 'type', + begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?' + }, + hljs.inherit(hljs.TITLE_MODE, { + begin: '[_a-z][\\w\']*' + }), + COMMENT + ] + }; + + const RECORD = { + begin: /\{/, + end: /\}/, + contains: LIST.contains + }; + + return { + name: 'Haskell', + aliases: ['hs'], + keywords: + 'let in if then else case of where do module import hiding ' + + 'qualified type data newtype deriving class instance as default ' + + 'infix infixl infixr foreign export ccall stdcall cplusplus ' + + 'jvm dotnet safe unsafe family forall mdo proc rec', + contains: [ + // Top-level constructions. + { + beginKeywords: 'module', + end: 'where', + keywords: 'module where', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + begin: '\\bimport\\b', + end: '$', + keywords: 'import qualified as hiding', + contains: [ + LIST, + COMMENT + ], + illegal: '\\W\\.|;' + }, + { + className: 'class', + begin: '^(\\s*)?(class|instance)\\b', + end: 'where', + keywords: 'class family instance where', + contains: [ + CONSTRUCTOR, + LIST, + COMMENT + ] + }, + { + className: 'class', + begin: '\\b(data|(new)?type)\\b', + end: '$', + keywords: 'data family type newtype deriving', + contains: [ + PRAGMA, + CONSTRUCTOR, + LIST, + RECORD, + COMMENT + ] + }, + { + beginKeywords: 'default', + end: '$', + contains: [ + CONSTRUCTOR, + LIST, + COMMENT + ] + }, + { + beginKeywords: 'infix infixl infixr', + end: '$', + contains: [ + hljs.C_NUMBER_MODE, + COMMENT + ] + }, + { + begin: '\\bforeign\\b', + end: '$', + keywords: 'foreign import export ccall stdcall cplusplus jvm ' + + 'dotnet safe unsafe', + contains: [ + CONSTRUCTOR, + hljs.QUOTE_STRING_MODE, + COMMENT + ] + }, + { + className: 'meta', + begin: '#!\\/usr\\/bin\\/env\ runhaskell', + end: '$' + }, + // "Whitespaces". + PRAGMA, + PREPROCESSOR, + + // Literals and names. + + // TODO: characters. + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + CONSTRUCTOR, + hljs.inherit(hljs.TITLE_MODE, { + begin: '^[_a-z][\\w\']*' + }), + COMMENT, + { // No markup, relevance booster + begin: '->|<-' + } + ] + }; +} + +module.exports = haskell; + + +/***/ }), + +/***/ 50428: +/***/ ((module) => { + +/* +Language: Haxe +Description: Haxe is an open source toolkit based on a modern, high level, strictly typed programming language. +Author: Christopher Kaster (Based on the actionscript.js language file by Alexander Myadzel) +Contributors: Kenton Hamaluik +Website: https://haxe.org +*/ + +function haxe(hljs) { + + const HAXE_BASIC_TYPES = 'Int Float String Bool Dynamic Void Array '; + + return { + name: 'Haxe', + aliases: ['hx'], + keywords: { + keyword: 'break case cast catch continue default do dynamic else enum extern ' + + 'for function here if import in inline never new override package private get set ' + + 'public return static super switch this throw trace try typedef untyped using var while ' + + HAXE_BASIC_TYPES, + built_in: + 'trace this', + literal: + 'true false null _' + }, + contains: [ + { + className: 'string', // interpolate-able strings + begin: '\'', + end: '\'', + contains: [ + hljs.BACKSLASH_ESCAPE, + { + className: 'subst', // interpolation + begin: '\\$\\{', + end: '\\}' + }, + { + className: 'subst', // interpolation + begin: '\\$', + end: /\W\}/ + } + ] + }, + hljs.QUOTE_STRING_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', // compiler meta + begin: '@:', + end: '$' + }, + { + className: 'meta', // compiler conditionals + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'if else elseif end error' + } + }, + { + className: 'type', // function types + begin: ':[ \t]*', + end: '[^A-Za-z0-9_ \t\\->]', + excludeBegin: true, + excludeEnd: true, + relevance: 0 + }, + { + className: 'type', // types + begin: ':[ \t]*', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', // instantiation + begin: 'new *', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'class', // enums + beginKeywords: 'enum', + end: '\\{', + contains: [hljs.TITLE_MODE] + }, + { + className: 'class', // abstracts + beginKeywords: 'abstract', + end: '[\\{$]', + contains: [ + { + className: 'type', + begin: '\\(', + end: '\\)', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', + begin: 'from +', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'type', + begin: 'to +', + end: '\\W', + excludeBegin: true, + excludeEnd: true + }, + hljs.TITLE_MODE + ], + keywords: { + keyword: 'abstract from to' + } + }, + { + className: 'class', // classes + begin: '\\b(class|interface) +', + end: '[\\{$]', + excludeEnd: true, + keywords: 'class interface', + contains: [ + { + className: 'keyword', + begin: '\\b(extends|implements) +', + keywords: 'extends implements', + contains: [ + { + className: 'type', + begin: hljs.IDENT_RE, + relevance: 0 + } + ] + }, + hljs.TITLE_MODE + ] + }, + { + className: 'function', + beginKeywords: 'function', + end: '\\(', + excludeEnd: true, + illegal: '\\S', + contains: [hljs.TITLE_MODE] + } + ], + illegal: /<\// + }; +} + +module.exports = haxe; + + +/***/ }), + +/***/ 99053: +/***/ ((module) => { + +/* +Language: HSP +Author: prince +Website: https://en.wikipedia.org/wiki/Hot_Soup_Processor +Category: scripting +*/ + +function hsp(hljs) { + return { + name: 'HSP', + case_insensitive: true, + keywords: { + $pattern: /[\w._]+/, + keyword: 'goto gosub return break repeat loop continue wait await dim sdim foreach dimtype dup dupptr end stop newmod delmod mref run exgoto on mcall assert logmes newlab resume yield onexit onerror onkey onclick oncmd exist delete mkdir chdir dirlist bload bsave bcopy memfile if else poke wpoke lpoke getstr chdpm memexpand memcpy memset notesel noteadd notedel noteload notesave randomize noteunsel noteget split strrep setease button chgdisp exec dialog mmload mmplay mmstop mci pset pget syscolor mes print title pos circle cls font sysfont objsize picload color palcolor palette redraw width gsel gcopy gzoom gmode bmpsave hsvcolor getkey listbox chkbox combox input mesbox buffer screen bgscr mouse objsel groll line clrobj boxf objprm objmode stick grect grotate gsquare gradf objimage objskip objenable celload celdiv celput newcom querycom delcom cnvstow comres axobj winobj sendmsg comevent comevarg sarrayconv callfunc cnvwtos comevdisp libptr system hspstat hspver stat cnt err strsize looplev sublev iparam wparam lparam refstr refdval int rnd strlen length length2 length3 length4 vartype gettime peek wpeek lpeek varptr varuse noteinfo instr abs limit getease str strmid strf getpath strtrim sin cos tan atan sqrt double absf expf logf limitf powf geteasef mousex mousey mousew hwnd hinstance hdc ginfo objinfo dirinfo sysinfo thismod __hspver__ __hsp30__ __date__ __time__ __line__ __file__ _debug __hspdef__ and or xor not screen_normal screen_palette screen_hide screen_fixedsize screen_tool screen_frame gmode_gdi gmode_mem gmode_rgb0 gmode_alpha gmode_rgb0alpha gmode_add gmode_sub gmode_pixela ginfo_mx ginfo_my ginfo_act ginfo_sel ginfo_wx1 ginfo_wy1 ginfo_wx2 ginfo_wy2 ginfo_vx ginfo_vy ginfo_sizex ginfo_sizey ginfo_winx ginfo_winy ginfo_mesx ginfo_mesy ginfo_r ginfo_g ginfo_b ginfo_paluse ginfo_dispx ginfo_dispy ginfo_cx ginfo_cy ginfo_intid ginfo_newid ginfo_sx ginfo_sy objinfo_mode objinfo_bmscr objinfo_hwnd notemax notesize dir_cur dir_exe dir_win dir_sys dir_cmdline dir_desktop dir_mydoc dir_tv font_normal font_bold font_italic font_underline font_strikeout font_antialias objmode_normal objmode_guifont objmode_usefont gsquare_grad msgothic msmincho do until while wend for next _break _continue switch case default swbreak swend ddim ldim alloc m_pi rad2deg deg2rad ease_linear ease_quad_in ease_quad_out ease_quad_inout ease_cubic_in ease_cubic_out ease_cubic_inout ease_quartic_in ease_quartic_out ease_quartic_inout ease_bounce_in ease_bounce_out ease_bounce_inout ease_shake_in ease_shake_out ease_shake_inout ease_loop' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + + { + // multi-line string + className: 'string', + begin: /\{"/, + end: /"\}/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + + hljs.COMMENT(';', '$', { + relevance: 0 + }), + + { + // pre-processor + className: 'meta', + begin: '#', + end: '$', + keywords: { + 'meta-keyword': 'addion cfunc cmd cmpopt comfunc const defcfunc deffunc define else endif enum epack func global if ifdef ifndef include modcfunc modfunc modinit modterm module pack packopt regcmd runtime undef usecom uselib' + }, + contains: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'meta-string' + }), + hljs.NUMBER_MODE, + hljs.C_NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + + { + // label + className: 'symbol', + begin: '^\\*(\\w+|@)' + }, + + hljs.NUMBER_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = hsp; + + +/***/ }), + +/***/ 44683: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function anyNumberOfTimes(re) { + return concat('(', re, ')*'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Handlebars +Requires: xml.js +Author: Robin Ward +Description: Matcher for Handlebars as well as EmberJS additions. +Website: https://handlebarsjs.com +Category: template +*/ + +function handlebars(hljs) { + const BUILT_INS = { + 'builtin-name': [ + 'action', + 'bindattr', + 'collection', + 'component', + 'concat', + 'debugger', + 'each', + 'each-in', + 'get', + 'hash', + 'if', + 'in', + 'input', + 'link-to', + 'loc', + 'log', + 'lookup', + 'mut', + 'outlet', + 'partial', + 'query-params', + 'render', + 'template', + 'textarea', + 'unbound', + 'unless', + 'view', + 'with', + 'yield' + ] + }; + + const LITERALS = { + literal: [ + 'true', + 'false', + 'undefined', + 'null' + ] + }; + + // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments + // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths + // like a/b, ./abc/cde, and abc.bcd + + const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/; + const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/; + const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/; + const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/; + const PATH_DELIMITER_REGEX = /(\.|\/)/; + const ANY_ID = either( + DOUBLE_QUOTED_ID_REGEX, + SINGLE_QUOTED_ID_REGEX, + BRACKET_QUOTED_ID_REGEX, + PLAIN_ID_REGEX + ); + + const IDENTIFIER_REGEX = concat( + optional(/\.|\.\/|\//), // relative or absolute path + ANY_ID, + anyNumberOfTimes(concat( + PATH_DELIMITER_REGEX, + ANY_ID + )) + ); + + // identifier followed by a equal-sign (without the equal sign) + const HASH_PARAM_REGEX = concat( + '(', + BRACKET_QUOTED_ID_REGEX, '|', + PLAIN_ID_REGEX, + ')(?==)' + ); + + const HELPER_NAME_OR_PATH_EXPRESSION = { + begin: IDENTIFIER_REGEX, + lexemes: /[\w.\/]+/ + }; + + const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: LITERALS + }); + + const SUB_EXPRESSION = { + begin: /\(/, + end: /\)/ + // the "contains" is added below when all necessary sub-modes are defined + }; + + const HASH = { + // fka "attribute-assignment", parameters of the form 'key=value' + className: 'attr', + begin: HASH_PARAM_REGEX, + relevance: 0, + starts: { + begin: /=/, + end: /=/, + starts: { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + HELPER_PARAMETER, + SUB_EXPRESSION + ] + } + } + }; + + const BLOCK_PARAMS = { + // parameters of the form '{{#with x as | y |}}...{{/with}}' + begin: /as\s+\|/, + keywords: { + keyword: 'as' + }, + end: /\|/, + contains: [ + { + // define sub-mode in order to prevent highlighting of block-parameter named "as" + begin: /\w+/ + } + ] + }; + + const HELPER_PARAMETERS = { + contains: [ + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BLOCK_PARAMS, + HASH, + HELPER_PARAMETER, + SUB_EXPRESSION + ], + returnEnd: true + // the property "end" is defined through inheritance when the mode is used. If depends + // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the + // end-token of the surrounding mode) + }; + + const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\)/ + }) + }); + + SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS]; + + const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name', + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + keywords: BUILT_INS, + className: 'name' + }); + + const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, { + className: 'name', + keywords: BUILT_INS, + starts: hljs.inherit(HELPER_PARAMETERS, { + end: /\}\}/ + }) + }); + + const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = { + begin: /\\\{\{/, + skip: true + }; + const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = { + begin: /\\\\(?=\{\{)/, + skip: true + }; + + return { + name: 'Handlebars', + aliases: [ + 'hbs', + 'html.hbs', + 'html.handlebars', + 'htmlbars' + ], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH, + PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH, + hljs.COMMENT(/\{\{!--/, /--\}\}/), + hljs.COMMENT(/\{\{!/, /\}\}/), + { + // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}" + className: 'template-tag', + begin: /\{\{\{\{(?!\/)/, + end: /\}\}\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS], + starts: { + end: /\{\{\{\{\//, + returnEnd: true, + subLanguage: 'xml' + } + }, + { + // close raw block + className: 'template-tag', + begin: /\{\{\{\{\//, + end: /\}\}\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // open block statement + className: 'template-tag', + begin: /\{\{#/, + end: /\}\}/, + contains: [OPENING_BLOCK_MUSTACHE_CONTENTS] + }, + { + className: 'template-tag', + begin: /\{\{(?=else\}\})/, + end: /\}\}/, + keywords: 'else' + }, + { + className: 'template-tag', + begin: /\{\{(?=else if)/, + end: /\}\}/, + keywords: 'else if' + }, + { + // closing block statement + className: 'template-tag', + begin: /\{\{\//, + end: /\}\}/, + contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is NOT html-escaped + className: 'template-variable', + begin: /\{\{\{/, + end: /\}\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + }, + { + // template variable or helper-call that is html-escaped + className: 'template-variable', + begin: /\{\{/, + end: /\}\}/, + contains: [BASIC_MUSTACHE_CONTENTS] + } + ] + }; +} + +/* + Language: HTMLBars (legacy) + Requires: xml.js + Description: Matcher for Handlebars as well as EmberJS additions. + Website: https://github.com/tildeio/htmlbars + Category: template + */ + +function htmlbars(hljs) { + const definition = handlebars(hljs); + + definition.name = "HTMLbars"; + + // HACK: This lets handlebars do the auto-detection if it's been loaded (by + // default the build script will load in alphabetical order) and if not (perhaps + // an install is only using `htmlbars`, not `handlebars`) then this will still + // allow HTMLBars to participate in the auto-detection + + // worse case someone will have HTMLbars and handlebars competing for the same + // content and will need to change their setup to only require handlebars, but + // I don't consider this a breaking change + if (hljs.getLanguage("handlebars")) { + definition.disableAutodetect = true; + } + + return definition; +} + +module.exports = htmlbars; + + +/***/ }), + +/***/ 66376: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: HTTP +Description: HTTP request and response headers with automatic body highlighting +Author: Ivan Sagalaev +Category: common, protocols +Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview +*/ + +function http(hljs) { + const VERSION = 'HTTP/(2|1\\.[01])'; + const HEADER_NAME = /[A-Za-z][A-Za-z0-9-]*/; + const HEADER = { + className: 'attribute', + begin: concat('^', HEADER_NAME, '(?=\\:\\s)'), + starts: { + contains: [ + { + className: "punctuation", + begin: /: /, + relevance: 0, + starts: { + end: '$', + relevance: 0 + } + } + ] + } + }; + const HEADERS_AND_BODY = [ + HEADER, + { + begin: '\\n\\n', + starts: { subLanguage: [], endsWithParent: true } + } + ]; + + return { + name: 'HTTP', + aliases: ['https'], + illegal: /\S/, + contains: [ + // response + { + begin: '^(?=' + VERSION + " \\d{3})", + end: /$/, + contains: [ + { + className: "meta", + begin: VERSION + }, + { + className: 'number', begin: '\\b\\d{3}\\b' + } + ], + starts: { + end: /\b\B/, + illegal: /\S/, + contains: HEADERS_AND_BODY + } + }, + // request + { + begin: '(?=^[A-Z]+ (.*?) ' + VERSION + '$)', + end: /$/, + contains: [ + { + className: 'string', + begin: ' ', + end: ' ', + excludeBegin: true, + excludeEnd: true + }, + { + className: "meta", + begin: VERSION + }, + { + className: 'keyword', + begin: '[A-Z]+' + } + ], + starts: { + end: /\b\B/, + illegal: /\S/, + contains: HEADERS_AND_BODY + } + }, + // to allow headers to work even without a preamble + hljs.inherit(HEADER, { + relevance: 0 + }) + ] + }; +} + +module.exports = http; + + +/***/ }), + +/***/ 52327: +/***/ ((module) => { + +/* +Language: Hy +Description: Hy is a wonderful dialect of Lisp that’s embedded in Python. +Author: Sergey Sobko +Website: http://docs.hylang.org/en/stable/ +Category: lisp +*/ + +function hy(hljs) { + var SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\''; + var SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*'; + var keywords = { + $pattern: SYMBOL_RE, + 'builtin-name': + // keywords + '!= % %= & &= * ** **= *= *map ' + + '+ += , --build-class-- --import-- -= . / // //= ' + + '/= < << <<= <= = > >= >> >>= ' + + '@ @= ^ ^= abs accumulate all and any ap-compose ' + + 'ap-dotimes ap-each ap-each-while ap-filter ap-first ap-if ap-last ap-map ap-map-when ap-pipe ' + + 'ap-reduce ap-reject apply as-> ascii assert assoc bin break butlast ' + + 'callable calling-module-name car case cdr chain chr coll? combinations compile ' + + 'compress cond cons cons? continue count curry cut cycle dec ' + + 'def default-method defclass defmacro defmacro-alias defmacro/g! defmain defmethod defmulti defn ' + + 'defn-alias defnc defnr defreader defseq del delattr delete-route dict-comp dir ' + + 'disassemble dispatch-reader-macro distinct divmod do doto drop drop-last drop-while empty? ' + + 'end-sequence eval eval-and-compile eval-when-compile even? every? except exec filter first ' + + 'flatten float? fn fnc fnr for for* format fraction genexpr ' + + 'gensym get getattr global globals group-by hasattr hash hex id ' + + 'identity if if* if-not if-python2 import in inc input instance? ' + + 'integer integer-char? integer? interleave interpose is is-coll is-cons is-empty is-even ' + + 'is-every is-float is-instance is-integer is-integer-char is-iterable is-iterator is-keyword is-neg is-none ' + + 'is-not is-numeric is-odd is-pos is-string is-symbol is-zero isinstance islice issubclass ' + + 'iter iterable? iterate iterator? keyword keyword? lambda last len let ' + + 'lif lif-not list* list-comp locals loop macro-error macroexpand macroexpand-1 macroexpand-all ' + + 'map max merge-with method-decorator min multi-decorator multicombinations name neg? next ' + + 'none? nonlocal not not-in not? nth numeric? oct odd? open ' + + 'or ord partition permutations pos? post-route postwalk pow prewalk print ' + + 'product profile/calls profile/cpu put-route quasiquote quote raise range read read-str ' + + 'recursive-replace reduce remove repeat repeatedly repr require rest round route ' + + 'route-with-methods rwm second seq set-comp setattr setv some sorted string ' + + 'string? sum switch symbol? take take-nth take-while tee try unless ' + + 'unquote unquote-splicing vars walk when while with with* with-decorator with-gensyms ' + + 'xi xor yield yield-from zero? zip zip-longest | |= ~' + }; + + var SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?'; + + var SYMBOL = { + begin: SYMBOL_RE, + relevance: 0 + }; + var NUMBER = { + className: 'number', begin: SIMPLE_NUMBER_RE, + relevance: 0 + }; + var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); + var COMMENT = hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ); + var LITERAL = { + className: 'literal', + begin: /\b([Tt]rue|[Ff]alse|nil|None)\b/ + }; + var COLLECTION = { + begin: '[\\[\\{]', end: '[\\]\\}]' + }; + var HINT = { + className: 'comment', + begin: '\\^' + SYMBOL_RE + }; + var HINT_COL = hljs.COMMENT('\\^\\{', '\\}'); + var KEY = { + className: 'symbol', + begin: '[:]{1,2}' + SYMBOL_RE + }; + var LIST = { + begin: '\\(', end: '\\)' + }; + var BODY = { + endsWithParent: true, + relevance: 0 + }; + var NAME = { + className: 'name', + relevance: 0, + keywords: keywords, + begin: SYMBOL_RE, + starts: BODY + }; + var DEFAULT_CONTAINS = [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL, SYMBOL]; + + LIST.contains = [hljs.COMMENT('comment', ''), NAME, BODY]; + BODY.contains = DEFAULT_CONTAINS; + COLLECTION.contains = DEFAULT_CONTAINS; + + return { + name: 'Hy', + aliases: ['hylang'], + illegal: /\S/, + contains: [hljs.SHEBANG(), LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL] + }; +} + +module.exports = hy; + + +/***/ }), + +/***/ 89928: +/***/ ((module) => { + +/* +Language: Inform 7 +Author: Bruno Dias +Description: Language definition for Inform 7, a DSL for writing parser interactive fiction. +Website: http://inform7.com +*/ + +function inform7(hljs) { + const START_BRACKET = '\\['; + const END_BRACKET = '\\]'; + return { + name: 'Inform 7', + aliases: ['i7'], + case_insensitive: true, + keywords: { + // Some keywords more or less unique to I7, for relevance. + keyword: + // kind: + 'thing room person man woman animal container ' + + 'supporter backdrop door ' + + // characteristic: + 'scenery open closed locked inside gender ' + + // verb: + 'is are say understand ' + + // misc keyword: + 'kind of rule' + }, + contains: [ + { + className: 'string', + begin: '"', + end: '"', + relevance: 0, + contains: [ + { + className: 'subst', + begin: START_BRACKET, + end: END_BRACKET + } + ] + }, + { + className: 'section', + begin: /^(Volume|Book|Part|Chapter|Section|Table)\b/, + end: '$' + }, + { + // Rule definition + // This is here for relevance. + begin: /^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/, + end: ':', + contains: [ + { + // Rule name + begin: '\\(This', + end: '\\)' + } + ] + }, + { + className: 'comment', + begin: START_BRACKET, + end: END_BRACKET, + contains: ['self'] + } + ] + }; +} + +module.exports = inform7; + + +/***/ }), + +/***/ 35856: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: TOML, also INI +Description: TOML aims to be a minimal configuration file format that's easy to read due to obvious semantics. +Contributors: Guillaume Gomez +Category: common, config +Website: https://github.com/toml-lang/toml +*/ + +function ini(hljs) { + const NUMBERS = { + className: 'number', + relevance: 0, + variants: [ + { + begin: /([+-]+)?[\d]+_[\d_]+/ + }, + { + begin: hljs.NUMBER_RE + } + ] + }; + const COMMENTS = hljs.COMMENT(); + COMMENTS.variants = [ + { + begin: /;/, + end: /$/ + }, + { + begin: /#/, + end: /$/ + } + ]; + const VARIABLES = { + className: 'variable', + variants: [ + { + begin: /\$[\w\d"][\w\d_]*/ + }, + { + begin: /\$\{(.*?)\}/ + } + ] + }; + const LITERALS = { + className: 'literal', + begin: /\bon|off|true|false|yes|no\b/ + }; + const STRINGS = { + className: "string", + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + { + begin: "'''", + end: "'''", + relevance: 10 + }, + { + begin: '"""', + end: '"""', + relevance: 10 + }, + { + begin: '"', + end: '"' + }, + { + begin: "'", + end: "'" + } + ] + }; + const ARRAY = { + begin: /\[/, + end: /\]/, + contains: [ + COMMENTS, + LITERALS, + VARIABLES, + STRINGS, + NUMBERS, + 'self' + ], + relevance: 0 + }; + + const BARE_KEY = /[A-Za-z0-9_-]+/; + const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/; + const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/; + const ANY_KEY = either( + BARE_KEY, QUOTED_KEY_DOUBLE_QUOTE, QUOTED_KEY_SINGLE_QUOTE + ); + const DOTTED_KEY = concat( + ANY_KEY, '(\\s*\\.\\s*', ANY_KEY, ')*', + lookahead(/\s*=\s*[^#\s]/) + ); + + return { + name: 'TOML, also INI', + aliases: ['toml'], + case_insensitive: true, + illegal: /\S/, + contains: [ + COMMENTS, + { + className: 'section', + begin: /\[+/, + end: /\]+/ + }, + { + begin: DOTTED_KEY, + className: 'attr', + starts: { + end: /$/, + contains: [ + COMMENTS, + ARRAY, + LITERALS, + VARIABLES, + STRINGS, + NUMBERS + ] + } + } + ] + }; +} + +module.exports = ini; + + +/***/ }), + +/***/ 42084: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: IRPF90 +Author: Anthony Scemama +Description: IRPF90 is an open-source Fortran code generator +Website: http://irpf90.ups-tlse.fr +Category: scientific +*/ + +/** @type LanguageFn */ +function irpf90(hljs) { + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)' + }; + + // regex in both fortran and irpf90 should match + const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/; + const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/; + const NUMBER = { + className: 'number', + variants: [ + { + begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + }, + { + begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX) + } + ], + relevance: 0 + }; + + const F_KEYWORDS = { + literal: '.False. .True.', + keyword: 'kind do while private call intrinsic where elsewhere ' + + 'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then ' + + 'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' + + 'goto save else use module select case ' + + 'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' + + 'continue format pause cycle exit ' + + 'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' + + 'synchronous nopass non_overridable pass protected volatile abstract extends import ' + + 'non_intrinsic value deferred generic final enumerator class associate bind enum ' + + 'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' + + 'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' + + 'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' + + 'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer ' + + 'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' + + 'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' + + 'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' + + 'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure ' + + 'integer real character complex logical dimension allocatable|10 parameter ' + + 'external implicit|10 none double precision assign intent optional pointer ' + + 'target in out common equivalence data ' + + // IRPF90 special keywords + 'begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch ' + + 'soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read', + built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' + + 'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' + + 'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' + + 'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' + + 'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' + + 'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' + + 'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' + + 'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' + + 'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' + + 'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' + + 'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' + + 'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' + + 'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' + + 'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' + + 'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' + + 'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' + + 'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' + + 'num_images parity popcnt poppar shifta shiftl shiftr this_image ' + + // IRPF90 special built_ins + 'IRP_ALIGN irp_here' + }; + return { + name: 'IRPF90', + case_insensitive: true, + keywords: F_KEYWORDS, + illegal: /\/\*/, + contains: [ + hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'string', + relevance: 0 + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'string', + relevance: 0 + }), + { + className: 'function', + beginKeywords: 'subroutine function program', + illegal: '[${=\\n]', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }, + hljs.COMMENT('!', '$', { + relevance: 0 + }), + hljs.COMMENT('begin_doc', 'end_doc', { + relevance: 10 + }), + NUMBER + ] + }; +} + +module.exports = irpf90; + + +/***/ }), + +/***/ 73162: +/***/ ((module) => { + +/* +Language: ISBL +Author: Dmitriy Tarasov +Description: built-in language DIRECTUM +Category: enterprise +*/ + +function isbl(hljs) { + // Определение идентификаторов + const UNDERSCORE_IDENT_RE = "[A-Za-zА-Яа-яёЁ_!][A-Za-zА-Яа-яёЁ_0-9]*"; + + // Определение имен функций + const FUNCTION_NAME_IDENT_RE = "[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]*"; + + // keyword : ключевые слова + const KEYWORD = + "and и else иначе endexcept endfinally endforeach конецвсе endif конецесли endwhile конецпока " + + "except exitfor finally foreach все if если in в not не or или try while пока "; + + // SYSRES Constants + const sysres_constants = + "SYSRES_CONST_ACCES_RIGHT_TYPE_EDIT " + + "SYSRES_CONST_ACCES_RIGHT_TYPE_FULL " + + "SYSRES_CONST_ACCES_RIGHT_TYPE_VIEW " + + "SYSRES_CONST_ACCESS_MODE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW " + + "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_CODE " + + "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_YES_CODE " + + "SYSRES_CONST_ACCESS_TYPE_CHANGE " + + "SYSRES_CONST_ACCESS_TYPE_CHANGE_CODE " + + "SYSRES_CONST_ACCESS_TYPE_EXISTS " + + "SYSRES_CONST_ACCESS_TYPE_EXISTS_CODE " + + "SYSRES_CONST_ACCESS_TYPE_FULL " + + "SYSRES_CONST_ACCESS_TYPE_FULL_CODE " + + "SYSRES_CONST_ACCESS_TYPE_VIEW " + + "SYSRES_CONST_ACCESS_TYPE_VIEW_CODE " + + "SYSRES_CONST_ACTION_TYPE_ABORT " + + "SYSRES_CONST_ACTION_TYPE_ACCEPT " + + "SYSRES_CONST_ACTION_TYPE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ADD_ATTACHMENT " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_CARD " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_KIND " + + "SYSRES_CONST_ACTION_TYPE_CHANGE_STORAGE " + + "SYSRES_CONST_ACTION_TYPE_CONTINUE " + + "SYSRES_CONST_ACTION_TYPE_COPY " + + "SYSRES_CONST_ACTION_TYPE_CREATE " + + "SYSRES_CONST_ACTION_TYPE_CREATE_VERSION " + + "SYSRES_CONST_ACTION_TYPE_DELETE " + + "SYSRES_CONST_ACTION_TYPE_DELETE_ATTACHMENT " + + "SYSRES_CONST_ACTION_TYPE_DELETE_VERSION " + + "SYSRES_CONST_ACTION_TYPE_DISABLE_DELEGATE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ENABLE_DELEGATE_ACCESS_RIGHTS " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE_AND_PASSWORD " + + "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_PASSWORD " + + "SYSRES_CONST_ACTION_TYPE_EXPORT_WITH_LOCK " + + "SYSRES_CONST_ACTION_TYPE_EXPORT_WITHOUT_LOCK " + + "SYSRES_CONST_ACTION_TYPE_IMPORT_WITH_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_IMPORT_WITHOUT_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_LIFE_CYCLE_STAGE " + + "SYSRES_CONST_ACTION_TYPE_LOCK " + + "SYSRES_CONST_ACTION_TYPE_LOCK_FOR_SERVER " + + "SYSRES_CONST_ACTION_TYPE_LOCK_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_MARK_AS_READED " + + "SYSRES_CONST_ACTION_TYPE_MARK_AS_UNREADED " + + "SYSRES_CONST_ACTION_TYPE_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_MODIFY_CARD " + + "SYSRES_CONST_ACTION_TYPE_MOVE_TO_ARCHIVE " + + "SYSRES_CONST_ACTION_TYPE_OFF_ENCRYPTION " + + "SYSRES_CONST_ACTION_TYPE_PASSWORD_CHANGE " + + "SYSRES_CONST_ACTION_TYPE_PERFORM " + + "SYSRES_CONST_ACTION_TYPE_RECOVER_FROM_LOCAL_COPY " + + "SYSRES_CONST_ACTION_TYPE_RESTART " + + "SYSRES_CONST_ACTION_TYPE_RESTORE_FROM_ARCHIVE " + + "SYSRES_CONST_ACTION_TYPE_REVISION " + + "SYSRES_CONST_ACTION_TYPE_SEND_BY_MAIL " + + "SYSRES_CONST_ACTION_TYPE_SIGN " + + "SYSRES_CONST_ACTION_TYPE_START " + + "SYSRES_CONST_ACTION_TYPE_UNLOCK " + + "SYSRES_CONST_ACTION_TYPE_UNLOCK_FROM_SERVER " + + "SYSRES_CONST_ACTION_TYPE_VERSION_STATE " + + "SYSRES_CONST_ACTION_TYPE_VERSION_VISIBILITY " + + "SYSRES_CONST_ACTION_TYPE_VIEW " + + "SYSRES_CONST_ACTION_TYPE_VIEW_SHADOW_COPY " + + "SYSRES_CONST_ACTION_TYPE_WORKFLOW_DESCRIPTION_MODIFY " + + "SYSRES_CONST_ACTION_TYPE_WRITE_HISTORY " + + "SYSRES_CONST_ACTIVE_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_ADD_REFERENCE_MODE_NAME " + + "SYSRES_CONST_ADDITION_REQUISITE_CODE " + + "SYSRES_CONST_ADDITIONAL_PARAMS_REQUISITE_CODE " + + "SYSRES_CONST_ADITIONAL_JOB_END_DATE_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_READ_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_START_DATE_REQUISITE_NAME " + + "SYSRES_CONST_ADITIONAL_JOB_STATE_REQUISITE_NAME " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION_CODE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE " + + "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE_ACTION " + + "SYSRES_CONST_ALL_ACCEPT_CONDITION_RUS " + + "SYSRES_CONST_ALL_USERS_GROUP " + + "SYSRES_CONST_ALL_USERS_GROUP_NAME " + + "SYSRES_CONST_ALL_USERS_SERVER_GROUP_NAME " + + "SYSRES_CONST_ALLOWED_ACCESS_TYPE_CODE " + + "SYSRES_CONST_ALLOWED_ACCESS_TYPE_NAME " + + "SYSRES_CONST_APP_VIEWER_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_APPROVING_SIGNATURE_NAME " + + "SYSRES_CONST_APPROVING_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE " + + "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE_CODE " + + "SYSRES_CONST_ATTACH_TYPE_COMPONENT_TOKEN " + + "SYSRES_CONST_ATTACH_TYPE_DOC " + + "SYSRES_CONST_ATTACH_TYPE_EDOC " + + "SYSRES_CONST_ATTACH_TYPE_FOLDER " + + "SYSRES_CONST_ATTACH_TYPE_JOB " + + "SYSRES_CONST_ATTACH_TYPE_REFERENCE " + + "SYSRES_CONST_ATTACH_TYPE_TASK " + + "SYSRES_CONST_AUTH_ENCODED_PASSWORD " + + "SYSRES_CONST_AUTH_ENCODED_PASSWORD_CODE " + + "SYSRES_CONST_AUTH_NOVELL " + + "SYSRES_CONST_AUTH_PASSWORD " + + "SYSRES_CONST_AUTH_PASSWORD_CODE " + + "SYSRES_CONST_AUTH_WINDOWS " + + "SYSRES_CONST_AUTHENTICATING_SIGNATURE_NAME " + + "SYSRES_CONST_AUTHENTICATING_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_AUTO_ENUM_METHOD_FLAG " + + "SYSRES_CONST_AUTO_NUMERATION_CODE " + + "SYSRES_CONST_AUTO_STRONG_ENUM_METHOD_FLAG " + + "SYSRES_CONST_AUTOTEXT_NAME_REQUISITE_CODE " + + "SYSRES_CONST_AUTOTEXT_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_ALL " + + "SYSRES_CONST_AUTOTEXT_USAGE_ALL_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_SIGN " + + "SYSRES_CONST_AUTOTEXT_USAGE_SIGN_CODE " + + "SYSRES_CONST_AUTOTEXT_USAGE_WORK " + + "SYSRES_CONST_AUTOTEXT_USAGE_WORK_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ANYWHERE_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ON_SIGNING_CODE " + + "SYSRES_CONST_AUTOTEXT_USE_ON_WORK_CODE " + + "SYSRES_CONST_BEGIN_DATE_REQUISITE_CODE " + + "SYSRES_CONST_BLACK_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_BLUE_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_BTN_PART " + + "SYSRES_CONST_CALCULATED_ROLE_TYPE_CODE " + + "SYSRES_CONST_CALL_TYPE_VARIABLE_BUTTON_VALUE " + + "SYSRES_CONST_CALL_TYPE_VARIABLE_PROGRAM_VALUE " + + "SYSRES_CONST_CANCEL_MESSAGE_FUNCTION_RESULT " + + "SYSRES_CONST_CARD_PART " + + "SYSRES_CONST_CARD_REFERENCE_MODE_NAME " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_ENCRYPT_VALUE " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_AND_ENCRYPT_VALUE " + + "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_VALUE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_DATE_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_FLOAT_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_INTEGER_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_PICK_PARAM_TYPE " + + "SYSRES_CONST_CHECK_PARAM_VALUE_REEFRENCE_PARAM_TYPE " + + "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_FEMININE " + + "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_ADMIN " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_DEVELOPER " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_DOCS " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_EDOC_CARDS " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_OTHER " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_REFERENCE " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_REPORT " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_SCRIPT " + + "SYSRES_CONST_CODE_COMPONENT_TYPE_URL " + + "SYSRES_CONST_CODE_REQUISITE_ACCESS " + + "SYSRES_CONST_CODE_REQUISITE_CODE " + + "SYSRES_CONST_CODE_REQUISITE_COMPONENT " + + "SYSRES_CONST_CODE_REQUISITE_DESCRIPTION " + + "SYSRES_CONST_CODE_REQUISITE_EXCLUDE_COMPONENT " + + "SYSRES_CONST_CODE_REQUISITE_RECORD " + + "SYSRES_CONST_COMMENT_REQ_CODE " + + "SYSRES_CONST_COMMON_SETTINGS_REQUISITE_CODE " + + "SYSRES_CONST_COMP_CODE_GRD " + + "SYSRES_CONST_COMPONENT_GROUP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_COMPONENT_TYPE_ADMIN_COMPONENTS " + + "SYSRES_CONST_COMPONENT_TYPE_DEVELOPER_COMPONENTS " + + "SYSRES_CONST_COMPONENT_TYPE_DOCS " + + "SYSRES_CONST_COMPONENT_TYPE_EDOC_CARDS " + + "SYSRES_CONST_COMPONENT_TYPE_EDOCS " + + "SYSRES_CONST_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " + + "SYSRES_CONST_COMPONENT_TYPE_OTHER " + + "SYSRES_CONST_COMPONENT_TYPE_REFERENCE_TYPES " + + "SYSRES_CONST_COMPONENT_TYPE_REFERENCES " + + "SYSRES_CONST_COMPONENT_TYPE_REPORTS " + + "SYSRES_CONST_COMPONENT_TYPE_SCRIPTS " + + "SYSRES_CONST_COMPONENT_TYPE_URL " + + "SYSRES_CONST_COMPONENTS_REMOTE_SERVERS_VIEW_CODE " + + "SYSRES_CONST_CONDITION_BLOCK_DESCRIPTION " + + "SYSRES_CONST_CONST_FIRM_STATUS_COMMON " + + "SYSRES_CONST_CONST_FIRM_STATUS_INDIVIDUAL " + + "SYSRES_CONST_CONST_NEGATIVE_VALUE " + + "SYSRES_CONST_CONST_POSITIVE_VALUE " + + "SYSRES_CONST_CONST_SERVER_STATUS_DONT_REPLICATE " + + "SYSRES_CONST_CONST_SERVER_STATUS_REPLICATE " + + "SYSRES_CONST_CONTENTS_REQUISITE_CODE " + + "SYSRES_CONST_DATA_TYPE_BOOLEAN " + + "SYSRES_CONST_DATA_TYPE_DATE " + + "SYSRES_CONST_DATA_TYPE_FLOAT " + + "SYSRES_CONST_DATA_TYPE_INTEGER " + + "SYSRES_CONST_DATA_TYPE_PICK " + + "SYSRES_CONST_DATA_TYPE_REFERENCE " + + "SYSRES_CONST_DATA_TYPE_STRING " + + "SYSRES_CONST_DATA_TYPE_TEXT " + + "SYSRES_CONST_DATA_TYPE_VARIANT " + + "SYSRES_CONST_DATE_CLOSE_REQ_CODE " + + "SYSRES_CONST_DATE_FORMAT_DATE_ONLY_CHAR " + + "SYSRES_CONST_DATE_OPEN_REQ_CODE " + + "SYSRES_CONST_DATE_REQUISITE " + + "SYSRES_CONST_DATE_REQUISITE_CODE " + + "SYSRES_CONST_DATE_REQUISITE_NAME " + + "SYSRES_CONST_DATE_REQUISITE_TYPE " + + "SYSRES_CONST_DATE_TYPE_CHAR " + + "SYSRES_CONST_DATETIME_FORMAT_VALUE " + + "SYSRES_CONST_DEA_ACCESS_RIGHTS_ACTION_CODE " + + "SYSRES_CONST_DESCRIPTION_LOCALIZE_ID_REQUISITE_CODE " + + "SYSRES_CONST_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_DET1_PART " + + "SYSRES_CONST_DET2_PART " + + "SYSRES_CONST_DET3_PART " + + "SYSRES_CONST_DET4_PART " + + "SYSRES_CONST_DET5_PART " + + "SYSRES_CONST_DET6_PART " + + "SYSRES_CONST_DETAIL_DATASET_KEY_REQUISITE_CODE " + + "SYSRES_CONST_DETAIL_PICK_REQUISITE_CODE " + + "SYSRES_CONST_DETAIL_REQ_CODE " + + "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_CODE " + + "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_NAME " + + "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_CODE " + + "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_NAME " + + "SYSRES_CONST_DOCUMENT_STORAGES_CODE " + + "SYSRES_CONST_DOCUMENT_TEMPLATES_TYPE_NAME " + + "SYSRES_CONST_DOUBLE_REQUISITE_CODE " + + "SYSRES_CONST_EDITOR_CLOSE_FILE_OBSERV_TYPE_CODE " + + "SYSRES_CONST_EDITOR_CLOSE_PROCESS_OBSERV_TYPE_CODE " + + "SYSRES_CONST_EDITOR_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_APPLICATION_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_CREATE_SEVERAL_PROCESSES_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_EXTENSION_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_OBSERVER_BY_PROCESS_TYPE " + + "SYSRES_CONST_EDITORS_REFERENCE_CODE " + + "SYSRES_CONST_EDITORS_REPLACE_SPEC_CHARS_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_USE_PLUGINS_REQUISITE_CODE " + + "SYSRES_CONST_EDITORS_VIEW_DOCUMENT_OPENED_TO_EDIT_CODE " + + "SYSRES_CONST_EDOC_CARD_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_CARD_TYPES_LINK_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_CERTIFICATE_AND_PASSWORD_ENCODE_CODE " + + "SYSRES_CONST_EDOC_CERTIFICATE_ENCODE_CODE " + + "SYSRES_CONST_EDOC_DATE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_KIND_REFERENCE_CODE " + + "SYSRES_CONST_EDOC_KINDS_BY_TEMPLATE_ACTION_CODE " + + "SYSRES_CONST_EDOC_MANAGE_ACCESS_CODE " + + "SYSRES_CONST_EDOC_NONE_ENCODE_CODE " + + "SYSRES_CONST_EDOC_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_PASSWORD_ENCODE_CODE " + + "SYSRES_CONST_EDOC_READONLY_ACCESS_CODE " + + "SYSRES_CONST_EDOC_SHELL_LIFE_TYPE_VIEW_VALUE " + + "SYSRES_CONST_EDOC_SIZE_RESTRICTION_PRIORITY_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_CHECK_ACCESS_RIGHTS_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_COMPUTER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_DATABASE_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_EDIT_IN_STORAGE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_LOCAL_PATH_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_STORAGE_SHARED_SOURCE_NAME_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_EDOC_TYPES_REFERENCE_CODE " + + "SYSRES_CONST_EDOC_VERSION_ACTIVE_STAGE_CODE " + + "SYSRES_CONST_EDOC_VERSION_DESIGN_STAGE_CODE " + + "SYSRES_CONST_EDOC_VERSION_OBSOLETE_STAGE_CODE " + + "SYSRES_CONST_EDOC_WRITE_ACCES_CODE " + + "SYSRES_CONST_EDOCUMENT_CARD_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " + + "SYSRES_CONST_ENCODE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_END_DATE_REQUISITE_CODE " + + "SYSRES_CONST_ENUMERATION_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_EXECUTE_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_EXECUTIVE_FILE_STORAGE_TYPE " + + "SYSRES_CONST_EXIST_CONST " + + "SYSRES_CONST_EXIST_VALUE " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_ASK " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_WITH_LOCK " + + "SYSRES_CONST_EXPORT_LOCK_TYPE_WITHOUT_LOCK " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_ASK " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST " + + "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST_ACTIVE " + + "SYSRES_CONST_EXTENSION_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_REQUISITE_CODE " + + "SYSRES_CONST_FILTER_TYPE_COMMON_CODE " + + "SYSRES_CONST_FILTER_TYPE_COMMON_NAME " + + "SYSRES_CONST_FILTER_TYPE_USER_CODE " + + "SYSRES_CONST_FILTER_TYPE_USER_NAME " + + "SYSRES_CONST_FILTER_VALUE_REQUISITE_NAME " + + "SYSRES_CONST_FLOAT_NUMBER_FORMAT_CHAR " + + "SYSRES_CONST_FLOAT_REQUISITE_TYPE " + + "SYSRES_CONST_FOLDER_AUTHOR_VALUE " + + "SYSRES_CONST_FOLDER_KIND_ANY_OBJECTS " + + "SYSRES_CONST_FOLDER_KIND_COMPONENTS " + + "SYSRES_CONST_FOLDER_KIND_EDOCS " + + "SYSRES_CONST_FOLDER_KIND_JOBS " + + "SYSRES_CONST_FOLDER_KIND_TASKS " + + "SYSRES_CONST_FOLDER_TYPE_COMMON " + + "SYSRES_CONST_FOLDER_TYPE_COMPONENT " + + "SYSRES_CONST_FOLDER_TYPE_FAVORITES " + + "SYSRES_CONST_FOLDER_TYPE_INBOX " + + "SYSRES_CONST_FOLDER_TYPE_OUTBOX " + + "SYSRES_CONST_FOLDER_TYPE_QUICK_LAUNCH " + + "SYSRES_CONST_FOLDER_TYPE_SEARCH " + + "SYSRES_CONST_FOLDER_TYPE_SHORTCUTS " + + "SYSRES_CONST_FOLDER_TYPE_USER " + + "SYSRES_CONST_FROM_DICTIONARY_ENUM_METHOD_FLAG " + + "SYSRES_CONST_FULL_SUBSTITUTE_TYPE " + + "SYSRES_CONST_FULL_SUBSTITUTE_TYPE_CODE " + + "SYSRES_CONST_FUNCTION_CANCEL_RESULT " + + "SYSRES_CONST_FUNCTION_CATEGORY_SYSTEM " + + "SYSRES_CONST_FUNCTION_CATEGORY_USER " + + "SYSRES_CONST_FUNCTION_FAILURE_RESULT " + + "SYSRES_CONST_FUNCTION_SAVE_RESULT " + + "SYSRES_CONST_GENERATED_REQUISITE " + + "SYSRES_CONST_GREEN_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_GROUP_ACCOUNT_TYPE_VALUE_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_NORMAL_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_NORMAL_NAME " + + "SYSRES_CONST_GROUP_CATEGORY_SERVICE_CODE " + + "SYSRES_CONST_GROUP_CATEGORY_SERVICE_NAME " + + "SYSRES_CONST_GROUP_COMMON_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_GROUP_FULL_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_RIGHTS_T_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVER_CODES_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_GROUP_SERVICE_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_GROUP_USER_REQUISITE_CODE " + + "SYSRES_CONST_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_GROUPS_REQUISITE_CODE " + + "SYSRES_CONST_HIDDEN_MODE_NAME " + + "SYSRES_CONST_HIGH_LVL_REQUISITE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_CREATE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_DELETE_CODE " + + "SYSRES_CONST_HISTORY_ACTION_EDIT_CODE " + + "SYSRES_CONST_HOUR_CHAR " + + "SYSRES_CONST_ID_REQUISITE_CODE " + + "SYSRES_CONST_IDSPS_REQUISITE_CODE " + + "SYSRES_CONST_IMAGE_MODE_COLOR " + + "SYSRES_CONST_IMAGE_MODE_GREYSCALE " + + "SYSRES_CONST_IMAGE_MODE_MONOCHROME " + + "SYSRES_CONST_IMPORTANCE_HIGH " + + "SYSRES_CONST_IMPORTANCE_LOW " + + "SYSRES_CONST_IMPORTANCE_NORMAL " + + "SYSRES_CONST_IN_DESIGN_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_INCOMING_WORK_RULE_TYPE_CODE " + + "SYSRES_CONST_INT_REQUISITE " + + "SYSRES_CONST_INT_REQUISITE_TYPE " + + "SYSRES_CONST_INTEGER_NUMBER_FORMAT_CHAR " + + "SYSRES_CONST_INTEGER_TYPE_CHAR " + + "SYSRES_CONST_IS_GENERATED_REQUISITE_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_PUBLIC_ROLE_REQUISITE_CODE " + + "SYSRES_CONST_IS_REMOTE_USER_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_REMOTE_USER_POSITIVE_VALUE " + + "SYSRES_CONST_IS_STORED_REQUISITE_NEGATIVE_VALUE " + + "SYSRES_CONST_IS_STORED_REQUISITE_STORED_VALUE " + + "SYSRES_CONST_ITALIC_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_JOB_BLOCK_DESCRIPTION " + + "SYSRES_CONST_JOB_KIND_CONTROL_JOB " + + "SYSRES_CONST_JOB_KIND_JOB " + + "SYSRES_CONST_JOB_KIND_NOTICE " + + "SYSRES_CONST_JOB_STATE_ABORTED " + + "SYSRES_CONST_JOB_STATE_COMPLETE " + + "SYSRES_CONST_JOB_STATE_WORKING " + + "SYSRES_CONST_KIND_REQUISITE_CODE " + + "SYSRES_CONST_KIND_REQUISITE_NAME " + + "SYSRES_CONST_KINDS_CREATE_SHADOW_COPIES_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_DEFAULT_EDOC_LIFE_STAGE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALL_TEPLATES_ALLOWED_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALLOW_LIFE_CYCLE_STAGE_CHANGING_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_ALLOW_MULTIPLE_ACTIVE_VERSIONS_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_SHARE_ACCES_RIGHTS_BY_DEFAULT_CODE " + + "SYSRES_CONST_KINDS_EDOC_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_EDOC_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_KINDS_SIGNERS_REQUISITES_CODE " + + "SYSRES_CONST_KOD_INPUT_TYPE " + + "SYSRES_CONST_LAST_UPDATE_DATE_REQUISITE_CODE " + + "SYSRES_CONST_LIFE_CYCLE_START_STAGE_REQUISITE_CODE " + + "SYSRES_CONST_LILAC_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_LINK_OBJECT_KIND_COMPONENT " + + "SYSRES_CONST_LINK_OBJECT_KIND_DOCUMENT " + + "SYSRES_CONST_LINK_OBJECT_KIND_EDOC " + + "SYSRES_CONST_LINK_OBJECT_KIND_FOLDER " + + "SYSRES_CONST_LINK_OBJECT_KIND_JOB " + + "SYSRES_CONST_LINK_OBJECT_KIND_REFERENCE " + + "SYSRES_CONST_LINK_OBJECT_KIND_TASK " + + "SYSRES_CONST_LINK_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_LIST_REFERENCE_MODE_NAME " + + "SYSRES_CONST_LOCALIZATION_DICTIONARY_MAIN_VIEW_CODE " + + "SYSRES_CONST_MAIN_VIEW_CODE " + + "SYSRES_CONST_MANUAL_ENUM_METHOD_FLAG " + + "SYSRES_CONST_MASTER_COMP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_MASTER_TABLE_REC_ID_REQUISITE_CODE " + + "SYSRES_CONST_MAXIMIZED_MODE_NAME " + + "SYSRES_CONST_ME_VALUE " + + "SYSRES_CONST_MESSAGE_ATTENTION_CAPTION " + + "SYSRES_CONST_MESSAGE_CONFIRMATION_CAPTION " + + "SYSRES_CONST_MESSAGE_ERROR_CAPTION " + + "SYSRES_CONST_MESSAGE_INFORMATION_CAPTION " + + "SYSRES_CONST_MINIMIZED_MODE_NAME " + + "SYSRES_CONST_MINUTE_CHAR " + + "SYSRES_CONST_MODULE_REQUISITE_CODE " + + "SYSRES_CONST_MONITORING_BLOCK_DESCRIPTION " + + "SYSRES_CONST_MONTH_FORMAT_VALUE " + + "SYSRES_CONST_NAME_LOCALIZE_ID_REQUISITE_CODE " + + "SYSRES_CONST_NAME_REQUISITE_CODE " + + "SYSRES_CONST_NAME_SINGULAR_REQUISITE_CODE " + + "SYSRES_CONST_NAMEAN_INPUT_TYPE " + + "SYSRES_CONST_NEGATIVE_PICK_VALUE " + + "SYSRES_CONST_NEGATIVE_VALUE " + + "SYSRES_CONST_NO " + + "SYSRES_CONST_NO_PICK_VALUE " + + "SYSRES_CONST_NO_SIGNATURE_REQUISITE_CODE " + + "SYSRES_CONST_NO_VALUE " + + "SYSRES_CONST_NONE_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE " + + "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_NORMAL_ACCESS_RIGHTS_TYPE_CODE " + + "SYSRES_CONST_NORMAL_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_NORMAL_MODE_NAME " + + "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_CODE " + + "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_NAME " + + "SYSRES_CONST_NOTE_REQUISITE_CODE " + + "SYSRES_CONST_NOTICE_BLOCK_DESCRIPTION " + + "SYSRES_CONST_NUM_REQUISITE " + + "SYSRES_CONST_NUM_STR_REQUISITE_CODE " + + "SYSRES_CONST_NUMERATION_AUTO_NOT_STRONG " + + "SYSRES_CONST_NUMERATION_AUTO_STRONG " + + "SYSRES_CONST_NUMERATION_FROM_DICTONARY " + + "SYSRES_CONST_NUMERATION_MANUAL " + + "SYSRES_CONST_NUMERIC_TYPE_CHAR " + + "SYSRES_CONST_NUMREQ_REQUISITE_CODE " + + "SYSRES_CONST_OBSOLETE_VERSION_STATE_PICK_VALUE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_CODE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_FEMININE " + + "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_MASCULINE " + + "SYSRES_CONST_OPTIONAL_FORM_COMP_REQCODE_PREFIX " + + "SYSRES_CONST_ORANGE_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_ORIGINALREF_REQUISITE_CODE " + + "SYSRES_CONST_OURFIRM_REF_CODE " + + "SYSRES_CONST_OURFIRM_REQUISITE_CODE " + + "SYSRES_CONST_OURFIRM_VAR " + + "SYSRES_CONST_OUTGOING_WORK_RULE_TYPE_CODE " + + "SYSRES_CONST_PICK_NEGATIVE_RESULT " + + "SYSRES_CONST_PICK_POSITIVE_RESULT " + + "SYSRES_CONST_PICK_REQUISITE " + + "SYSRES_CONST_PICK_REQUISITE_TYPE " + + "SYSRES_CONST_PICK_TYPE_CHAR " + + "SYSRES_CONST_PLAN_STATUS_REQUISITE_CODE " + + "SYSRES_CONST_PLATFORM_VERSION_COMMENT " + + "SYSRES_CONST_PLUGINS_SETTINGS_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_POSITIVE_PICK_VALUE " + + "SYSRES_CONST_POWER_TO_CREATE_ACTION_CODE " + + "SYSRES_CONST_POWER_TO_SIGN_ACTION_CODE " + + "SYSRES_CONST_PRIORITY_REQUISITE_CODE " + + "SYSRES_CONST_QUALIFIED_TASK_TYPE " + + "SYSRES_CONST_QUALIFIED_TASK_TYPE_CODE " + + "SYSRES_CONST_RECSTAT_REQUISITE_CODE " + + "SYSRES_CONST_RED_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_REF_ID_T_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_REF_REQUISITE " + + "SYSRES_CONST_REF_REQUISITE_TYPE " + + "SYSRES_CONST_REF_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_CREATE_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_DELETE_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_RECORD_HISTORY_MODIFY_ACTION_CODE " + + "SYSRES_CONST_REFERENCE_TYPE_CHAR " + + "SYSRES_CONST_REFERENCE_TYPE_REQUISITE_NAME " + + "SYSRES_CONST_REFERENCES_ADD_PARAMS_REQUISITE_CODE " + + "SYSRES_CONST_REFERENCES_DISPLAY_REQUISITE_REQUISITE_CODE " + + "SYSRES_CONST_REMOTE_SERVER_STATUS_WORKING " + + "SYSRES_CONST_REMOTE_SERVER_TYPE_MAIN " + + "SYSRES_CONST_REMOTE_SERVER_TYPE_SECONDARY " + + "SYSRES_CONST_REMOTE_USER_FLAG_VALUE_CODE " + + "SYSRES_CONST_REPORT_APP_EDITOR_INTERNAL " + + "SYSRES_CONST_REPORT_BASE_REPORT_ID_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_BASE_REPORT_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_SCRIPT_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_TEMPLATE_REQUISITE_CODE " + + "SYSRES_CONST_REPORT_VIEWER_CODE_REQUISITE_CODE " + + "SYSRES_CONST_REQ_ALLOW_COMPONENT_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_ALLOW_RECORD_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_ALLOW_SERVER_COMPONENT_DEFAULT_VALUE " + + "SYSRES_CONST_REQ_MODE_AVAILABLE_CODE " + + "SYSRES_CONST_REQ_MODE_EDIT_CODE " + + "SYSRES_CONST_REQ_MODE_HIDDEN_CODE " + + "SYSRES_CONST_REQ_MODE_NOT_AVAILABLE_CODE " + + "SYSRES_CONST_REQ_MODE_VIEW_CODE " + + "SYSRES_CONST_REQ_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_REQ_SECTION_VALUE " + + "SYSRES_CONST_REQ_TYPE_VALUE " + + "SYSRES_CONST_REQUISITE_FORMAT_BY_UNIT " + + "SYSRES_CONST_REQUISITE_FORMAT_DATE_FULL " + + "SYSRES_CONST_REQUISITE_FORMAT_DATE_TIME " + + "SYSRES_CONST_REQUISITE_FORMAT_LEFT " + + "SYSRES_CONST_REQUISITE_FORMAT_RIGHT " + + "SYSRES_CONST_REQUISITE_FORMAT_WITHOUT_UNIT " + + "SYSRES_CONST_REQUISITE_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_REQUISITE_SECTION_ACTIONS " + + "SYSRES_CONST_REQUISITE_SECTION_BUTTON " + + "SYSRES_CONST_REQUISITE_SECTION_BUTTONS " + + "SYSRES_CONST_REQUISITE_SECTION_CARD " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE10 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE11 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE12 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE13 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE14 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE15 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE16 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE17 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE18 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE19 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE2 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE20 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE21 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE22 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE23 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE24 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE3 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE4 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE5 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE6 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE7 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE8 " + + "SYSRES_CONST_REQUISITE_SECTION_TABLE9 " + + "SYSRES_CONST_REQUISITES_PSEUDOREFERENCE_REQUISITE_NUMBER_REQUISITE_CODE " + + "SYSRES_CONST_RIGHT_ALIGNMENT_CODE " + + "SYSRES_CONST_ROLES_REFERENCE_CODE " + + "SYSRES_CONST_ROUTE_STEP_AFTER_RUS " + + "SYSRES_CONST_ROUTE_STEP_AND_CONDITION_RUS " + + "SYSRES_CONST_ROUTE_STEP_OR_CONDITION_RUS " + + "SYSRES_CONST_ROUTE_TYPE_COMPLEX " + + "SYSRES_CONST_ROUTE_TYPE_PARALLEL " + + "SYSRES_CONST_ROUTE_TYPE_SERIAL " + + "SYSRES_CONST_SBDATASETDESC_NEGATIVE_VALUE " + + "SYSRES_CONST_SBDATASETDESC_POSITIVE_VALUE " + + "SYSRES_CONST_SBVIEWSDESC_POSITIVE_VALUE " + + "SYSRES_CONST_SCRIPT_BLOCK_DESCRIPTION " + + "SYSRES_CONST_SEARCH_BY_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_SEARCHES_COMPONENT_CONTENT " + + "SYSRES_CONST_SEARCHES_CRITERIA_ACTION_NAME " + + "SYSRES_CONST_SEARCHES_EDOC_CONTENT " + + "SYSRES_CONST_SEARCHES_FOLDER_CONTENT " + + "SYSRES_CONST_SEARCHES_JOB_CONTENT " + + "SYSRES_CONST_SEARCHES_REFERENCE_CODE " + + "SYSRES_CONST_SEARCHES_TASK_CONTENT " + + "SYSRES_CONST_SECOND_CHAR " + + "SYSRES_CONST_SECTION_REQUISITE_ACTIONS_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_CARD_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_CODE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_1_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_2_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_3_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_4_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_5_VALUE " + + "SYSRES_CONST_SECTION_REQUISITE_DETAIL_6_VALUE " + + "SYSRES_CONST_SELECT_REFERENCE_MODE_NAME " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE_ONLY_CHILD " + + "SYSRES_CONST_SELECT_TYPE_SELECTABLE_WITH_CHILD " + + "SYSRES_CONST_SELECT_TYPE_UNSLECTABLE " + + "SYSRES_CONST_SERVER_TYPE_MAIN " + + "SYSRES_CONST_SERVICE_USER_CATEGORY_FIELD_VALUE " + + "SYSRES_CONST_SETTINGS_USER_REQUISITE_CODE " + + "SYSRES_CONST_SIGNATURE_AND_ENCODE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_SIGNATURE_CERTIFICATE_TYPE_CODE " + + "SYSRES_CONST_SINGULAR_TITLE_REQUISITE_CODE " + + "SYSRES_CONST_SQL_SERVER_AUTHENTIFICATION_FLAG_VALUE_CODE " + + "SYSRES_CONST_SQL_SERVER_ENCODE_AUTHENTIFICATION_FLAG_VALUE_CODE " + + "SYSRES_CONST_STANDART_ROUTE_REFERENCE_CODE " + + "SYSRES_CONST_STANDART_ROUTE_REFERENCE_COMMENT_REQUISITE_CODE " + + "SYSRES_CONST_STANDART_ROUTES_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_STATE_REQ_NAME " + + "SYSRES_CONST_STATE_REQUISITE_ACTIVE_VALUE " + + "SYSRES_CONST_STATE_REQUISITE_CLOSED_VALUE " + + "SYSRES_CONST_STATE_REQUISITE_CODE " + + "SYSRES_CONST_STATIC_ROLE_TYPE_CODE " + + "SYSRES_CONST_STATUS_PLAN_DEFAULT_VALUE " + + "SYSRES_CONST_STATUS_VALUE_AUTOCLEANING " + + "SYSRES_CONST_STATUS_VALUE_BLUE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_COMPLETE " + + "SYSRES_CONST_STATUS_VALUE_GREEN_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_ORANGE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_PURPLE_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_RED_SQUARE " + + "SYSRES_CONST_STATUS_VALUE_SUSPEND " + + "SYSRES_CONST_STATUS_VALUE_YELLOW_SQUARE " + + "SYSRES_CONST_STDROUTE_SHOW_TO_USERS_REQUISITE_CODE " + + "SYSRES_CONST_STORAGE_TYPE_FILE " + + "SYSRES_CONST_STORAGE_TYPE_SQL_SERVER " + + "SYSRES_CONST_STR_REQUISITE " + + "SYSRES_CONST_STRIKEOUT_LIFE_CYCLE_STAGE_DRAW_STYLE " + + "SYSRES_CONST_STRING_FORMAT_LEFT_ALIGN_CHAR " + + "SYSRES_CONST_STRING_FORMAT_RIGHT_ALIGN_CHAR " + + "SYSRES_CONST_STRING_REQUISITE_CODE " + + "SYSRES_CONST_STRING_REQUISITE_TYPE " + + "SYSRES_CONST_STRING_TYPE_CHAR " + + "SYSRES_CONST_SUBSTITUTES_PSEUDOREFERENCE_CODE " + + "SYSRES_CONST_SUBTASK_BLOCK_DESCRIPTION " + + "SYSRES_CONST_SYSTEM_SETTING_CURRENT_USER_PARAM_VALUE " + + "SYSRES_CONST_SYSTEM_SETTING_EMPTY_VALUE_PARAM_VALUE " + + "SYSRES_CONST_SYSTEM_VERSION_COMMENT " + + "SYSRES_CONST_TASK_ACCESS_TYPE_ALL " + + "SYSRES_CONST_TASK_ACCESS_TYPE_ALL_MEMBERS " + + "SYSRES_CONST_TASK_ACCESS_TYPE_MANUAL " + + "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION " + + "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION_AND_PASSWORD " + + "SYSRES_CONST_TASK_ENCODE_TYPE_NONE " + + "SYSRES_CONST_TASK_ENCODE_TYPE_PASSWORD " + + "SYSRES_CONST_TASK_ROUTE_ALL_CONDITION " + + "SYSRES_CONST_TASK_ROUTE_AND_CONDITION " + + "SYSRES_CONST_TASK_ROUTE_OR_CONDITION " + + "SYSRES_CONST_TASK_STATE_ABORTED " + + "SYSRES_CONST_TASK_STATE_COMPLETE " + + "SYSRES_CONST_TASK_STATE_CONTINUED " + + "SYSRES_CONST_TASK_STATE_CONTROL " + + "SYSRES_CONST_TASK_STATE_INIT " + + "SYSRES_CONST_TASK_STATE_WORKING " + + "SYSRES_CONST_TASK_TITLE " + + "SYSRES_CONST_TASK_TYPES_GROUPS_REFERENCE_CODE " + + "SYSRES_CONST_TASK_TYPES_REFERENCE_CODE " + + "SYSRES_CONST_TEMPLATES_REFERENCE_CODE " + + "SYSRES_CONST_TEST_DATE_REQUISITE_NAME " + + "SYSRES_CONST_TEST_DEV_DATABASE_NAME " + + "SYSRES_CONST_TEST_DEV_SYSTEM_CODE " + + "SYSRES_CONST_TEST_EDMS_DATABASE_NAME " + + "SYSRES_CONST_TEST_EDMS_MAIN_CODE " + + "SYSRES_CONST_TEST_EDMS_MAIN_DB_NAME " + + "SYSRES_CONST_TEST_EDMS_SECOND_CODE " + + "SYSRES_CONST_TEST_EDMS_SECOND_DB_NAME " + + "SYSRES_CONST_TEST_EDMS_SYSTEM_CODE " + + "SYSRES_CONST_TEST_NUMERIC_REQUISITE_NAME " + + "SYSRES_CONST_TEXT_REQUISITE " + + "SYSRES_CONST_TEXT_REQUISITE_CODE " + + "SYSRES_CONST_TEXT_REQUISITE_TYPE " + + "SYSRES_CONST_TEXT_TYPE_CHAR " + + "SYSRES_CONST_TYPE_CODE_REQUISITE_CODE " + + "SYSRES_CONST_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_UNDEFINED_LIFE_CYCLE_STAGE_FONT_COLOR " + + "SYSRES_CONST_UNITS_SECTION_ID_REQUISITE_CODE " + + "SYSRES_CONST_UNITS_SECTION_REQUISITE_CODE " + + "SYSRES_CONST_UNOPERATING_RECORD_FLAG_VALUE_CODE " + + "SYSRES_CONST_UNSTORED_DATA_REQUISITE_CODE " + + "SYSRES_CONST_UNSTORED_DATA_REQUISITE_NAME " + + "SYSRES_CONST_USE_ACCESS_TYPE_CODE " + + "SYSRES_CONST_USE_ACCESS_TYPE_NAME " + + "SYSRES_CONST_USER_ACCOUNT_TYPE_VALUE_CODE " + + "SYSRES_CONST_USER_ADDITIONAL_INFORMATION_REQUISITE_CODE " + + "SYSRES_CONST_USER_AND_GROUP_ID_FROM_PSEUDOREFERENCE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CATEGORY_NORMAL " + + "SYSRES_CONST_USER_CERTIFICATE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_STATE_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_SUBJECT_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_CERTIFICATE_THUMBPRINT_REQUISITE_CODE " + + "SYSRES_CONST_USER_COMMON_CATEGORY " + + "SYSRES_CONST_USER_COMMON_CATEGORY_CODE " + + "SYSRES_CONST_USER_FULL_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_GROUP_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_USER_LOGIN_REQUISITE_CODE " + + "SYSRES_CONST_USER_REMOTE_CONTROLLER_REQUISITE_CODE " + + "SYSRES_CONST_USER_REMOTE_SYSTEM_REQUISITE_CODE " + + "SYSRES_CONST_USER_RIGHTS_T_REQUISITE_CODE " + + "SYSRES_CONST_USER_SERVER_NAME_REQUISITE_CODE " + + "SYSRES_CONST_USER_SERVICE_CATEGORY " + + "SYSRES_CONST_USER_SERVICE_CATEGORY_CODE " + + "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_CODE " + + "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_NAME " + + "SYSRES_CONST_USER_STATUS_DEVELOPER_CODE " + + "SYSRES_CONST_USER_STATUS_DEVELOPER_NAME " + + "SYSRES_CONST_USER_STATUS_DISABLED_CODE " + + "SYSRES_CONST_USER_STATUS_DISABLED_NAME " + + "SYSRES_CONST_USER_STATUS_SYSTEM_DEVELOPER_CODE " + + "SYSRES_CONST_USER_STATUS_USER_CODE " + + "SYSRES_CONST_USER_STATUS_USER_NAME " + + "SYSRES_CONST_USER_STATUS_USER_NAME_DEPRECATED " + + "SYSRES_CONST_USER_TYPE_FIELD_VALUE_USER " + + "SYSRES_CONST_USER_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_USERS_CONTROLLER_REQUISITE_CODE " + + "SYSRES_CONST_USERS_IS_MAIN_SERVER_REQUISITE_CODE " + + "SYSRES_CONST_USERS_REFERENCE_CODE " + + "SYSRES_CONST_USERS_REGISTRATION_CERTIFICATES_ACTION_NAME " + + "SYSRES_CONST_USERS_REQUISITE_CODE " + + "SYSRES_CONST_USERS_SYSTEM_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_ACCESS_RIGHTS_TYPR_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_AUTHENTICATION_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_COMPONENT_REQUISITE_CODE " + + "SYSRES_CONST_USERS_USER_GROUP_REQUISITE_CODE " + + "SYSRES_CONST_USERS_VIEW_CERTIFICATES_ACTION_NAME " + + "SYSRES_CONST_VIEW_DEFAULT_CODE " + + "SYSRES_CONST_VIEW_DEFAULT_NAME " + + "SYSRES_CONST_VIEWER_REQUISITE_CODE " + + "SYSRES_CONST_WAITING_BLOCK_DESCRIPTION " + + "SYSRES_CONST_WIZARD_FORM_LABEL_TEST_STRING " + + "SYSRES_CONST_WIZARD_QUERY_PARAM_HEIGHT_ETALON_STRING " + + "SYSRES_CONST_WIZARD_REFERENCE_COMMENT_REQUISITE_CODE " + + "SYSRES_CONST_WORK_RULES_DESCRIPTION_REQUISITE_CODE " + + "SYSRES_CONST_WORK_TIME_CALENDAR_REFERENCE_CODE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE " + + "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE_RUS " + + "SYSRES_CONST_WORK_WORKFLOW_SOFT_ROUTE_TYPE_VALUE_CODE_RUS " + + "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_HARD " + + "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_SOFT " + + "SYSRES_CONST_XML_ENCODING " + + "SYSRES_CONST_XREC_STAT_REQUISITE_CODE " + + "SYSRES_CONST_XRECID_FIELD_NAME " + + "SYSRES_CONST_YES " + + "SYSRES_CONST_YES_NO_2_REQUISITE_CODE " + + "SYSRES_CONST_YES_NO_REQUISITE_CODE " + + "SYSRES_CONST_YES_NO_T_REF_TYPE_REQUISITE_CODE " + + "SYSRES_CONST_YES_PICK_VALUE " + + "SYSRES_CONST_YES_VALUE "; + + // Base constant + const base_constants = "CR FALSE nil NO_VALUE NULL TAB TRUE YES_VALUE "; + + // Base group name + const base_group_name_constants = + "ADMINISTRATORS_GROUP_NAME CUSTOMIZERS_GROUP_NAME DEVELOPERS_GROUP_NAME SERVICE_USERS_GROUP_NAME "; + + // Decision block properties + const decision_block_properties_constants = + "DECISION_BLOCK_FIRST_OPERAND_PROPERTY DECISION_BLOCK_NAME_PROPERTY DECISION_BLOCK_OPERATION_PROPERTY " + + "DECISION_BLOCK_RESULT_TYPE_PROPERTY DECISION_BLOCK_SECOND_OPERAND_PROPERTY "; + + // File extension + const file_extension_constants = + "ANY_FILE_EXTENTION COMPRESSED_DOCUMENT_EXTENSION EXTENDED_DOCUMENT_EXTENSION " + + "SHORT_COMPRESSED_DOCUMENT_EXTENSION SHORT_EXTENDED_DOCUMENT_EXTENSION "; + + // Job block properties + const job_block_properties_constants = + "JOB_BLOCK_ABORT_DEADLINE_PROPERTY " + + "JOB_BLOCK_AFTER_FINISH_EVENT " + + "JOB_BLOCK_AFTER_QUERY_PARAMETERS_EVENT " + + "JOB_BLOCK_ATTACHMENT_PROPERTY " + + "JOB_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "JOB_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "JOB_BLOCK_BEFORE_QUERY_PARAMETERS_EVENT " + + "JOB_BLOCK_BEFORE_START_EVENT " + + "JOB_BLOCK_CREATED_JOBS_PROPERTY " + + "JOB_BLOCK_DEADLINE_PROPERTY " + + "JOB_BLOCK_EXECUTION_RESULTS_PROPERTY " + + "JOB_BLOCK_IS_PARALLEL_PROPERTY " + + "JOB_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " + + "JOB_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "JOB_BLOCK_JOB_TEXT_PROPERTY " + + "JOB_BLOCK_NAME_PROPERTY " + + "JOB_BLOCK_NEED_SIGN_ON_PERFORM_PROPERTY " + + "JOB_BLOCK_PERFORMER_PROPERTY " + + "JOB_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " + + "JOB_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "JOB_BLOCK_SUBJECT_PROPERTY "; + + // Language code + const language_code_constants = "ENGLISH_LANGUAGE_CODE RUSSIAN_LANGUAGE_CODE "; + + // Launching external applications + const launching_external_applications_constants = + "smHidden smMaximized smMinimized smNormal wmNo wmYes "; + + // Link kind + const link_kind_constants = + "COMPONENT_TOKEN_LINK_KIND " + + "DOCUMENT_LINK_KIND " + + "EDOCUMENT_LINK_KIND " + + "FOLDER_LINK_KIND " + + "JOB_LINK_KIND " + + "REFERENCE_LINK_KIND " + + "TASK_LINK_KIND "; + + // Lock type + const lock_type_constants = + "COMPONENT_TOKEN_LOCK_TYPE EDOCUMENT_VERSION_LOCK_TYPE "; + + // Monitor block properties + const monitor_block_properties_constants = + "MONITOR_BLOCK_AFTER_FINISH_EVENT " + + "MONITOR_BLOCK_BEFORE_START_EVENT " + + "MONITOR_BLOCK_DEADLINE_PROPERTY " + + "MONITOR_BLOCK_INTERVAL_PROPERTY " + + "MONITOR_BLOCK_INTERVAL_TYPE_PROPERTY " + + "MONITOR_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "MONITOR_BLOCK_NAME_PROPERTY " + + "MONITOR_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "MONITOR_BLOCK_SEARCH_SCRIPT_PROPERTY "; + + // Notice block properties + const notice_block_properties_constants = + "NOTICE_BLOCK_AFTER_FINISH_EVENT " + + "NOTICE_BLOCK_ATTACHMENT_PROPERTY " + + "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "NOTICE_BLOCK_BEFORE_START_EVENT " + + "NOTICE_BLOCK_CREATED_NOTICES_PROPERTY " + + "NOTICE_BLOCK_DEADLINE_PROPERTY " + + "NOTICE_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "NOTICE_BLOCK_NAME_PROPERTY " + + "NOTICE_BLOCK_NOTICE_TEXT_PROPERTY " + + "NOTICE_BLOCK_PERFORMER_PROPERTY " + + "NOTICE_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "NOTICE_BLOCK_SUBJECT_PROPERTY "; + + // Object events + const object_events_constants = + "dseAfterCancel " + + "dseAfterClose " + + "dseAfterDelete " + + "dseAfterDeleteOutOfTransaction " + + "dseAfterInsert " + + "dseAfterOpen " + + "dseAfterScroll " + + "dseAfterUpdate " + + "dseAfterUpdateOutOfTransaction " + + "dseBeforeCancel " + + "dseBeforeClose " + + "dseBeforeDelete " + + "dseBeforeDetailUpdate " + + "dseBeforeInsert " + + "dseBeforeOpen " + + "dseBeforeUpdate " + + "dseOnAnyRequisiteChange " + + "dseOnCloseRecord " + + "dseOnDeleteError " + + "dseOnOpenRecord " + + "dseOnPrepareUpdate " + + "dseOnUpdateError " + + "dseOnUpdateRatifiedRecord " + + "dseOnValidDelete " + + "dseOnValidUpdate " + + "reOnChange " + + "reOnChangeValues " + + "SELECTION_BEGIN_ROUTE_EVENT " + + "SELECTION_END_ROUTE_EVENT "; + + // Object params + const object_params_constants = + "CURRENT_PERIOD_IS_REQUIRED " + + "PREVIOUS_CARD_TYPE_NAME " + + "SHOW_RECORD_PROPERTIES_FORM "; + + // Other + const other_constants = + "ACCESS_RIGHTS_SETTING_DIALOG_CODE " + + "ADMINISTRATOR_USER_CODE " + + "ANALYTIC_REPORT_TYPE " + + "asrtHideLocal " + + "asrtHideRemote " + + "CALCULATED_ROLE_TYPE_CODE " + + "COMPONENTS_REFERENCE_DEVELOPER_VIEW_CODE " + + "DCTS_TEST_PROTOCOLS_FOLDER_PATH " + + "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED " + + "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED_BY_USER " + + "E_EDOC_VERSION_ALREDY_SIGNED " + + "E_EDOC_VERSION_ALREDY_SIGNED_BY_USER " + + "EDOC_TYPES_CODE_REQUISITE_FIELD_NAME " + + "EDOCUMENTS_ALIAS_NAME " + + "FILES_FOLDER_PATH " + + "FILTER_OPERANDS_DELIMITER " + + "FILTER_OPERATIONS_DELIMITER " + + "FORMCARD_NAME " + + "FORMLIST_NAME " + + "GET_EXTENDED_DOCUMENT_EXTENSION_CREATION_MODE " + + "GET_EXTENDED_DOCUMENT_EXTENSION_IMPORT_MODE " + + "INTEGRATED_REPORT_TYPE " + + "IS_BUILDER_APPLICATION_ROLE " + + "IS_BUILDER_APPLICATION_ROLE2 " + + "IS_BUILDER_USERS " + + "ISBSYSDEV " + + "LOG_FOLDER_PATH " + + "mbCancel " + + "mbNo " + + "mbNoToAll " + + "mbOK " + + "mbYes " + + "mbYesToAll " + + "MEMORY_DATASET_DESRIPTIONS_FILENAME " + + "mrNo " + + "mrNoToAll " + + "mrYes " + + "mrYesToAll " + + "MULTIPLE_SELECT_DIALOG_CODE " + + "NONOPERATING_RECORD_FLAG_FEMININE " + + "NONOPERATING_RECORD_FLAG_MASCULINE " + + "OPERATING_RECORD_FLAG_FEMININE " + + "OPERATING_RECORD_FLAG_MASCULINE " + + "PROFILING_SETTINGS_COMMON_SETTINGS_CODE_VALUE " + + "PROGRAM_INITIATED_LOOKUP_ACTION " + + "ratDelete " + + "ratEdit " + + "ratInsert " + + "REPORT_TYPE " + + "REQUIRED_PICK_VALUES_VARIABLE " + + "rmCard " + + "rmList " + + "SBRTE_PROGID_DEV " + + "SBRTE_PROGID_RELEASE " + + "STATIC_ROLE_TYPE_CODE " + + "SUPPRESS_EMPTY_TEMPLATE_CREATION " + + "SYSTEM_USER_CODE " + + "UPDATE_DIALOG_DATASET " + + "USED_IN_OBJECT_HINT_PARAM " + + "USER_INITIATED_LOOKUP_ACTION " + + "USER_NAME_FORMAT " + + "USER_SELECTION_RESTRICTIONS " + + "WORKFLOW_TEST_PROTOCOLS_FOLDER_PATH " + + "ELS_SUBTYPE_CONTROL_NAME " + + "ELS_FOLDER_KIND_CONTROL_NAME " + + "REPEAT_PROCESS_CURRENT_OBJECT_EXCEPTION_NAME "; + + // Privileges + const privileges_constants = + "PRIVILEGE_COMPONENT_FULL_ACCESS " + + "PRIVILEGE_DEVELOPMENT_EXPORT " + + "PRIVILEGE_DEVELOPMENT_IMPORT " + + "PRIVILEGE_DOCUMENT_DELETE " + + "PRIVILEGE_ESD " + + "PRIVILEGE_FOLDER_DELETE " + + "PRIVILEGE_MANAGE_ACCESS_RIGHTS " + + "PRIVILEGE_MANAGE_REPLICATION " + + "PRIVILEGE_MANAGE_SESSION_SERVER " + + "PRIVILEGE_OBJECT_FULL_ACCESS " + + "PRIVILEGE_OBJECT_VIEW " + + "PRIVILEGE_RESERVE_LICENSE " + + "PRIVILEGE_SYSTEM_CUSTOMIZE " + + "PRIVILEGE_SYSTEM_DEVELOP " + + "PRIVILEGE_SYSTEM_INSTALL " + + "PRIVILEGE_TASK_DELETE " + + "PRIVILEGE_USER_PLUGIN_SETTINGS_CUSTOMIZE " + + "PRIVILEGES_PSEUDOREFERENCE_CODE "; + + // Pseudoreference code + const pseudoreference_code_constants = + "ACCESS_TYPES_PSEUDOREFERENCE_CODE " + + "ALL_AVAILABLE_COMPONENTS_PSEUDOREFERENCE_CODE " + + "ALL_AVAILABLE_PRIVILEGES_PSEUDOREFERENCE_CODE " + + "ALL_REPLICATE_COMPONENTS_PSEUDOREFERENCE_CODE " + + "AVAILABLE_DEVELOPERS_COMPONENTS_PSEUDOREFERENCE_CODE " + + "COMPONENTS_PSEUDOREFERENCE_CODE " + + "FILTRATER_SETTINGS_CONFLICTS_PSEUDOREFERENCE_CODE " + + "GROUPS_PSEUDOREFERENCE_CODE " + + "RECEIVE_PROTOCOL_PSEUDOREFERENCE_CODE " + + "REFERENCE_REQUISITE_PSEUDOREFERENCE_CODE " + + "REFERENCE_REQUISITES_PSEUDOREFERENCE_CODE " + + "REFTYPES_PSEUDOREFERENCE_CODE " + + "REPLICATION_SEANCES_DIARY_PSEUDOREFERENCE_CODE " + + "SEND_PROTOCOL_PSEUDOREFERENCE_CODE " + + "SUBSTITUTES_PSEUDOREFERENCE_CODE " + + "SYSTEM_SETTINGS_PSEUDOREFERENCE_CODE " + + "UNITS_PSEUDOREFERENCE_CODE " + + "USERS_PSEUDOREFERENCE_CODE " + + "VIEWERS_PSEUDOREFERENCE_CODE "; + + // Requisite ISBCertificateType values + const requisite_ISBCertificateType_values_constants = + "CERTIFICATE_TYPE_ENCRYPT " + + "CERTIFICATE_TYPE_SIGN " + + "CERTIFICATE_TYPE_SIGN_AND_ENCRYPT "; + + // Requisite ISBEDocStorageType values + const requisite_ISBEDocStorageType_values_constants = + "STORAGE_TYPE_FILE " + + "STORAGE_TYPE_NAS_CIFS " + + "STORAGE_TYPE_SAPERION " + + "STORAGE_TYPE_SQL_SERVER "; + + // Requisite CompType2 values + const requisite_compType2_values_constants = + "COMPTYPE2_REQUISITE_DOCUMENTS_VALUE " + + "COMPTYPE2_REQUISITE_TASKS_VALUE " + + "COMPTYPE2_REQUISITE_FOLDERS_VALUE " + + "COMPTYPE2_REQUISITE_REFERENCES_VALUE "; + + // Requisite name + const requisite_name_constants = + "SYSREQ_CODE " + + "SYSREQ_COMPTYPE2 " + + "SYSREQ_CONST_AVAILABLE_FOR_WEB " + + "SYSREQ_CONST_COMMON_CODE " + + "SYSREQ_CONST_COMMON_VALUE " + + "SYSREQ_CONST_FIRM_CODE " + + "SYSREQ_CONST_FIRM_STATUS " + + "SYSREQ_CONST_FIRM_VALUE " + + "SYSREQ_CONST_SERVER_STATUS " + + "SYSREQ_CONTENTS " + + "SYSREQ_DATE_OPEN " + + "SYSREQ_DATE_CLOSE " + + "SYSREQ_DESCRIPTION " + + "SYSREQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_DOUBLE " + + "SYSREQ_EDOC_ACCESS_TYPE " + + "SYSREQ_EDOC_AUTHOR " + + "SYSREQ_EDOC_CREATED " + + "SYSREQ_EDOC_DELEGATE_RIGHTS_REQUISITE_CODE " + + "SYSREQ_EDOC_EDITOR " + + "SYSREQ_EDOC_ENCODE_TYPE " + + "SYSREQ_EDOC_ENCRYPTION_PLUGIN_NAME " + + "SYSREQ_EDOC_ENCRYPTION_PLUGIN_VERSION " + + "SYSREQ_EDOC_EXPORT_DATE " + + "SYSREQ_EDOC_EXPORTER " + + "SYSREQ_EDOC_KIND " + + "SYSREQ_EDOC_LIFE_STAGE_NAME " + + "SYSREQ_EDOC_LOCKED_FOR_SERVER_CODE " + + "SYSREQ_EDOC_MODIFIED " + + "SYSREQ_EDOC_NAME " + + "SYSREQ_EDOC_NOTE " + + "SYSREQ_EDOC_QUALIFIED_ID " + + "SYSREQ_EDOC_SESSION_KEY " + + "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_NAME " + + "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_VERSION " + + "SYSREQ_EDOC_SIGNATURE_TYPE " + + "SYSREQ_EDOC_SIGNED " + + "SYSREQ_EDOC_STORAGE " + + "SYSREQ_EDOC_STORAGES_ARCHIVE_STORAGE " + + "SYSREQ_EDOC_STORAGES_CHECK_RIGHTS " + + "SYSREQ_EDOC_STORAGES_COMPUTER_NAME " + + "SYSREQ_EDOC_STORAGES_EDIT_IN_STORAGE " + + "SYSREQ_EDOC_STORAGES_EXECUTIVE_STORAGE " + + "SYSREQ_EDOC_STORAGES_FUNCTION " + + "SYSREQ_EDOC_STORAGES_INITIALIZED " + + "SYSREQ_EDOC_STORAGES_LOCAL_PATH " + + "SYSREQ_EDOC_STORAGES_SAPERION_DATABASE_NAME " + + "SYSREQ_EDOC_STORAGES_SEARCH_BY_TEXT " + + "SYSREQ_EDOC_STORAGES_SERVER_NAME " + + "SYSREQ_EDOC_STORAGES_SHARED_SOURCE_NAME " + + "SYSREQ_EDOC_STORAGES_TYPE " + + "SYSREQ_EDOC_TEXT_MODIFIED " + + "SYSREQ_EDOC_TYPE_ACT_CODE " + + "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION " + + "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE " + + "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE_EXISTS " + + "SYSREQ_EDOC_TYPE_ACT_SECTION " + + "SYSREQ_EDOC_TYPE_ADD_PARAMS " + + "SYSREQ_EDOC_TYPE_COMMENT " + + "SYSREQ_EDOC_TYPE_EVENT_TEXT " + + "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR " + + "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_NAME_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_NUMERATION_METHOD " + + "SYSREQ_EDOC_TYPE_PSEUDO_REQUISITE_CODE " + + "SYSREQ_EDOC_TYPE_REQ_CODE " + + "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION " + + "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_EDOC_TYPE_REQ_IS_LEADING " + + "SYSREQ_EDOC_TYPE_REQ_IS_REQUIRED " + + "SYSREQ_EDOC_TYPE_REQ_NUMBER " + + "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE " + + "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE_EXISTS " + + "SYSREQ_EDOC_TYPE_REQ_ON_SELECT " + + "SYSREQ_EDOC_TYPE_REQ_ON_SELECT_KIND " + + "SYSREQ_EDOC_TYPE_REQ_SECTION " + + "SYSREQ_EDOC_TYPE_VIEW_CARD " + + "SYSREQ_EDOC_TYPE_VIEW_CODE " + + "SYSREQ_EDOC_TYPE_VIEW_COMMENT " + + "SYSREQ_EDOC_TYPE_VIEW_IS_MAIN " + + "SYSREQ_EDOC_TYPE_VIEW_NAME " + + "SYSREQ_EDOC_TYPE_VIEW_NAME_LOCALIZE_ID " + + "SYSREQ_EDOC_VERSION_AUTHOR " + + "SYSREQ_EDOC_VERSION_CRC " + + "SYSREQ_EDOC_VERSION_DATA " + + "SYSREQ_EDOC_VERSION_EDITOR " + + "SYSREQ_EDOC_VERSION_EXPORT_DATE " + + "SYSREQ_EDOC_VERSION_EXPORTER " + + "SYSREQ_EDOC_VERSION_HIDDEN " + + "SYSREQ_EDOC_VERSION_LIFE_STAGE " + + "SYSREQ_EDOC_VERSION_MODIFIED " + + "SYSREQ_EDOC_VERSION_NOTE " + + "SYSREQ_EDOC_VERSION_SIGNATURE_TYPE " + + "SYSREQ_EDOC_VERSION_SIGNED " + + "SYSREQ_EDOC_VERSION_SIZE " + + "SYSREQ_EDOC_VERSION_SOURCE " + + "SYSREQ_EDOC_VERSION_TEXT_MODIFIED " + + "SYSREQ_EDOCKIND_DEFAULT_VERSION_STATE_CODE " + + "SYSREQ_FOLDER_KIND " + + "SYSREQ_FUNC_CATEGORY " + + "SYSREQ_FUNC_COMMENT " + + "SYSREQ_FUNC_GROUP " + + "SYSREQ_FUNC_GROUP_COMMENT " + + "SYSREQ_FUNC_GROUP_NUMBER " + + "SYSREQ_FUNC_HELP " + + "SYSREQ_FUNC_PARAM_DEF_VALUE " + + "SYSREQ_FUNC_PARAM_IDENT " + + "SYSREQ_FUNC_PARAM_NUMBER " + + "SYSREQ_FUNC_PARAM_TYPE " + + "SYSREQ_FUNC_TEXT " + + "SYSREQ_GROUP_CATEGORY " + + "SYSREQ_ID " + + "SYSREQ_LAST_UPDATE " + + "SYSREQ_LEADER_REFERENCE " + + "SYSREQ_LINE_NUMBER " + + "SYSREQ_MAIN_RECORD_ID " + + "SYSREQ_NAME " + + "SYSREQ_NAME_LOCALIZE_ID " + + "SYSREQ_NOTE " + + "SYSREQ_ORIGINAL_RECORD " + + "SYSREQ_OUR_FIRM " + + "SYSREQ_PROFILING_SETTINGS_BATCH_LOGING " + + "SYSREQ_PROFILING_SETTINGS_BATCH_SIZE " + + "SYSREQ_PROFILING_SETTINGS_PROFILING_ENABLED " + + "SYSREQ_PROFILING_SETTINGS_SQL_PROFILING_ENABLED " + + "SYSREQ_PROFILING_SETTINGS_START_LOGGED " + + "SYSREQ_RECORD_STATUS " + + "SYSREQ_REF_REQ_FIELD_NAME " + + "SYSREQ_REF_REQ_FORMAT " + + "SYSREQ_REF_REQ_GENERATED " + + "SYSREQ_REF_REQ_LENGTH " + + "SYSREQ_REF_REQ_PRECISION " + + "SYSREQ_REF_REQ_REFERENCE " + + "SYSREQ_REF_REQ_SECTION " + + "SYSREQ_REF_REQ_STORED " + + "SYSREQ_REF_REQ_TOKENS " + + "SYSREQ_REF_REQ_TYPE " + + "SYSREQ_REF_REQ_VIEW " + + "SYSREQ_REF_TYPE_ACT_CODE " + + "SYSREQ_REF_TYPE_ACT_DESCRIPTION " + + "SYSREQ_REF_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_ACT_ON_EXECUTE " + + "SYSREQ_REF_TYPE_ACT_ON_EXECUTE_EXISTS " + + "SYSREQ_REF_TYPE_ACT_SECTION " + + "SYSREQ_REF_TYPE_ADD_PARAMS " + + "SYSREQ_REF_TYPE_COMMENT " + + "SYSREQ_REF_TYPE_COMMON_SETTINGS " + + "SYSREQ_REF_TYPE_DISPLAY_REQUISITE_NAME " + + "SYSREQ_REF_TYPE_EVENT_TEXT " + + "SYSREQ_REF_TYPE_MAIN_LEADING_REF " + + "SYSREQ_REF_TYPE_NAME_IN_SINGULAR " + + "SYSREQ_REF_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_NAME_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_NUMERATION_METHOD " + + "SYSREQ_REF_TYPE_REQ_CODE " + + "SYSREQ_REF_TYPE_REQ_DESCRIPTION " + + "SYSREQ_REF_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " + + "SYSREQ_REF_TYPE_REQ_IS_CONTROL " + + "SYSREQ_REF_TYPE_REQ_IS_FILTER " + + "SYSREQ_REF_TYPE_REQ_IS_LEADING " + + "SYSREQ_REF_TYPE_REQ_IS_REQUIRED " + + "SYSREQ_REF_TYPE_REQ_NUMBER " + + "SYSREQ_REF_TYPE_REQ_ON_CHANGE " + + "SYSREQ_REF_TYPE_REQ_ON_CHANGE_EXISTS " + + "SYSREQ_REF_TYPE_REQ_ON_SELECT " + + "SYSREQ_REF_TYPE_REQ_ON_SELECT_KIND " + + "SYSREQ_REF_TYPE_REQ_SECTION " + + "SYSREQ_REF_TYPE_VIEW_CARD " + + "SYSREQ_REF_TYPE_VIEW_CODE " + + "SYSREQ_REF_TYPE_VIEW_COMMENT " + + "SYSREQ_REF_TYPE_VIEW_IS_MAIN " + + "SYSREQ_REF_TYPE_VIEW_NAME " + + "SYSREQ_REF_TYPE_VIEW_NAME_LOCALIZE_ID " + + "SYSREQ_REFERENCE_TYPE_ID " + + "SYSREQ_STATE " + + "SYSREQ_STATЕ " + + "SYSREQ_SYSTEM_SETTINGS_VALUE " + + "SYSREQ_TYPE " + + "SYSREQ_UNIT " + + "SYSREQ_UNIT_ID " + + "SYSREQ_USER_GROUPS_GROUP_FULL_NAME " + + "SYSREQ_USER_GROUPS_GROUP_NAME " + + "SYSREQ_USER_GROUPS_GROUP_SERVER_NAME " + + "SYSREQ_USERS_ACCESS_RIGHTS " + + "SYSREQ_USERS_AUTHENTICATION " + + "SYSREQ_USERS_CATEGORY " + + "SYSREQ_USERS_COMPONENT " + + "SYSREQ_USERS_COMPONENT_USER_IS_PUBLIC " + + "SYSREQ_USERS_DOMAIN " + + "SYSREQ_USERS_FULL_USER_NAME " + + "SYSREQ_USERS_GROUP " + + "SYSREQ_USERS_IS_MAIN_SERVER " + + "SYSREQ_USERS_LOGIN " + + "SYSREQ_USERS_REFERENCE_USER_IS_PUBLIC " + + "SYSREQ_USERS_STATUS " + + "SYSREQ_USERS_USER_CERTIFICATE " + + "SYSREQ_USERS_USER_CERTIFICATE_INFO " + + "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_NAME " + + "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_VERSION " + + "SYSREQ_USERS_USER_CERTIFICATE_STATE " + + "SYSREQ_USERS_USER_CERTIFICATE_SUBJECT_NAME " + + "SYSREQ_USERS_USER_CERTIFICATE_THUMBPRINT " + + "SYSREQ_USERS_USER_DEFAULT_CERTIFICATE " + + "SYSREQ_USERS_USER_DESCRIPTION " + + "SYSREQ_USERS_USER_GLOBAL_NAME " + + "SYSREQ_USERS_USER_LOGIN " + + "SYSREQ_USERS_USER_MAIN_SERVER " + + "SYSREQ_USERS_USER_TYPE " + + "SYSREQ_WORK_RULES_FOLDER_ID "; + + // Result + const result_constants = "RESULT_VAR_NAME RESULT_VAR_NAME_ENG "; + + // Rule identification + const rule_identification_constants = + "AUTO_NUMERATION_RULE_ID " + + "CANT_CHANGE_ID_REQUISITE_RULE_ID " + + "CANT_CHANGE_OURFIRM_REQUISITE_RULE_ID " + + "CHECK_CHANGING_REFERENCE_RECORD_USE_RULE_ID " + + "CHECK_CODE_REQUISITE_RULE_ID " + + "CHECK_DELETING_REFERENCE_RECORD_USE_RULE_ID " + + "CHECK_FILTRATER_CHANGES_RULE_ID " + + "CHECK_RECORD_INTERVAL_RULE_ID " + + "CHECK_REFERENCE_INTERVAL_RULE_ID " + + "CHECK_REQUIRED_DATA_FULLNESS_RULE_ID " + + "CHECK_REQUIRED_REQUISITES_FULLNESS_RULE_ID " + + "MAKE_RECORD_UNRATIFIED_RULE_ID " + + "RESTORE_AUTO_NUMERATION_RULE_ID " + + "SET_FIRM_CONTEXT_FROM_RECORD_RULE_ID " + + "SET_FIRST_RECORD_IN_LIST_FORM_RULE_ID " + + "SET_IDSPS_VALUE_RULE_ID " + + "SET_NEXT_CODE_VALUE_RULE_ID " + + "SET_OURFIRM_BOUNDS_RULE_ID " + + "SET_OURFIRM_REQUISITE_RULE_ID "; + + // Script block properties + const script_block_properties_constants = + "SCRIPT_BLOCK_AFTER_FINISH_EVENT " + + "SCRIPT_BLOCK_BEFORE_START_EVENT " + + "SCRIPT_BLOCK_EXECUTION_RESULTS_PROPERTY " + + "SCRIPT_BLOCK_NAME_PROPERTY " + + "SCRIPT_BLOCK_SCRIPT_PROPERTY "; + + // Subtask block properties + const subtask_block_properties_constants = + "SUBTASK_BLOCK_ABORT_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_AFTER_FINISH_EVENT " + + "SUBTASK_BLOCK_ASSIGN_PARAMS_EVENT " + + "SUBTASK_BLOCK_ATTACHMENTS_PROPERTY " + + "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " + + "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " + + "SUBTASK_BLOCK_BEFORE_START_EVENT " + + "SUBTASK_BLOCK_CREATED_TASK_PROPERTY " + + "SUBTASK_BLOCK_CREATION_EVENT " + + "SUBTASK_BLOCK_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_IMPORTANCE_PROPERTY " + + "SUBTASK_BLOCK_INITIATOR_PROPERTY " + + "SUBTASK_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "SUBTASK_BLOCK_JOBS_TYPE_PROPERTY " + + "SUBTASK_BLOCK_NAME_PROPERTY " + + "SUBTASK_BLOCK_PARALLEL_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_PERFORMERS_PROPERTY " + + "SUBTASK_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " + + "SUBTASK_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " + + "SUBTASK_BLOCK_REQUIRE_SIGN_PROPERTY " + + "SUBTASK_BLOCK_STANDARD_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_START_EVENT " + + "SUBTASK_BLOCK_STEP_CONTROL_PROPERTY " + + "SUBTASK_BLOCK_SUBJECT_PROPERTY " + + "SUBTASK_BLOCK_TASK_CONTROL_PROPERTY " + + "SUBTASK_BLOCK_TEXT_PROPERTY " + + "SUBTASK_BLOCK_UNLOCK_ATTACHMENTS_ON_STOP_PROPERTY " + + "SUBTASK_BLOCK_USE_STANDARD_ROUTE_PROPERTY " + + "SUBTASK_BLOCK_WAIT_FOR_TASK_COMPLETE_PROPERTY "; + + // System component + const system_component_constants = + "SYSCOMP_CONTROL_JOBS " + + "SYSCOMP_FOLDERS " + + "SYSCOMP_JOBS " + + "SYSCOMP_NOTICES " + + "SYSCOMP_TASKS "; + + // System dialogs + const system_dialogs_constants = + "SYSDLG_CREATE_EDOCUMENT " + + "SYSDLG_CREATE_EDOCUMENT_VERSION " + + "SYSDLG_CURRENT_PERIOD " + + "SYSDLG_EDIT_FUNCTION_HELP " + + "SYSDLG_EDOCUMENT_KINDS_FOR_TEMPLATE " + + "SYSDLG_EXPORT_MULTIPLE_EDOCUMENTS " + + "SYSDLG_EXPORT_SINGLE_EDOCUMENT " + + "SYSDLG_IMPORT_EDOCUMENT " + + "SYSDLG_MULTIPLE_SELECT " + + "SYSDLG_SETUP_ACCESS_RIGHTS " + + "SYSDLG_SETUP_DEFAULT_RIGHTS " + + "SYSDLG_SETUP_FILTER_CONDITION " + + "SYSDLG_SETUP_SIGN_RIGHTS " + + "SYSDLG_SETUP_TASK_OBSERVERS " + + "SYSDLG_SETUP_TASK_ROUTE " + + "SYSDLG_SETUP_USERS_LIST " + + "SYSDLG_SIGN_EDOCUMENT " + + "SYSDLG_SIGN_MULTIPLE_EDOCUMENTS "; + + // System reference names + const system_reference_names_constants = + "SYSREF_ACCESS_RIGHTS_TYPES " + + "SYSREF_ADMINISTRATION_HISTORY " + + "SYSREF_ALL_AVAILABLE_COMPONENTS " + + "SYSREF_ALL_AVAILABLE_PRIVILEGES " + + "SYSREF_ALL_REPLICATING_COMPONENTS " + + "SYSREF_AVAILABLE_DEVELOPERS_COMPONENTS " + + "SYSREF_CALENDAR_EVENTS " + + "SYSREF_COMPONENT_TOKEN_HISTORY " + + "SYSREF_COMPONENT_TOKENS " + + "SYSREF_COMPONENTS " + + "SYSREF_CONSTANTS " + + "SYSREF_DATA_RECEIVE_PROTOCOL " + + "SYSREF_DATA_SEND_PROTOCOL " + + "SYSREF_DIALOGS " + + "SYSREF_DIALOGS_REQUISITES " + + "SYSREF_EDITORS " + + "SYSREF_EDOC_CARDS " + + "SYSREF_EDOC_TYPES " + + "SYSREF_EDOCUMENT_CARD_REQUISITES " + + "SYSREF_EDOCUMENT_CARD_TYPES " + + "SYSREF_EDOCUMENT_CARD_TYPES_REFERENCE " + + "SYSREF_EDOCUMENT_CARDS " + + "SYSREF_EDOCUMENT_HISTORY " + + "SYSREF_EDOCUMENT_KINDS " + + "SYSREF_EDOCUMENT_REQUISITES " + + "SYSREF_EDOCUMENT_SIGNATURES " + + "SYSREF_EDOCUMENT_TEMPLATES " + + "SYSREF_EDOCUMENT_TEXT_STORAGES " + + "SYSREF_EDOCUMENT_VIEWS " + + "SYSREF_FILTERER_SETUP_CONFLICTS " + + "SYSREF_FILTRATER_SETTING_CONFLICTS " + + "SYSREF_FOLDER_HISTORY " + + "SYSREF_FOLDERS " + + "SYSREF_FUNCTION_GROUPS " + + "SYSREF_FUNCTION_PARAMS " + + "SYSREF_FUNCTIONS " + + "SYSREF_JOB_HISTORY " + + "SYSREF_LINKS " + + "SYSREF_LOCALIZATION_DICTIONARY " + + "SYSREF_LOCALIZATION_LANGUAGES " + + "SYSREF_MODULES " + + "SYSREF_PRIVILEGES " + + "SYSREF_RECORD_HISTORY " + + "SYSREF_REFERENCE_REQUISITES " + + "SYSREF_REFERENCE_TYPE_VIEWS " + + "SYSREF_REFERENCE_TYPES " + + "SYSREF_REFERENCES " + + "SYSREF_REFERENCES_REQUISITES " + + "SYSREF_REMOTE_SERVERS " + + "SYSREF_REPLICATION_SESSIONS_LOG " + + "SYSREF_REPLICATION_SESSIONS_PROTOCOL " + + "SYSREF_REPORTS " + + "SYSREF_ROLES " + + "SYSREF_ROUTE_BLOCK_GROUPS " + + "SYSREF_ROUTE_BLOCKS " + + "SYSREF_SCRIPTS " + + "SYSREF_SEARCHES " + + "SYSREF_SERVER_EVENTS " + + "SYSREF_SERVER_EVENTS_HISTORY " + + "SYSREF_STANDARD_ROUTE_GROUPS " + + "SYSREF_STANDARD_ROUTES " + + "SYSREF_STATUSES " + + "SYSREF_SYSTEM_SETTINGS " + + "SYSREF_TASK_HISTORY " + + "SYSREF_TASK_KIND_GROUPS " + + "SYSREF_TASK_KINDS " + + "SYSREF_TASK_RIGHTS " + + "SYSREF_TASK_SIGNATURES " + + "SYSREF_TASKS " + + "SYSREF_UNITS " + + "SYSREF_USER_GROUPS " + + "SYSREF_USER_GROUPS_REFERENCE " + + "SYSREF_USER_SUBSTITUTION " + + "SYSREF_USERS " + + "SYSREF_USERS_REFERENCE " + + "SYSREF_VIEWERS " + + "SYSREF_WORKING_TIME_CALENDARS "; + + // Table name + const table_name_constants = + "ACCESS_RIGHTS_TABLE_NAME " + + "EDMS_ACCESS_TABLE_NAME " + + "EDOC_TYPES_TABLE_NAME "; + + // Test + const test_constants = + "TEST_DEV_DB_NAME " + + "TEST_DEV_SYSTEM_CODE " + + "TEST_EDMS_DB_NAME " + + "TEST_EDMS_MAIN_CODE " + + "TEST_EDMS_MAIN_DB_NAME " + + "TEST_EDMS_SECOND_CODE " + + "TEST_EDMS_SECOND_DB_NAME " + + "TEST_EDMS_SYSTEM_CODE " + + "TEST_ISB5_MAIN_CODE " + + "TEST_ISB5_SECOND_CODE " + + "TEST_SQL_SERVER_2005_NAME " + + "TEST_SQL_SERVER_NAME "; + + // Using the dialog windows + const using_the_dialog_windows_constants = + "ATTENTION_CAPTION " + + "cbsCommandLinks " + + "cbsDefault " + + "CONFIRMATION_CAPTION " + + "ERROR_CAPTION " + + "INFORMATION_CAPTION " + + "mrCancel " + + "mrOk "; + + // Using the document + const using_the_document_constants = + "EDOC_VERSION_ACTIVE_STAGE_CODE " + + "EDOC_VERSION_DESIGN_STAGE_CODE " + + "EDOC_VERSION_OBSOLETE_STAGE_CODE "; + + // Using the EA and encryption + const using_the_EA_and_encryption_constants = + "cpDataEnciphermentEnabled " + + "cpDigitalSignatureEnabled " + + "cpID " + + "cpIssuer " + + "cpPluginVersion " + + "cpSerial " + + "cpSubjectName " + + "cpSubjSimpleName " + + "cpValidFromDate " + + "cpValidToDate "; + + // Using the ISBL-editor + const using_the_ISBL_editor_constants = + "ISBL_SYNTAX " + "NO_SYNTAX " + "XML_SYNTAX "; + + // Wait block properties + const wait_block_properties_constants = + "WAIT_BLOCK_AFTER_FINISH_EVENT " + + "WAIT_BLOCK_BEFORE_START_EVENT " + + "WAIT_BLOCK_DEADLINE_PROPERTY " + + "WAIT_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " + + "WAIT_BLOCK_NAME_PROPERTY " + + "WAIT_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY "; + + // SYSRES Common + const sysres_common_constants = + "SYSRES_COMMON " + + "SYSRES_CONST " + + "SYSRES_MBFUNC " + + "SYSRES_SBDATA " + + "SYSRES_SBGUI " + + "SYSRES_SBINTF " + + "SYSRES_SBREFDSC " + + "SYSRES_SQLERRORS " + + "SYSRES_SYSCOMP "; + + // Константы ==> built_in + const CONSTANTS = + sysres_constants + + base_constants + + base_group_name_constants + + decision_block_properties_constants + + file_extension_constants + + job_block_properties_constants + + language_code_constants + + launching_external_applications_constants + + link_kind_constants + + lock_type_constants + + monitor_block_properties_constants + + notice_block_properties_constants + + object_events_constants + + object_params_constants + + other_constants + + privileges_constants + + pseudoreference_code_constants + + requisite_ISBCertificateType_values_constants + + requisite_ISBEDocStorageType_values_constants + + requisite_compType2_values_constants + + requisite_name_constants + + result_constants + + rule_identification_constants + + script_block_properties_constants + + subtask_block_properties_constants + + system_component_constants + + system_dialogs_constants + + system_reference_names_constants + + table_name_constants + + test_constants + + using_the_dialog_windows_constants + + using_the_document_constants + + using_the_EA_and_encryption_constants + + using_the_ISBL_editor_constants + + wait_block_properties_constants + + sysres_common_constants; + + // enum TAccountType + const TAccountType = "atUser atGroup atRole "; + + // enum TActionEnabledMode + const TActionEnabledMode = + "aemEnabledAlways " + + "aemDisabledAlways " + + "aemEnabledOnBrowse " + + "aemEnabledOnEdit " + + "aemDisabledOnBrowseEmpty "; + + // enum TAddPosition + const TAddPosition = "apBegin apEnd "; + + // enum TAlignment + const TAlignment = "alLeft alRight "; + + // enum TAreaShowMode + const TAreaShowMode = + "asmNever " + + "asmNoButCustomize " + + "asmAsLastTime " + + "asmYesButCustomize " + + "asmAlways "; + + // enum TCertificateInvalidationReason + const TCertificateInvalidationReason = "cirCommon cirRevoked "; + + // enum TCertificateType + const TCertificateType = "ctSignature ctEncode ctSignatureEncode "; + + // enum TCheckListBoxItemState + const TCheckListBoxItemState = "clbUnchecked clbChecked clbGrayed "; + + // enum TCloseOnEsc + const TCloseOnEsc = "ceISB ceAlways ceNever "; + + // enum TCompType + const TCompType = + "ctDocument " + + "ctReference " + + "ctScript " + + "ctUnknown " + + "ctReport " + + "ctDialog " + + "ctFunction " + + "ctFolder " + + "ctEDocument " + + "ctTask " + + "ctJob " + + "ctNotice " + + "ctControlJob "; + + // enum TConditionFormat + const TConditionFormat = "cfInternal cfDisplay "; + + // enum TConnectionIntent + const TConnectionIntent = "ciUnspecified ciWrite ciRead "; + + // enum TContentKind + const TContentKind = + "ckFolder " + + "ckEDocument " + + "ckTask " + + "ckJob " + + "ckComponentToken " + + "ckAny " + + "ckReference " + + "ckScript " + + "ckReport " + + "ckDialog "; + + // enum TControlType + const TControlType = + "ctISBLEditor " + + "ctBevel " + + "ctButton " + + "ctCheckListBox " + + "ctComboBox " + + "ctComboEdit " + + "ctGrid " + + "ctDBCheckBox " + + "ctDBComboBox " + + "ctDBEdit " + + "ctDBEllipsis " + + "ctDBMemo " + + "ctDBNavigator " + + "ctDBRadioGroup " + + "ctDBStatusLabel " + + "ctEdit " + + "ctGroupBox " + + "ctInplaceHint " + + "ctMemo " + + "ctPanel " + + "ctListBox " + + "ctRadioButton " + + "ctRichEdit " + + "ctTabSheet " + + "ctWebBrowser " + + "ctImage " + + "ctHyperLink " + + "ctLabel " + + "ctDBMultiEllipsis " + + "ctRibbon " + + "ctRichView " + + "ctInnerPanel " + + "ctPanelGroup " + + "ctBitButton "; + + // enum TCriterionContentType + const TCriterionContentType = + "cctDate " + + "cctInteger " + + "cctNumeric " + + "cctPick " + + "cctReference " + + "cctString " + + "cctText "; + + // enum TCultureType + const TCultureType = "cltInternal cltPrimary cltGUI "; + + // enum TDataSetEventType + const TDataSetEventType = + "dseBeforeOpen " + + "dseAfterOpen " + + "dseBeforeClose " + + "dseAfterClose " + + "dseOnValidDelete " + + "dseBeforeDelete " + + "dseAfterDelete " + + "dseAfterDeleteOutOfTransaction " + + "dseOnDeleteError " + + "dseBeforeInsert " + + "dseAfterInsert " + + "dseOnValidUpdate " + + "dseBeforeUpdate " + + "dseOnUpdateRatifiedRecord " + + "dseAfterUpdate " + + "dseAfterUpdateOutOfTransaction " + + "dseOnUpdateError " + + "dseAfterScroll " + + "dseOnOpenRecord " + + "dseOnCloseRecord " + + "dseBeforeCancel " + + "dseAfterCancel " + + "dseOnUpdateDeadlockError " + + "dseBeforeDetailUpdate " + + "dseOnPrepareUpdate " + + "dseOnAnyRequisiteChange "; + + // enum TDataSetState + const TDataSetState = "dssEdit dssInsert dssBrowse dssInActive "; + + // enum TDateFormatType + const TDateFormatType = "dftDate dftShortDate dftDateTime dftTimeStamp "; + + // enum TDateOffsetType + const TDateOffsetType = "dotDays dotHours dotMinutes dotSeconds "; + + // enum TDateTimeKind + const TDateTimeKind = "dtkndLocal dtkndUTC "; + + // enum TDeaAccessRights + const TDeaAccessRights = "arNone arView arEdit arFull "; + + // enum TDocumentDefaultAction + const TDocumentDefaultAction = "ddaView ddaEdit "; + + // enum TEditMode + const TEditMode = + "emLock " + + "emEdit " + + "emSign " + + "emExportWithLock " + + "emImportWithUnlock " + + "emChangeVersionNote " + + "emOpenForModify " + + "emChangeLifeStage " + + "emDelete " + + "emCreateVersion " + + "emImport " + + "emUnlockExportedWithLock " + + "emStart " + + "emAbort " + + "emReInit " + + "emMarkAsReaded " + + "emMarkAsUnreaded " + + "emPerform " + + "emAccept " + + "emResume " + + "emChangeRights " + + "emEditRoute " + + "emEditObserver " + + "emRecoveryFromLocalCopy " + + "emChangeWorkAccessType " + + "emChangeEncodeTypeToCertificate " + + "emChangeEncodeTypeToPassword " + + "emChangeEncodeTypeToNone " + + "emChangeEncodeTypeToCertificatePassword " + + "emChangeStandardRoute " + + "emGetText " + + "emOpenForView " + + "emMoveToStorage " + + "emCreateObject " + + "emChangeVersionHidden " + + "emDeleteVersion " + + "emChangeLifeCycleStage " + + "emApprovingSign " + + "emExport " + + "emContinue " + + "emLockFromEdit " + + "emUnLockForEdit " + + "emLockForServer " + + "emUnlockFromServer " + + "emDelegateAccessRights " + + "emReEncode "; + + // enum TEditorCloseObservType + const TEditorCloseObservType = "ecotFile ecotProcess "; + + // enum TEdmsApplicationAction + const TEdmsApplicationAction = "eaGet eaCopy eaCreate eaCreateStandardRoute "; + + // enum TEDocumentLockType + const TEDocumentLockType = "edltAll edltNothing edltQuery "; + + // enum TEDocumentStepShowMode + const TEDocumentStepShowMode = "essmText essmCard "; + + // enum TEDocumentStepVersionType + const TEDocumentStepVersionType = "esvtLast esvtLastActive esvtSpecified "; + + // enum TEDocumentStorageFunction + const TEDocumentStorageFunction = "edsfExecutive edsfArchive "; + + // enum TEDocumentStorageType + const TEDocumentStorageType = "edstSQLServer edstFile "; + + // enum TEDocumentVersionSourceType + const TEDocumentVersionSourceType = + "edvstNone edvstEDocumentVersionCopy edvstFile edvstTemplate edvstScannedFile "; + + // enum TEDocumentVersionState + const TEDocumentVersionState = "vsDefault vsDesign vsActive vsObsolete "; + + // enum TEncodeType + const TEncodeType = "etNone etCertificate etPassword etCertificatePassword "; + + // enum TExceptionCategory + const TExceptionCategory = "ecException ecWarning ecInformation "; + + // enum TExportedSignaturesType + const TExportedSignaturesType = "estAll estApprovingOnly "; + + // enum TExportedVersionType + const TExportedVersionType = "evtLast evtLastActive evtQuery "; + + // enum TFieldDataType + const TFieldDataType = + "fdtString " + + "fdtNumeric " + + "fdtInteger " + + "fdtDate " + + "fdtText " + + "fdtUnknown " + + "fdtWideString " + + "fdtLargeInteger "; + + // enum TFolderType + const TFolderType = + "ftInbox " + + "ftOutbox " + + "ftFavorites " + + "ftCommonFolder " + + "ftUserFolder " + + "ftComponents " + + "ftQuickLaunch " + + "ftShortcuts " + + "ftSearch "; + + // enum TGridRowHeight + const TGridRowHeight = "grhAuto " + "grhX1 " + "grhX2 " + "grhX3 "; + + // enum THyperlinkType + const THyperlinkType = "hltText " + "hltRTF " + "hltHTML "; + + // enum TImageFileFormat + const TImageFileFormat = + "iffBMP " + + "iffJPEG " + + "iffMultiPageTIFF " + + "iffSinglePageTIFF " + + "iffTIFF " + + "iffPNG "; + + // enum TImageMode + const TImageMode = "im8bGrayscale " + "im24bRGB " + "im1bMonochrome "; + + // enum TImageType + const TImageType = "itBMP " + "itJPEG " + "itWMF " + "itPNG "; + + // enum TInplaceHintKind + const TInplaceHintKind = + "ikhInformation " + "ikhWarning " + "ikhError " + "ikhNoIcon "; + + // enum TISBLContext + const TISBLContext = + "icUnknown " + + "icScript " + + "icFunction " + + "icIntegratedReport " + + "icAnalyticReport " + + "icDataSetEventHandler " + + "icActionHandler " + + "icFormEventHandler " + + "icLookUpEventHandler " + + "icRequisiteChangeEventHandler " + + "icBeforeSearchEventHandler " + + "icRoleCalculation " + + "icSelectRouteEventHandler " + + "icBlockPropertyCalculation " + + "icBlockQueryParamsEventHandler " + + "icChangeSearchResultEventHandler " + + "icBlockEventHandler " + + "icSubTaskInitEventHandler " + + "icEDocDataSetEventHandler " + + "icEDocLookUpEventHandler " + + "icEDocActionHandler " + + "icEDocFormEventHandler " + + "icEDocRequisiteChangeEventHandler " + + "icStructuredConversionRule " + + "icStructuredConversionEventBefore " + + "icStructuredConversionEventAfter " + + "icWizardEventHandler " + + "icWizardFinishEventHandler " + + "icWizardStepEventHandler " + + "icWizardStepFinishEventHandler " + + "icWizardActionEnableEventHandler " + + "icWizardActionExecuteEventHandler " + + "icCreateJobsHandler " + + "icCreateNoticesHandler " + + "icBeforeLookUpEventHandler " + + "icAfterLookUpEventHandler " + + "icTaskAbortEventHandler " + + "icWorkflowBlockActionHandler " + + "icDialogDataSetEventHandler " + + "icDialogActionHandler " + + "icDialogLookUpEventHandler " + + "icDialogRequisiteChangeEventHandler " + + "icDialogFormEventHandler " + + "icDialogValidCloseEventHandler " + + "icBlockFormEventHandler " + + "icTaskFormEventHandler " + + "icReferenceMethod " + + "icEDocMethod " + + "icDialogMethod " + + "icProcessMessageHandler "; + + // enum TItemShow + const TItemShow = "isShow " + "isHide " + "isByUserSettings "; + + // enum TJobKind + const TJobKind = "jkJob " + "jkNotice " + "jkControlJob "; + + // enum TJoinType + const TJoinType = "jtInner " + "jtLeft " + "jtRight " + "jtFull " + "jtCross "; + + // enum TLabelPos + const TLabelPos = "lbpAbove " + "lbpBelow " + "lbpLeft " + "lbpRight "; + + // enum TLicensingType + const TLicensingType = "eltPerConnection " + "eltPerUser "; + + // enum TLifeCycleStageFontColor + const TLifeCycleStageFontColor = + "sfcUndefined " + + "sfcBlack " + + "sfcGreen " + + "sfcRed " + + "sfcBlue " + + "sfcOrange " + + "sfcLilac "; + + // enum TLifeCycleStageFontStyle + const TLifeCycleStageFontStyle = "sfsItalic " + "sfsStrikeout " + "sfsNormal "; + + // enum TLockableDevelopmentComponentType + const TLockableDevelopmentComponentType = + "ldctStandardRoute " + + "ldctWizard " + + "ldctScript " + + "ldctFunction " + + "ldctRouteBlock " + + "ldctIntegratedReport " + + "ldctAnalyticReport " + + "ldctReferenceType " + + "ldctEDocumentType " + + "ldctDialog " + + "ldctServerEvents "; + + // enum TMaxRecordCountRestrictionType + const TMaxRecordCountRestrictionType = + "mrcrtNone " + "mrcrtUser " + "mrcrtMaximal " + "mrcrtCustom "; + + // enum TRangeValueType + const TRangeValueType = + "vtEqual " + "vtGreaterOrEqual " + "vtLessOrEqual " + "vtRange "; + + // enum TRelativeDate + const TRelativeDate = + "rdYesterday " + + "rdToday " + + "rdTomorrow " + + "rdThisWeek " + + "rdThisMonth " + + "rdThisYear " + + "rdNextMonth " + + "rdNextWeek " + + "rdLastWeek " + + "rdLastMonth "; + + // enum TReportDestination + const TReportDestination = "rdWindow " + "rdFile " + "rdPrinter "; + + // enum TReqDataType + const TReqDataType = + "rdtString " + + "rdtNumeric " + + "rdtInteger " + + "rdtDate " + + "rdtReference " + + "rdtAccount " + + "rdtText " + + "rdtPick " + + "rdtUnknown " + + "rdtLargeInteger " + + "rdtDocument "; + + // enum TRequisiteEventType + const TRequisiteEventType = "reOnChange " + "reOnChangeValues "; + + // enum TSBTimeType + const TSBTimeType = "ttGlobal " + "ttLocal " + "ttUser " + "ttSystem "; + + // enum TSearchShowMode + const TSearchShowMode = + "ssmBrowse " + "ssmSelect " + "ssmMultiSelect " + "ssmBrowseModal "; + + // enum TSelectMode + const TSelectMode = "smSelect " + "smLike " + "smCard "; + + // enum TSignatureType + const TSignatureType = "stNone " + "stAuthenticating " + "stApproving "; + + // enum TSignerContentType + const TSignerContentType = "sctString " + "sctStream "; + + // enum TStringsSortType + const TStringsSortType = "sstAnsiSort " + "sstNaturalSort "; + + // enum TStringValueType + const TStringValueType = "svtEqual " + "svtContain "; + + // enum TStructuredObjectAttributeType + const TStructuredObjectAttributeType = + "soatString " + + "soatNumeric " + + "soatInteger " + + "soatDatetime " + + "soatReferenceRecord " + + "soatText " + + "soatPick " + + "soatBoolean " + + "soatEDocument " + + "soatAccount " + + "soatIntegerCollection " + + "soatNumericCollection " + + "soatStringCollection " + + "soatPickCollection " + + "soatDatetimeCollection " + + "soatBooleanCollection " + + "soatReferenceRecordCollection " + + "soatEDocumentCollection " + + "soatAccountCollection " + + "soatContents " + + "soatUnknown "; + + // enum TTaskAbortReason + const TTaskAbortReason = "tarAbortByUser " + "tarAbortByWorkflowException "; + + // enum TTextValueType + const TTextValueType = "tvtAllWords " + "tvtExactPhrase " + "tvtAnyWord "; + + // enum TUserObjectStatus + const TUserObjectStatus = + "usNone " + + "usCompleted " + + "usRedSquare " + + "usBlueSquare " + + "usYellowSquare " + + "usGreenSquare " + + "usOrangeSquare " + + "usPurpleSquare " + + "usFollowUp "; + + // enum TUserType + const TUserType = + "utUnknown " + + "utUser " + + "utDeveloper " + + "utAdministrator " + + "utSystemDeveloper " + + "utDisconnected "; + + // enum TValuesBuildType + const TValuesBuildType = + "btAnd " + "btDetailAnd " + "btOr " + "btNotOr " + "btOnly "; + + // enum TViewMode + const TViewMode = "vmView " + "vmSelect " + "vmNavigation "; + + // enum TViewSelectionMode + const TViewSelectionMode = + "vsmSingle " + "vsmMultiple " + "vsmMultipleCheck " + "vsmNoSelection "; + + // enum TWizardActionType + const TWizardActionType = + "wfatPrevious " + "wfatNext " + "wfatCancel " + "wfatFinish "; + + // enum TWizardFormElementProperty + const TWizardFormElementProperty = + "wfepUndefined " + + "wfepText3 " + + "wfepText6 " + + "wfepText9 " + + "wfepSpinEdit " + + "wfepDropDown " + + "wfepRadioGroup " + + "wfepFlag " + + "wfepText12 " + + "wfepText15 " + + "wfepText18 " + + "wfepText21 " + + "wfepText24 " + + "wfepText27 " + + "wfepText30 " + + "wfepRadioGroupColumn1 " + + "wfepRadioGroupColumn2 " + + "wfepRadioGroupColumn3 "; + + // enum TWizardFormElementType + const TWizardFormElementType = + "wfetQueryParameter " + "wfetText " + "wfetDelimiter " + "wfetLabel "; + + // enum TWizardParamType + const TWizardParamType = + "wptString " + + "wptInteger " + + "wptNumeric " + + "wptBoolean " + + "wptDateTime " + + "wptPick " + + "wptText " + + "wptUser " + + "wptUserList " + + "wptEDocumentInfo " + + "wptEDocumentInfoList " + + "wptReferenceRecordInfo " + + "wptReferenceRecordInfoList " + + "wptFolderInfo " + + "wptTaskInfo " + + "wptContents " + + "wptFileName " + + "wptDate "; + + // enum TWizardStepResult + const TWizardStepResult = + "wsrComplete " + + "wsrGoNext " + + "wsrGoPrevious " + + "wsrCustom " + + "wsrCancel " + + "wsrGoFinal "; + + // enum TWizardStepType + const TWizardStepType = + "wstForm " + + "wstEDocument " + + "wstTaskCard " + + "wstReferenceRecordCard " + + "wstFinal "; + + // enum TWorkAccessType + const TWorkAccessType = "waAll " + "waPerformers " + "waManual "; + + // enum TWorkflowBlockType + const TWorkflowBlockType = + "wsbStart " + + "wsbFinish " + + "wsbNotice " + + "wsbStep " + + "wsbDecision " + + "wsbWait " + + "wsbMonitor " + + "wsbScript " + + "wsbConnector " + + "wsbSubTask " + + "wsbLifeCycleStage " + + "wsbPause "; + + // enum TWorkflowDataType + const TWorkflowDataType = + "wdtInteger " + + "wdtFloat " + + "wdtString " + + "wdtPick " + + "wdtDateTime " + + "wdtBoolean " + + "wdtTask " + + "wdtJob " + + "wdtFolder " + + "wdtEDocument " + + "wdtReferenceRecord " + + "wdtUser " + + "wdtGroup " + + "wdtRole " + + "wdtIntegerCollection " + + "wdtFloatCollection " + + "wdtStringCollection " + + "wdtPickCollection " + + "wdtDateTimeCollection " + + "wdtBooleanCollection " + + "wdtTaskCollection " + + "wdtJobCollection " + + "wdtFolderCollection " + + "wdtEDocumentCollection " + + "wdtReferenceRecordCollection " + + "wdtUserCollection " + + "wdtGroupCollection " + + "wdtRoleCollection " + + "wdtContents " + + "wdtUserList " + + "wdtSearchDescription " + + "wdtDeadLine " + + "wdtPickSet " + + "wdtAccountCollection "; + + // enum TWorkImportance + const TWorkImportance = "wiLow " + "wiNormal " + "wiHigh "; + + // enum TWorkRouteType + const TWorkRouteType = "wrtSoft " + "wrtHard "; + + // enum TWorkState + const TWorkState = + "wsInit " + + "wsRunning " + + "wsDone " + + "wsControlled " + + "wsAborted " + + "wsContinued "; + + // enum TWorkTextBuildingMode + const TWorkTextBuildingMode = + "wtmFull " + "wtmFromCurrent " + "wtmOnlyCurrent "; + + // Перечисления + const ENUMS = + TAccountType + + TActionEnabledMode + + TAddPosition + + TAlignment + + TAreaShowMode + + TCertificateInvalidationReason + + TCertificateType + + TCheckListBoxItemState + + TCloseOnEsc + + TCompType + + TConditionFormat + + TConnectionIntent + + TContentKind + + TControlType + + TCriterionContentType + + TCultureType + + TDataSetEventType + + TDataSetState + + TDateFormatType + + TDateOffsetType + + TDateTimeKind + + TDeaAccessRights + + TDocumentDefaultAction + + TEditMode + + TEditorCloseObservType + + TEdmsApplicationAction + + TEDocumentLockType + + TEDocumentStepShowMode + + TEDocumentStepVersionType + + TEDocumentStorageFunction + + TEDocumentStorageType + + TEDocumentVersionSourceType + + TEDocumentVersionState + + TEncodeType + + TExceptionCategory + + TExportedSignaturesType + + TExportedVersionType + + TFieldDataType + + TFolderType + + TGridRowHeight + + THyperlinkType + + TImageFileFormat + + TImageMode + + TImageType + + TInplaceHintKind + + TISBLContext + + TItemShow + + TJobKind + + TJoinType + + TLabelPos + + TLicensingType + + TLifeCycleStageFontColor + + TLifeCycleStageFontStyle + + TLockableDevelopmentComponentType + + TMaxRecordCountRestrictionType + + TRangeValueType + + TRelativeDate + + TReportDestination + + TReqDataType + + TRequisiteEventType + + TSBTimeType + + TSearchShowMode + + TSelectMode + + TSignatureType + + TSignerContentType + + TStringsSortType + + TStringValueType + + TStructuredObjectAttributeType + + TTaskAbortReason + + TTextValueType + + TUserObjectStatus + + TUserType + + TValuesBuildType + + TViewMode + + TViewSelectionMode + + TWizardActionType + + TWizardFormElementProperty + + TWizardFormElementType + + TWizardParamType + + TWizardStepResult + + TWizardStepType + + TWorkAccessType + + TWorkflowBlockType + + TWorkflowDataType + + TWorkImportance + + TWorkRouteType + + TWorkState + + TWorkTextBuildingMode; + + // Системные функции ==> SYSFUNCTIONS + const system_functions = + "AddSubString " + + "AdjustLineBreaks " + + "AmountInWords " + + "Analysis " + + "ArrayDimCount " + + "ArrayHighBound " + + "ArrayLowBound " + + "ArrayOf " + + "ArrayReDim " + + "Assert " + + "Assigned " + + "BeginOfMonth " + + "BeginOfPeriod " + + "BuildProfilingOperationAnalysis " + + "CallProcedure " + + "CanReadFile " + + "CArrayElement " + + "CDataSetRequisite " + + "ChangeDate " + + "ChangeReferenceDataset " + + "Char " + + "CharPos " + + "CheckParam " + + "CheckParamValue " + + "CompareStrings " + + "ConstantExists " + + "ControlState " + + "ConvertDateStr " + + "Copy " + + "CopyFile " + + "CreateArray " + + "CreateCachedReference " + + "CreateConnection " + + "CreateDialog " + + "CreateDualListDialog " + + "CreateEditor " + + "CreateException " + + "CreateFile " + + "CreateFolderDialog " + + "CreateInputDialog " + + "CreateLinkFile " + + "CreateList " + + "CreateLock " + + "CreateMemoryDataSet " + + "CreateObject " + + "CreateOpenDialog " + + "CreateProgress " + + "CreateQuery " + + "CreateReference " + + "CreateReport " + + "CreateSaveDialog " + + "CreateScript " + + "CreateSQLPivotFunction " + + "CreateStringList " + + "CreateTreeListSelectDialog " + + "CSelectSQL " + + "CSQL " + + "CSubString " + + "CurrentUserID " + + "CurrentUserName " + + "CurrentVersion " + + "DataSetLocateEx " + + "DateDiff " + + "DateTimeDiff " + + "DateToStr " + + "DayOfWeek " + + "DeleteFile " + + "DirectoryExists " + + "DisableCheckAccessRights " + + "DisableCheckFullShowingRestriction " + + "DisableMassTaskSendingRestrictions " + + "DropTable " + + "DupeString " + + "EditText " + + "EnableCheckAccessRights " + + "EnableCheckFullShowingRestriction " + + "EnableMassTaskSendingRestrictions " + + "EndOfMonth " + + "EndOfPeriod " + + "ExceptionExists " + + "ExceptionsOff " + + "ExceptionsOn " + + "Execute " + + "ExecuteProcess " + + "Exit " + + "ExpandEnvironmentVariables " + + "ExtractFileDrive " + + "ExtractFileExt " + + "ExtractFileName " + + "ExtractFilePath " + + "ExtractParams " + + "FileExists " + + "FileSize " + + "FindFile " + + "FindSubString " + + "FirmContext " + + "ForceDirectories " + + "Format " + + "FormatDate " + + "FormatNumeric " + + "FormatSQLDate " + + "FormatString " + + "FreeException " + + "GetComponent " + + "GetComponentLaunchParam " + + "GetConstant " + + "GetLastException " + + "GetReferenceRecord " + + "GetRefTypeByRefID " + + "GetTableID " + + "GetTempFolder " + + "IfThen " + + "In " + + "IndexOf " + + "InputDialog " + + "InputDialogEx " + + "InteractiveMode " + + "IsFileLocked " + + "IsGraphicFile " + + "IsNumeric " + + "Length " + + "LoadString " + + "LoadStringFmt " + + "LocalTimeToUTC " + + "LowerCase " + + "Max " + + "MessageBox " + + "MessageBoxEx " + + "MimeDecodeBinary " + + "MimeDecodeString " + + "MimeEncodeBinary " + + "MimeEncodeString " + + "Min " + + "MoneyInWords " + + "MoveFile " + + "NewID " + + "Now " + + "OpenFile " + + "Ord " + + "Precision " + + "Raise " + + "ReadCertificateFromFile " + + "ReadFile " + + "ReferenceCodeByID " + + "ReferenceNumber " + + "ReferenceRequisiteMode " + + "ReferenceRequisiteValue " + + "RegionDateSettings " + + "RegionNumberSettings " + + "RegionTimeSettings " + + "RegRead " + + "RegWrite " + + "RenameFile " + + "Replace " + + "Round " + + "SelectServerCode " + + "SelectSQL " + + "ServerDateTime " + + "SetConstant " + + "SetManagedFolderFieldsState " + + "ShowConstantsInputDialog " + + "ShowMessage " + + "Sleep " + + "Split " + + "SQL " + + "SQL2XLSTAB " + + "SQLProfilingSendReport " + + "StrToDate " + + "SubString " + + "SubStringCount " + + "SystemSetting " + + "Time " + + "TimeDiff " + + "Today " + + "Transliterate " + + "Trim " + + "UpperCase " + + "UserStatus " + + "UTCToLocalTime " + + "ValidateXML " + + "VarIsClear " + + "VarIsEmpty " + + "VarIsNull " + + "WorkTimeDiff " + + "WriteFile " + + "WriteFileEx " + + "WriteObjectHistory " + + "Анализ " + + "БазаДанных " + + "БлокЕсть " + + "БлокЕстьРасш " + + "БлокИнфо " + + "БлокСнять " + + "БлокСнятьРасш " + + "БлокУстановить " + + "Ввод " + + "ВводМеню " + + "ВедС " + + "ВедСпр " + + "ВерхняяГраницаМассива " + + "ВнешПрогр " + + "Восст " + + "ВременнаяПапка " + + "Время " + + "ВыборSQL " + + "ВыбратьЗапись " + + "ВыделитьСтр " + + "Вызвать " + + "Выполнить " + + "ВыпПрогр " + + "ГрафическийФайл " + + "ГруппаДополнительно " + + "ДатаВремяСерв " + + "ДеньНедели " + + "ДиалогДаНет " + + "ДлинаСтр " + + "ДобПодстр " + + "ЕПусто " + + "ЕслиТо " + + "ЕЧисло " + + "ЗамПодстр " + + "ЗаписьСправочника " + + "ЗначПоляСпр " + + "ИДТипСпр " + + "ИзвлечьДиск " + + "ИзвлечьИмяФайла " + + "ИзвлечьПуть " + + "ИзвлечьРасширение " + + "ИзмДат " + + "ИзменитьРазмерМассива " + + "ИзмеренийМассива " + + "ИмяОрг " + + "ИмяПоляСпр " + + "Индекс " + + "ИндикаторЗакрыть " + + "ИндикаторОткрыть " + + "ИндикаторШаг " + + "ИнтерактивныйРежим " + + "ИтогТблСпр " + + "КодВидВедСпр " + + "КодВидСпрПоИД " + + "КодПоAnalit " + + "КодСимвола " + + "КодСпр " + + "КолПодстр " + + "КолПроп " + + "КонМес " + + "Конст " + + "КонстЕсть " + + "КонстЗнач " + + "КонТран " + + "КопироватьФайл " + + "КопияСтр " + + "КПериод " + + "КСтрТблСпр " + + "Макс " + + "МаксСтрТблСпр " + + "Массив " + + "Меню " + + "МенюРасш " + + "Мин " + + "НаборДанныхНайтиРасш " + + "НаимВидСпр " + + "НаимПоAnalit " + + "НаимСпр " + + "НастроитьПереводыСтрок " + + "НачМес " + + "НачТран " + + "НижняяГраницаМассива " + + "НомерСпр " + + "НПериод " + + "Окно " + + "Окр " + + "Окружение " + + "ОтлИнфДобавить " + + "ОтлИнфУдалить " + + "Отчет " + + "ОтчетАнал " + + "ОтчетИнт " + + "ПапкаСуществует " + + "Пауза " + + "ПВыборSQL " + + "ПереименоватьФайл " + + "Переменные " + + "ПереместитьФайл " + + "Подстр " + + "ПоискПодстр " + + "ПоискСтр " + + "ПолучитьИДТаблицы " + + "ПользовательДополнительно " + + "ПользовательИД " + + "ПользовательИмя " + + "ПользовательСтатус " + + "Прервать " + + "ПроверитьПараметр " + + "ПроверитьПараметрЗнач " + + "ПроверитьУсловие " + + "РазбСтр " + + "РазнВремя " + + "РазнДат " + + "РазнДатаВремя " + + "РазнРабВремя " + + "РегУстВрем " + + "РегУстДат " + + "РегУстЧсл " + + "РедТекст " + + "РеестрЗапись " + + "РеестрСписокИменПарам " + + "РеестрЧтение " + + "РеквСпр " + + "РеквСпрПр " + + "Сегодня " + + "Сейчас " + + "Сервер " + + "СерверПроцессИД " + + "СертификатФайлСчитать " + + "СжПроб " + + "Символ " + + "СистемаДиректумКод " + + "СистемаИнформация " + + "СистемаКод " + + "Содержит " + + "СоединениеЗакрыть " + + "СоединениеОткрыть " + + "СоздатьДиалог " + + "СоздатьДиалогВыбораИзДвухСписков " + + "СоздатьДиалогВыбораПапки " + + "СоздатьДиалогОткрытияФайла " + + "СоздатьДиалогСохраненияФайла " + + "СоздатьЗапрос " + + "СоздатьИндикатор " + + "СоздатьИсключение " + + "СоздатьКэшированныйСправочник " + + "СоздатьМассив " + + "СоздатьНаборДанных " + + "СоздатьОбъект " + + "СоздатьОтчет " + + "СоздатьПапку " + + "СоздатьРедактор " + + "СоздатьСоединение " + + "СоздатьСписок " + + "СоздатьСписокСтрок " + + "СоздатьСправочник " + + "СоздатьСценарий " + + "СоздСпр " + + "СостСпр " + + "Сохр " + + "СохрСпр " + + "СписокСистем " + + "Спр " + + "Справочник " + + "СпрБлокЕсть " + + "СпрБлокСнять " + + "СпрБлокСнятьРасш " + + "СпрБлокУстановить " + + "СпрИзмНабДан " + + "СпрКод " + + "СпрНомер " + + "СпрОбновить " + + "СпрОткрыть " + + "СпрОтменить " + + "СпрПарам " + + "СпрПолеЗнач " + + "СпрПолеИмя " + + "СпрРекв " + + "СпрРеквВведЗн " + + "СпрРеквНовые " + + "СпрРеквПр " + + "СпрРеквПредЗн " + + "СпрРеквРежим " + + "СпрРеквТипТекст " + + "СпрСоздать " + + "СпрСост " + + "СпрСохранить " + + "СпрТблИтог " + + "СпрТблСтр " + + "СпрТблСтрКол " + + "СпрТблСтрМакс " + + "СпрТблСтрМин " + + "СпрТблСтрПред " + + "СпрТблСтрСлед " + + "СпрТблСтрСозд " + + "СпрТблСтрУд " + + "СпрТекПредст " + + "СпрУдалить " + + "СравнитьСтр " + + "СтрВерхРегистр " + + "СтрНижнРегистр " + + "СтрТблСпр " + + "СумПроп " + + "Сценарий " + + "СценарийПарам " + + "ТекВерсия " + + "ТекОрг " + + "Точн " + + "Тран " + + "Транслитерация " + + "УдалитьТаблицу " + + "УдалитьФайл " + + "УдСпр " + + "УдСтрТблСпр " + + "Уст " + + "УстановкиКонстант " + + "ФайлАтрибутСчитать " + + "ФайлАтрибутУстановить " + + "ФайлВремя " + + "ФайлВремяУстановить " + + "ФайлВыбрать " + + "ФайлЗанят " + + "ФайлЗаписать " + + "ФайлИскать " + + "ФайлКопировать " + + "ФайлМожноЧитать " + + "ФайлОткрыть " + + "ФайлПереименовать " + + "ФайлПерекодировать " + + "ФайлПереместить " + + "ФайлПросмотреть " + + "ФайлРазмер " + + "ФайлСоздать " + + "ФайлСсылкаСоздать " + + "ФайлСуществует " + + "ФайлСчитать " + + "ФайлУдалить " + + "ФмтSQLДат " + + "ФмтДат " + + "ФмтСтр " + + "ФмтЧсл " + + "Формат " + + "ЦМассивЭлемент " + + "ЦНаборДанныхРеквизит " + + "ЦПодстр "; + + // Предопределенные переменные ==> built_in + const predefined_variables = + "AltState " + + "Application " + + "CallType " + + "ComponentTokens " + + "CreatedJobs " + + "CreatedNotices " + + "ControlState " + + "DialogResult " + + "Dialogs " + + "EDocuments " + + "EDocumentVersionSource " + + "Folders " + + "GlobalIDs " + + "Job " + + "Jobs " + + "InputValue " + + "LookUpReference " + + "LookUpRequisiteNames " + + "LookUpSearch " + + "Object " + + "ParentComponent " + + "Processes " + + "References " + + "Requisite " + + "ReportName " + + "Reports " + + "Result " + + "Scripts " + + "Searches " + + "SelectedAttachments " + + "SelectedItems " + + "SelectMode " + + "Sender " + + "ServerEvents " + + "ServiceFactory " + + "ShiftState " + + "SubTask " + + "SystemDialogs " + + "Tasks " + + "Wizard " + + "Wizards " + + "Work " + + "ВызовСпособ " + + "ИмяОтчета " + + "РеквЗнач "; + + // Интерфейсы ==> type + const interfaces = + "IApplication " + + "IAccessRights " + + "IAccountRepository " + + "IAccountSelectionRestrictions " + + "IAction " + + "IActionList " + + "IAdministrationHistoryDescription " + + "IAnchors " + + "IApplication " + + "IArchiveInfo " + + "IAttachment " + + "IAttachmentList " + + "ICheckListBox " + + "ICheckPointedList " + + "IColumn " + + "IComponent " + + "IComponentDescription " + + "IComponentToken " + + "IComponentTokenFactory " + + "IComponentTokenInfo " + + "ICompRecordInfo " + + "IConnection " + + "IContents " + + "IControl " + + "IControlJob " + + "IControlJobInfo " + + "IControlList " + + "ICrypto " + + "ICrypto2 " + + "ICustomJob " + + "ICustomJobInfo " + + "ICustomListBox " + + "ICustomObjectWizardStep " + + "ICustomWork " + + "ICustomWorkInfo " + + "IDataSet " + + "IDataSetAccessInfo " + + "IDataSigner " + + "IDateCriterion " + + "IDateRequisite " + + "IDateRequisiteDescription " + + "IDateValue " + + "IDeaAccessRights " + + "IDeaObjectInfo " + + "IDevelopmentComponentLock " + + "IDialog " + + "IDialogFactory " + + "IDialogPickRequisiteItems " + + "IDialogsFactory " + + "IDICSFactory " + + "IDocRequisite " + + "IDocumentInfo " + + "IDualListDialog " + + "IECertificate " + + "IECertificateInfo " + + "IECertificates " + + "IEditControl " + + "IEditorForm " + + "IEdmsExplorer " + + "IEdmsObject " + + "IEdmsObjectDescription " + + "IEdmsObjectFactory " + + "IEdmsObjectInfo " + + "IEDocument " + + "IEDocumentAccessRights " + + "IEDocumentDescription " + + "IEDocumentEditor " + + "IEDocumentFactory " + + "IEDocumentInfo " + + "IEDocumentStorage " + + "IEDocumentVersion " + + "IEDocumentVersionListDialog " + + "IEDocumentVersionSource " + + "IEDocumentWizardStep " + + "IEDocVerSignature " + + "IEDocVersionState " + + "IEnabledMode " + + "IEncodeProvider " + + "IEncrypter " + + "IEvent " + + "IEventList " + + "IException " + + "IExternalEvents " + + "IExternalHandler " + + "IFactory " + + "IField " + + "IFileDialog " + + "IFolder " + + "IFolderDescription " + + "IFolderDialog " + + "IFolderFactory " + + "IFolderInfo " + + "IForEach " + + "IForm " + + "IFormTitle " + + "IFormWizardStep " + + "IGlobalIDFactory " + + "IGlobalIDInfo " + + "IGrid " + + "IHasher " + + "IHistoryDescription " + + "IHyperLinkControl " + + "IImageButton " + + "IImageControl " + + "IInnerPanel " + + "IInplaceHint " + + "IIntegerCriterion " + + "IIntegerList " + + "IIntegerRequisite " + + "IIntegerValue " + + "IISBLEditorForm " + + "IJob " + + "IJobDescription " + + "IJobFactory " + + "IJobForm " + + "IJobInfo " + + "ILabelControl " + + "ILargeIntegerCriterion " + + "ILargeIntegerRequisite " + + "ILargeIntegerValue " + + "ILicenseInfo " + + "ILifeCycleStage " + + "IList " + + "IListBox " + + "ILocalIDInfo " + + "ILocalization " + + "ILock " + + "IMemoryDataSet " + + "IMessagingFactory " + + "IMetadataRepository " + + "INotice " + + "INoticeInfo " + + "INumericCriterion " + + "INumericRequisite " + + "INumericValue " + + "IObject " + + "IObjectDescription " + + "IObjectImporter " + + "IObjectInfo " + + "IObserver " + + "IPanelGroup " + + "IPickCriterion " + + "IPickProperty " + + "IPickRequisite " + + "IPickRequisiteDescription " + + "IPickRequisiteItem " + + "IPickRequisiteItems " + + "IPickValue " + + "IPrivilege " + + "IPrivilegeList " + + "IProcess " + + "IProcessFactory " + + "IProcessMessage " + + "IProgress " + + "IProperty " + + "IPropertyChangeEvent " + + "IQuery " + + "IReference " + + "IReferenceCriterion " + + "IReferenceEnabledMode " + + "IReferenceFactory " + + "IReferenceHistoryDescription " + + "IReferenceInfo " + + "IReferenceRecordCardWizardStep " + + "IReferenceRequisiteDescription " + + "IReferencesFactory " + + "IReferenceValue " + + "IRefRequisite " + + "IReport " + + "IReportFactory " + + "IRequisite " + + "IRequisiteDescription " + + "IRequisiteDescriptionList " + + "IRequisiteFactory " + + "IRichEdit " + + "IRouteStep " + + "IRule " + + "IRuleList " + + "ISchemeBlock " + + "IScript " + + "IScriptFactory " + + "ISearchCriteria " + + "ISearchCriterion " + + "ISearchDescription " + + "ISearchFactory " + + "ISearchFolderInfo " + + "ISearchForObjectDescription " + + "ISearchResultRestrictions " + + "ISecuredContext " + + "ISelectDialog " + + "IServerEvent " + + "IServerEventFactory " + + "IServiceDialog " + + "IServiceFactory " + + "ISignature " + + "ISignProvider " + + "ISignProvider2 " + + "ISignProvider3 " + + "ISimpleCriterion " + + "IStringCriterion " + + "IStringList " + + "IStringRequisite " + + "IStringRequisiteDescription " + + "IStringValue " + + "ISystemDialogsFactory " + + "ISystemInfo " + + "ITabSheet " + + "ITask " + + "ITaskAbortReasonInfo " + + "ITaskCardWizardStep " + + "ITaskDescription " + + "ITaskFactory " + + "ITaskInfo " + + "ITaskRoute " + + "ITextCriterion " + + "ITextRequisite " + + "ITextValue " + + "ITreeListSelectDialog " + + "IUser " + + "IUserList " + + "IValue " + + "IView " + + "IWebBrowserControl " + + "IWizard " + + "IWizardAction " + + "IWizardFactory " + + "IWizardFormElement " + + "IWizardParam " + + "IWizardPickParam " + + "IWizardReferenceParam " + + "IWizardStep " + + "IWorkAccessRights " + + "IWorkDescription " + + "IWorkflowAskableParam " + + "IWorkflowAskableParams " + + "IWorkflowBlock " + + "IWorkflowBlockResult " + + "IWorkflowEnabledMode " + + "IWorkflowParam " + + "IWorkflowPickParam " + + "IWorkflowReferenceParam " + + "IWorkState " + + "IWorkTreeCustomNode " + + "IWorkTreeJobNode " + + "IWorkTreeTaskNode " + + "IXMLEditorForm " + + "SBCrypto "; + + // built_in : встроенные или библиотечные объекты (константы, перечисления) + const BUILTIN = CONSTANTS + ENUMS; + + // class: встроенные наборы значений, системные объекты, фабрики + const CLASS = predefined_variables; + + // literal : примитивные типы + const LITERAL = "null true false nil "; + + // number : числа + const NUMBERS = { + className: "number", + begin: hljs.NUMBER_RE, + relevance: 0 + }; + + // string : строки + const STRINGS = { + className: "string", + variants: [ + { + begin: '"', + end: '"' + }, + { + begin: "'", + end: "'" + } + ] + }; + + // Токены + const DOCTAGS = { + className: "doctag", + begin: "\\b(?:TODO|DONE|BEGIN|END|STUB|CHG|FIXME|NOTE|BUG|XXX)\\b", + relevance: 0 + }; + + // Однострочный комментарий + const ISBL_LINE_COMMENT_MODE = { + className: "comment", + begin: "//", + end: "$", + relevance: 0, + contains: [ + hljs.PHRASAL_WORDS_MODE, + DOCTAGS + ] + }; + + // Многострочный комментарий + const ISBL_BLOCK_COMMENT_MODE = { + className: "comment", + begin: "/\\*", + end: "\\*/", + relevance: 0, + contains: [ + hljs.PHRASAL_WORDS_MODE, + DOCTAGS + ] + }; + + // comment : комментарии + const COMMENTS = { + variants: [ + ISBL_LINE_COMMENT_MODE, + ISBL_BLOCK_COMMENT_MODE + ] + }; + + // keywords : ключевые слова + const KEYWORDS = { + $pattern: UNDERSCORE_IDENT_RE, + keyword: KEYWORD, + built_in: BUILTIN, + class: CLASS, + literal: LITERAL + }; + + // methods : методы + const METHODS = { + begin: "\\.\\s*" + hljs.UNDERSCORE_IDENT_RE, + keywords: KEYWORDS, + relevance: 0 + }; + + // type : встроенные типы + const TYPES = { + className: "type", + begin: ":[ \\t]*(" + interfaces.trim().replace(/\s/g, "|") + ")", + end: "[ \\t]*=", + excludeEnd: true + }; + + // variables : переменные + const VARIABLES = { + className: "variable", + keywords: KEYWORDS, + begin: UNDERSCORE_IDENT_RE, + relevance: 0, + contains: [ + TYPES, + METHODS + ] + }; + + // Имена функций + const FUNCTION_TITLE = FUNCTION_NAME_IDENT_RE + "\\("; + + const TITLE_MODE = { + className: "title", + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + built_in: system_functions + }, + begin: FUNCTION_TITLE, + end: "\\(", + returnBegin: true, + excludeEnd: true + }; + + // function : функции + const FUNCTIONS = { + className: "function", + begin: FUNCTION_TITLE, + end: "\\)$", + returnBegin: true, + keywords: KEYWORDS, + illegal: "[\\[\\]\\|\\$\\?%,~#@]", + contains: [ + TITLE_MODE, + METHODS, + VARIABLES, + STRINGS, + NUMBERS, + COMMENTS + ] + }; + + return { + name: 'ISBL', + case_insensitive: true, + keywords: KEYWORDS, + illegal: "\\$|\\?|%|,|;$|~|#|@| { + +/* + Language: JBoss CLI + Author: Raphaël Parrëe + Description: language definition jboss cli + Website: https://docs.jboss.org/author/display/WFLY/Command+Line+Interface + Category: config + */ + +function jbossCli(hljs) { + const PARAM = { + begin: /[\w-]+ *=/, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'attr', + begin: /[\w-]+/ + } + ] + }; + const PARAMSBLOCK = { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [PARAM], + relevance: 0 + }; + const OPERATION = { + className: 'function', + begin: /:[\w\-.]+/, + relevance: 0 + }; + const PATH = { + className: 'string', + begin: /\B([\/.])[\w\-.\/=]+/ + }; + const COMMAND_PARAMS = { + className: 'params', + begin: /--[\w\-=\/]+/ + }; + return { + name: 'JBoss CLI', + aliases: ['wildfly-cli'], + keywords: { + $pattern: '[a-z\-]+', + keyword: 'alias batch cd clear command connect connection-factory connection-info data-source deploy ' + + 'deployment-info deployment-overlay echo echo-dmr help history if jdbc-driver-info jms-queue|20 jms-topic|20 ls ' + + 'patch pwd quit read-attribute read-operation reload rollout-plan run-batch set shutdown try unalias ' + + 'undeploy unset version xa-data-source', // module + literal: 'true false' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + COMMAND_PARAMS, + OPERATION, + PATH, + PARAMSBLOCK + ] + }; +} + +module.exports = jbossCli; + + +/***/ }), + +/***/ 7802: +/***/ ((module) => { + +/* +Language: JSON +Description: JSON (JavaScript Object Notation) is a lightweight data-interchange format. +Author: Ivan Sagalaev +Website: http://www.json.org +Category: common, protocols +*/ + +function json(hljs) { + const LITERALS = { + literal: 'true false null' + }; + const ALLOWED_COMMENTS = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ]; + const TYPES = [ + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ]; + const VALUE_CONTAINER = { + end: ',', + endsWithParent: true, + excludeEnd: true, + contains: TYPES, + keywords: LITERALS + }; + const OBJECT = { + begin: /\{/, + end: /\}/, + contains: [ + { + className: 'attr', + begin: /"/, + end: /"/, + contains: [hljs.BACKSLASH_ESCAPE], + illegal: '\\n' + }, + hljs.inherit(VALUE_CONTAINER, { + begin: /:/ + }) + ].concat(ALLOWED_COMMENTS), + illegal: '\\S' + }; + const ARRAY = { + begin: '\\[', + end: '\\]', + contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents + illegal: '\\S' + }; + TYPES.push(OBJECT, ARRAY); + ALLOWED_COMMENTS.forEach(function(rule) { + TYPES.push(rule); + }); + return { + name: 'JSON', + contains: TYPES, + keywords: LITERALS, + illegal: '\\S' + }; +} + +module.exports = json; + + +/***/ }), + +/***/ 64109: +/***/ ((module) => { + +/* +Language: Julia REPL +Description: Julia REPL sessions +Author: Morten Piibeleht +Website: https://julialang.org +Requires: julia.js + +The Julia REPL code blocks look something like the following: + + julia> function foo(x) + x + 1 + end + foo (generic function with 1 method) + +They start on a new line with "julia>". Usually there should also be a space after this, but +we also allow the code to start right after the > character. The code may run over multiple +lines, but the additional lines must start with six spaces (i.e. be indented to match +"julia>"). The rest of the code is assumed to be output from the executed code and will be +left un-highlighted. + +Using simply spaces to identify line continuations may get a false-positive if the output +also prints out six spaces, but such cases should be rare. +*/ + +function juliaRepl(hljs) { + return { + name: 'Julia REPL', + contains: [ + { + className: 'meta', + begin: /^julia>/, + relevance: 10, + starts: { + // end the highlighting if we are on a new line and the line does not have at + // least six spaces in the beginning + end: /^(?![ ]{6})/, + subLanguage: 'julia' + }, + // jldoctest Markdown blocks are used in the Julia manual and package docs indicate + // code snippets that should be verified when the documentation is built. They can be + // either REPL-like or script-like, but are usually REPL-like and therefore we apply + // julia-repl highlighting to them. More information can be found in Documenter's + // manual: https://juliadocs.github.io/Documenter.jl/latest/man/doctests.html + aliases: ['jldoctest'] + } + ] + } +} + +module.exports = juliaRepl; + + +/***/ }), + +/***/ 89879: +/***/ ((module) => { + +/* +Language: Julia +Description: Julia is a high-level, high-performance, dynamic programming language. +Author: Kenta Sato +Contributors: Alex Arslan , Fredrik Ekre +Website: https://julialang.org +*/ + +function julia(hljs) { + // Since there are numerous special names in Julia, it is too much trouble + // to maintain them by hand. Hence these names (i.e. keywords, literals and + // built-ins) are automatically generated from Julia 1.5.2 itself through + // the following scripts for each. + + // ref: https://docs.julialang.org/en/v1/manual/variables/#Allowed-Variable-Names + var VARIABLE_NAME_RE = '[A-Za-z_\\u00A1-\\uFFFF][A-Za-z_0-9\\u00A1-\\uFFFF]*'; + + // # keyword generator, multi-word keywords handled manually below (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String["in", "isa", "where"] + // for kw in collect(x.keyword for x in REPLCompletions.complete_keyword("")) + // if !(contains(kw, " ") || kw == "struct") + // push!(res, kw) + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var KEYWORD_LIST = [ + 'baremodule', + 'begin', + 'break', + 'catch', + 'ccall', + 'const', + 'continue', + 'do', + 'else', + 'elseif', + 'end', + 'export', + 'false', + 'finally', + 'for', + 'function', + 'global', + 'if', + 'import', + 'in', + 'isa', + 'let', + 'local', + 'macro', + 'module', + 'quote', + 'return', + 'true', + 'try', + 'using', + 'where', + 'while', + ]; + + // # literal generator (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String["true", "false"] + // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + // REPLCompletions.completions("", 0)[1]) + // try + // v = eval(Symbol(compl.mod)) + // if !(v isa Function || v isa Type || v isa TypeVar || v isa Module || v isa Colon) + // push!(res, compl.mod) + // end + // catch e + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var LITERAL_LIST = [ + 'ARGS', + 'C_NULL', + 'DEPOT_PATH', + 'ENDIAN_BOM', + 'ENV', + 'Inf', + 'Inf16', + 'Inf32', + 'Inf64', + 'InsertionSort', + 'LOAD_PATH', + 'MergeSort', + 'NaN', + 'NaN16', + 'NaN32', + 'NaN64', + 'PROGRAM_FILE', + 'QuickSort', + 'RoundDown', + 'RoundFromZero', + 'RoundNearest', + 'RoundNearestTiesAway', + 'RoundNearestTiesUp', + 'RoundToZero', + 'RoundUp', + 'VERSION|0', + 'devnull', + 'false', + 'im', + 'missing', + 'nothing', + 'pi', + 'stderr', + 'stdin', + 'stdout', + 'true', + 'undef', + 'π', + 'ℯ', + ]; + + // # built_in generator (Julia 1.5.2) + // import REPL.REPLCompletions + // res = String[] + // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + // REPLCompletions.completions("", 0)[1]) + // try + // v = eval(Symbol(compl.mod)) + // if (v isa Type || v isa TypeVar) && (compl.mod != "=>") + // push!(res, compl.mod) + // end + // catch e + // end + // end + // sort!(unique!(res)) + // foreach(x -> println("\'", x, "\',"), res) + var BUILT_IN_LIST = [ + 'AbstractArray', + 'AbstractChannel', + 'AbstractChar', + 'AbstractDict', + 'AbstractDisplay', + 'AbstractFloat', + 'AbstractIrrational', + 'AbstractMatrix', + 'AbstractRange', + 'AbstractSet', + 'AbstractString', + 'AbstractUnitRange', + 'AbstractVecOrMat', + 'AbstractVector', + 'Any', + 'ArgumentError', + 'Array', + 'AssertionError', + 'BigFloat', + 'BigInt', + 'BitArray', + 'BitMatrix', + 'BitSet', + 'BitVector', + 'Bool', + 'BoundsError', + 'CapturedException', + 'CartesianIndex', + 'CartesianIndices', + 'Cchar', + 'Cdouble', + 'Cfloat', + 'Channel', + 'Char', + 'Cint', + 'Cintmax_t', + 'Clong', + 'Clonglong', + 'Cmd', + 'Colon', + 'Complex', + 'ComplexF16', + 'ComplexF32', + 'ComplexF64', + 'CompositeException', + 'Condition', + 'Cptrdiff_t', + 'Cshort', + 'Csize_t', + 'Cssize_t', + 'Cstring', + 'Cuchar', + 'Cuint', + 'Cuintmax_t', + 'Culong', + 'Culonglong', + 'Cushort', + 'Cvoid', + 'Cwchar_t', + 'Cwstring', + 'DataType', + 'DenseArray', + 'DenseMatrix', + 'DenseVecOrMat', + 'DenseVector', + 'Dict', + 'DimensionMismatch', + 'Dims', + 'DivideError', + 'DomainError', + 'EOFError', + 'Enum', + 'ErrorException', + 'Exception', + 'ExponentialBackOff', + 'Expr', + 'Float16', + 'Float32', + 'Float64', + 'Function', + 'GlobalRef', + 'HTML', + 'IO', + 'IOBuffer', + 'IOContext', + 'IOStream', + 'IdDict', + 'IndexCartesian', + 'IndexLinear', + 'IndexStyle', + 'InexactError', + 'InitError', + 'Int', + 'Int128', + 'Int16', + 'Int32', + 'Int64', + 'Int8', + 'Integer', + 'InterruptException', + 'InvalidStateException', + 'Irrational', + 'KeyError', + 'LinRange', + 'LineNumberNode', + 'LinearIndices', + 'LoadError', + 'MIME', + 'Matrix', + 'Method', + 'MethodError', + 'Missing', + 'MissingException', + 'Module', + 'NTuple', + 'NamedTuple', + 'Nothing', + 'Number', + 'OrdinalRange', + 'OutOfMemoryError', + 'OverflowError', + 'Pair', + 'PartialQuickSort', + 'PermutedDimsArray', + 'Pipe', + 'ProcessFailedException', + 'Ptr', + 'QuoteNode', + 'Rational', + 'RawFD', + 'ReadOnlyMemoryError', + 'Real', + 'ReentrantLock', + 'Ref', + 'Regex', + 'RegexMatch', + 'RoundingMode', + 'SegmentationFault', + 'Set', + 'Signed', + 'Some', + 'StackOverflowError', + 'StepRange', + 'StepRangeLen', + 'StridedArray', + 'StridedMatrix', + 'StridedVecOrMat', + 'StridedVector', + 'String', + 'StringIndexError', + 'SubArray', + 'SubString', + 'SubstitutionString', + 'Symbol', + 'SystemError', + 'Task', + 'TaskFailedException', + 'Text', + 'TextDisplay', + 'Timer', + 'Tuple', + 'Type', + 'TypeError', + 'TypeVar', + 'UInt', + 'UInt128', + 'UInt16', + 'UInt32', + 'UInt64', + 'UInt8', + 'UndefInitializer', + 'UndefKeywordError', + 'UndefRefError', + 'UndefVarError', + 'Union', + 'UnionAll', + 'UnitRange', + 'Unsigned', + 'Val', + 'Vararg', + 'VecElement', + 'VecOrMat', + 'Vector', + 'VersionNumber', + 'WeakKeyDict', + 'WeakRef', + ]; + + var KEYWORDS = { + $pattern: VARIABLE_NAME_RE, + keyword: KEYWORD_LIST, + literal: LITERAL_LIST, + built_in: BUILT_IN_LIST, + }; + + // placeholder for recursive self-reference + var DEFAULT = { + keywords: KEYWORDS, illegal: /<\// + }; + + // ref: https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/ + var NUMBER = { + className: 'number', + // supported numeric literals: + // * binary literal (e.g. 0x10) + // * octal literal (e.g. 0o76543210) + // * hexadecimal literal (e.g. 0xfedcba876543210) + // * hexadecimal floating point literal (e.g. 0x1p0, 0x1.2p2) + // * decimal literal (e.g. 9876543210, 100_000_000) + // * floating pointe literal (e.g. 1.2, 1.2f, .2, 1., 1.2e10, 1.2e-10) + begin: /(\b0x[\d_]*(\.[\d_]*)?|0x\.\d[\d_]*)p[-+]?\d+|\b0[box][a-fA-F0-9][a-fA-F0-9_]*|(\b\d[\d_]*(\.[\d_]*)?|\.\d[\d_]*)([eEfF][-+]?\d+)?/, + relevance: 0 + }; + + var CHAR = { + className: 'string', + begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/ + }; + + var INTERPOLATION = { + className: 'subst', + begin: /\$\(/, end: /\)/, + keywords: KEYWORDS + }; + + var INTERPOLATED_VARIABLE = { + className: 'variable', + begin: '\\$' + VARIABLE_NAME_RE + }; + + // TODO: neatly escape normal code in string literal + var STRING = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE], + variants: [ + { begin: /\w*"""/, end: /"""\w*/, relevance: 10 }, + { begin: /\w*"/, end: /"\w*/ } + ] + }; + + var COMMAND = { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE], + begin: '`', end: '`' + }; + + var MACROCALL = { + className: 'meta', + begin: '@' + VARIABLE_NAME_RE + }; + + var COMMENT = { + className: 'comment', + variants: [ + { begin: '#=', end: '=#', relevance: 10 }, + { begin: '#', end: '$' } + ] + }; + + DEFAULT.name = 'Julia'; + DEFAULT.contains = [ + NUMBER, + CHAR, + STRING, + COMMAND, + MACROCALL, + COMMENT, + hljs.HASH_COMMENT_MODE, + { + className: 'keyword', + begin: + '\\b(((abstract|primitive)\\s+)type|(mutable\\s+)?struct)\\b' + }, + {begin: /<:/} // relevance booster + ]; + INTERPOLATION.contains = DEFAULT.contains; + + return DEFAULT; +} + +module.exports = julia; + + +/***/ }), + +/***/ 17084: +/***/ ((module) => { + +/* +Language: Lasso +Author: Eric Knibbe +Description: Lasso is a language and server platform for database-driven web applications. This definition handles Lasso 9 syntax and LassoScript for Lasso 8.6 and earlier. +Website: http://www.lassosoft.com/What-Is-Lasso +*/ + +function lasso(hljs) { + const LASSO_IDENT_RE = '[a-zA-Z_][\\w.]*'; + const LASSO_ANGLE_RE = '<\\?(lasso(script)?|=)'; + const LASSO_CLOSE_RE = '\\]|\\?>'; + const LASSO_KEYWORDS = { + $pattern: LASSO_IDENT_RE + '|&[lg]t;', + literal: + 'true false none minimal full all void and or not ' + + 'bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft', + built_in: + 'array date decimal duration integer map pair string tag xml null ' + + 'boolean bytes keyword list locale queue set stack staticarray ' + + 'local var variable global data self inherited currentcapture givenblock', + keyword: + 'cache database_names database_schemanames database_tablenames ' + + 'define_tag define_type email_batch encode_set html_comment handle ' + + 'handle_error header if inline iterate ljax_target link ' + + 'link_currentaction link_currentgroup link_currentrecord link_detail ' + + 'link_firstgroup link_firstrecord link_lastgroup link_lastrecord ' + + 'link_nextgroup link_nextrecord link_prevgroup link_prevrecord log ' + + 'loop namespace_using output_none portal private protect records ' + + 'referer referrer repeating resultset rows search_args ' + + 'search_arguments select sort_args sort_arguments thread_atomic ' + + 'value_list while abort case else fail_if fail_ifnot fail if_empty ' + + 'if_false if_null if_true loop_abort loop_continue loop_count params ' + + 'params_up return return_value run_children soap_definetag ' + + 'soap_lastrequest soap_lastresponse tag_name ascending average by ' + + 'define descending do equals frozen group handle_failure import in ' + + 'into join let match max min on order parent protected provide public ' + + 'require returnhome skip split_thread sum take thread to trait type ' + + 'where with yield yieldhome' + }; + const HTML_COMMENT = hljs.COMMENT( + '', + { + relevance: 0 + } + ); + const LASSO_NOPROCESS = { + className: 'meta', + begin: '\\[noprocess\\]', + starts: { + end: '\\[/noprocess\\]', + returnEnd: true, + contains: [HTML_COMMENT] + } + }; + const LASSO_START = { + className: 'meta', + begin: '\\[/noprocess|' + LASSO_ANGLE_RE + }; + const LASSO_DATAMEMBER = { + className: 'symbol', + begin: '\'' + LASSO_IDENT_RE + '\'' + }; + const LASSO_CODE = [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.inherit(hljs.C_NUMBER_MODE, { + begin: hljs.C_NUMBER_RE + '|(-?infinity|NaN)\\b' + }), + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'string', + begin: '`', + end: '`' + }, + { // variables + variants: [ + { + begin: '[#$]' + LASSO_IDENT_RE + }, + { + begin: '#', + end: '\\d+', + illegal: '\\W' + } + ] + }, + { + className: 'type', + begin: '::\\s*', + end: LASSO_IDENT_RE, + illegal: '\\W' + }, + { + className: 'params', + variants: [ + { + begin: '-(?!infinity)' + LASSO_IDENT_RE, + relevance: 0 + }, + { + begin: '(\\.\\.\\.)' + } + ] + }, + { + begin: /(->|\.)\s*/, + relevance: 0, + contains: [LASSO_DATAMEMBER] + }, + { + className: 'class', + beginKeywords: 'define', + returnEnd: true, + end: '\\(|=>', + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: LASSO_IDENT_RE + '(=(?!>))?|[-+*/%](?!>)' + }) + ] + } + ]; + return { + name: 'Lasso', + aliases: [ + 'ls', + 'lassoscript' + ], + case_insensitive: true, + keywords: LASSO_KEYWORDS, + contains: [ + { + className: 'meta', + begin: LASSO_CLOSE_RE, + relevance: 0, + starts: { // markup + end: '\\[|' + LASSO_ANGLE_RE, + returnEnd: true, + relevance: 0, + contains: [HTML_COMMENT] + } + }, + LASSO_NOPROCESS, + LASSO_START, + { + className: 'meta', + begin: '\\[no_square_brackets', + starts: { + end: '\\[/no_square_brackets\\]', // not implemented in the language + keywords: LASSO_KEYWORDS, + contains: [ + { + className: 'meta', + begin: LASSO_CLOSE_RE, + relevance: 0, + starts: { + end: '\\[noprocess\\]|' + LASSO_ANGLE_RE, + returnEnd: true, + contains: [HTML_COMMENT] + } + }, + LASSO_NOPROCESS, + LASSO_START + ].concat(LASSO_CODE) + } + }, + { + className: 'meta', + begin: '\\[', + relevance: 0 + }, + { + className: 'meta', + begin: '^#!', + end: 'lasso9$', + relevance: 10 + } + ].concat(LASSO_CODE) + }; +} + +module.exports = lasso; + + +/***/ }), + +/***/ 71302: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: LaTeX +Author: Benedikt Wilde +Website: https://www.latex-project.org +Category: markup +*/ + +/** @type LanguageFn */ +function latex(hljs) { + const KNOWN_CONTROL_WORDS = either(...[ + '(?:NeedsTeXFormat|RequirePackage|GetIdInfo)', + 'Provides(?:Expl)?(?:Package|Class|File)', + '(?:DeclareOption|ProcessOptions)', + '(?:documentclass|usepackage|input|include)', + 'makeat(?:letter|other)', + 'ExplSyntax(?:On|Off)', + '(?:new|renew|provide)?command', + '(?:re)newenvironment', + '(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand', + '(?:New|Renew|Provide|Declare)DocumentEnvironment', + '(?:(?:e|g|x)?def|let)', + '(?:begin|end)', + '(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)', + 'caption', + '(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)', + '(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)', + '(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)', + '(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)', + '(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)', + '(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)' + ].map(word => word + '(?![a-zA-Z@:_])')); + const L3_REGEX = new RegExp([ + // A function \module_function_name:signature or \__module_function_name:signature, + // where both module and function_name need at least two characters and + // function_name may contain single underscores. + '(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*', + // A variable \scope_module_and_name_type or \scope__module_ane_name_type, + // where scope is one of l, g or c, type needs at least two characters + // and module_and_name may contain single underscores. + '[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}', + // A quark \q_the_name or \q__the_name or + // scan mark \s_the_name or \s__vthe_name, + // where variable_name needs at least two characters and + // may contain single underscores. + '[qs]__?[a-zA-Z](?:_?[a-zA-Z])+', + // Other LaTeX3 macro names that are not covered by the three rules above. + 'use(?:_i)?:[a-zA-Z]*', + '(?:else|fi|or):', + '(?:if|cs|exp):w', + '(?:hbox|vbox):n', + '::[a-zA-Z]_unbraced', + '::[a-zA-Z:]' + ].map(pattern => pattern + '(?![a-zA-Z:_])').join('|')); + const L2_VARIANTS = [ + {begin: /[a-zA-Z@]+/}, // control word + {begin: /[^a-zA-Z@]?/} // control symbol + ]; + const DOUBLE_CARET_VARIANTS = [ + {begin: /\^{6}[0-9a-f]{6}/}, + {begin: /\^{5}[0-9a-f]{5}/}, + {begin: /\^{4}[0-9a-f]{4}/}, + {begin: /\^{3}[0-9a-f]{3}/}, + {begin: /\^{2}[0-9a-f]{2}/}, + {begin: /\^{2}[\u0000-\u007f]/} + ]; + const CONTROL_SEQUENCE = { + className: 'keyword', + begin: /\\/, + relevance: 0, + contains: [ + { + endsParent: true, + begin: KNOWN_CONTROL_WORDS + }, + { + endsParent: true, + begin: L3_REGEX + }, + { + endsParent: true, + variants: DOUBLE_CARET_VARIANTS + }, + { + endsParent: true, + relevance: 0, + variants: L2_VARIANTS + } + ] + }; + const MACRO_PARAM = { + className: 'params', + relevance: 0, + begin: /#+\d?/ + }; + const DOUBLE_CARET_CHAR = { + // relevance: 1 + variants: DOUBLE_CARET_VARIANTS + }; + const SPECIAL_CATCODE = { + className: 'built_in', + relevance: 0, + begin: /[$&^_]/ + }; + const MAGIC_COMMENT = { + className: 'meta', + begin: '% !TeX', + end: '$', + relevance: 10 + }; + const COMMENT = hljs.COMMENT( + '%', + '$', + { + relevance: 0 + } + ); + const EVERYTHING_BUT_VERBATIM = [ + CONTROL_SEQUENCE, + MACRO_PARAM, + DOUBLE_CARET_CHAR, + SPECIAL_CATCODE, + MAGIC_COMMENT, + COMMENT + ]; + const BRACE_GROUP_NO_VERBATIM = { + begin: /\{/, end: /\}/, + relevance: 0, + contains: ['self', ...EVERYTHING_BUT_VERBATIM] + }; + const ARGUMENT_BRACES = hljs.inherit( + BRACE_GROUP_NO_VERBATIM, + { + relevance: 0, + endsParent: true, + contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM] + } + ); + const ARGUMENT_BRACKETS = { + begin: /\[/, + end: /\]/, + endsParent: true, + relevance: 0, + contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM] + }; + const SPACE_GOBBLER = { + begin: /\s+/, + relevance: 0 + }; + const ARGUMENT_M = [ARGUMENT_BRACES]; + const ARGUMENT_O = [ARGUMENT_BRACKETS]; + const ARGUMENT_AND_THEN = function(arg, starts_mode) { + return { + contains: [SPACE_GOBBLER], + starts: { + relevance: 0, + contains: arg, + starts: starts_mode + } + }; + }; + const CSNAME = function(csname, starts_mode) { + return { + begin: '\\\\' + csname + '(?![a-zA-Z@:_])', + keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\' + csname}, + relevance: 0, + contains: [SPACE_GOBBLER], + starts: starts_mode + }; + }; + const BEGIN_ENV = function(envname, starts_mode) { + return hljs.inherit( + { + begin: '\\\\begin(?=[ \t]*(\\r?\\n[ \t]*)?\\{' + envname + '\\})', + keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\begin'}, + relevance: 0, + }, + ARGUMENT_AND_THEN(ARGUMENT_M, starts_mode) + ); + }; + const VERBATIM_DELIMITED_EQUAL = (innerName = "string") => { + return hljs.END_SAME_AS_BEGIN({ + className: innerName, + begin: /(.|\r?\n)/, + end: /(.|\r?\n)/, + excludeBegin: true, + excludeEnd: true, + endsParent: true + }); + }; + const VERBATIM_DELIMITED_ENV = function(envname) { + return { + className: 'string', + end: '(?=\\\\end\\{' + envname + '\\})' + }; + }; + + const VERBATIM_DELIMITED_BRACES = (innerName = "string") => { + return { + relevance: 0, + begin: /\{/, + starts: { + endsParent: true, + contains: [ + { + className: innerName, + end: /(?=\})/, + endsParent:true, + contains: [ + { + begin: /\{/, + end: /\}/, + relevance: 0, + contains: ["self"] + } + ], + } + ] + } + }; + }; + const VERBATIM = [ + ...['verb', 'lstinline'].map(csname => CSNAME(csname, {contains: [VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('mint', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('mintinline', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_BRACES(), VERBATIM_DELIMITED_EQUAL()]})), + CSNAME('url', {contains: [VERBATIM_DELIMITED_BRACES("link"), VERBATIM_DELIMITED_BRACES("link")]}), + CSNAME('hyperref', {contains: [VERBATIM_DELIMITED_BRACES("link")]}), + CSNAME('href', ARGUMENT_AND_THEN(ARGUMENT_O, {contains: [VERBATIM_DELIMITED_BRACES("link")]})), + ...[].concat(...['', '\\*'].map(suffix => [ + BEGIN_ENV('verbatim' + suffix, VERBATIM_DELIMITED_ENV('verbatim' + suffix)), + BEGIN_ENV('filecontents' + suffix, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('filecontents' + suffix))), + ...['', 'B', 'L'].map(prefix => + BEGIN_ENV(prefix + 'Verbatim' + suffix, ARGUMENT_AND_THEN(ARGUMENT_O, VERBATIM_DELIMITED_ENV(prefix + 'Verbatim' + suffix))) + ) + ])), + BEGIN_ENV('minted', ARGUMENT_AND_THEN(ARGUMENT_O, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('minted')))), + ]; + + return { + name: 'LaTeX', + aliases: ['tex'], + contains: [ + ...VERBATIM, + ...EVERYTHING_BUT_VERBATIM + ] + }; +} + +module.exports = latex; + + +/***/ }), + +/***/ 94711: +/***/ ((module) => { + +/* +Language: LDIF +Contributors: Jacob Childress +Category: enterprise, config +Website: https://en.wikipedia.org/wiki/LDAP_Data_Interchange_Format +*/ +function ldif(hljs) { + return { + name: 'LDIF', + contains: [ + { + className: 'attribute', + begin: '^dn', + end: ': ', + excludeEnd: true, + starts: { + end: '$', + relevance: 0 + }, + relevance: 10 + }, + { + className: 'attribute', + begin: '^\\w', + end: ': ', + excludeEnd: true, + starts: { + end: '$', + relevance: 0 + } + }, + { + className: 'literal', + begin: '^-', + end: '$' + }, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = ldif; + + +/***/ }), + +/***/ 22796: +/***/ ((module) => { + +/* +Language: Leaf +Author: Hale Chan +Description: Based on the Leaf reference from https://vapor.github.io/documentation/guide/leaf.html. +*/ + +function leaf(hljs) { + return { + name: 'Leaf', + contains: [ + { + className: 'function', + begin: '#+' + '[A-Za-z_0-9]*' + '\\(', + end: / \{/, + returnBegin: true, + excludeEnd: true, + contains: [ + { + className: 'keyword', + begin: '#+' + }, + { + className: 'title', + begin: '[A-Za-z_][A-Za-z_0-9]*' + }, + { + className: 'params', + begin: '\\(', + end: '\\)', + endsParent: true, + contains: [ + { + className: 'string', + begin: '"', + end: '"' + }, + { + className: 'variable', + begin: '[A-Za-z_][A-Za-z_0-9]*' + } + ] + } + ] + } + ] + }; +} + +module.exports = leaf; + + +/***/ }), + +/***/ 35665: +/***/ ((module) => { + +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +// some grammars use them all as a single group +const PSEUDO_SELECTORS = PSEUDO_CLASSES.concat(PSEUDO_ELEMENTS); + +/* +Language: Less +Description: It's CSS, with just a little more. +Author: Max Mikhailov +Website: http://lesscss.org +Category: common, css +*/ + +/** @type LanguageFn */ +function less(hljs) { + const modes = MODES(hljs); + const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS; + + const AT_MODIFIERS = "and or not only"; + const IDENT_RE = '[\\w-]+'; // yes, Less identifiers may begin with a digit + const INTERP_IDENT_RE = '(' + IDENT_RE + '|@\\{' + IDENT_RE + '\\})'; + + /* Generic Modes */ + + const RULES = []; const VALUE_MODES = []; // forward def. for recursive modes + + const STRING_MODE = function(c) { + return { + // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings) + className: 'string', + begin: '~?' + c + '.*?' + c + }; + }; + + const IDENT_MODE = function(name, begin, relevance) { + return { + className: name, + begin: begin, + relevance: relevance + }; + }; + + const AT_KEYWORDS = { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }; + + const PARENS_MODE = { + // used only to properly balance nested parens inside mixin call, def. arg list + begin: '\\(', + end: '\\)', + contains: VALUE_MODES, + keywords: AT_KEYWORDS, + relevance: 0 + }; + + // generic Less highlighter (used almost everywhere except selectors): + VALUE_MODES.push( + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + STRING_MODE("'"), + STRING_MODE('"'), + hljs.CSS_NUMBER_MODE, // fixme: it does not include dot for numbers like .5em :( + { + begin: '(url|data-uri)\\(', + starts: { + className: 'string', + end: '[\\)\\n]', + excludeEnd: true + } + }, + modes.HEXCOLOR, + PARENS_MODE, + IDENT_MODE('variable', '@@?' + IDENT_RE, 10), + IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'), + IDENT_MODE('built_in', '~?`[^`]*?`'), // inline javascript (or whatever host language) *multiline* string + { // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding): + className: 'attribute', + begin: IDENT_RE + '\\s*:', + end: ':', + returnBegin: true, + excludeEnd: true + }, + modes.IMPORTANT + ); + + const VALUE_WITH_RULESETS = VALUE_MODES.concat({ + begin: /\{/, + end: /\}/, + contains: RULES + }); + + const MIXIN_GUARD_MODE = { + beginKeywords: 'when', + endsWithParent: true, + contains: [ + { + beginKeywords: 'and not' + } + ].concat(VALUE_MODES) // using this form to override VALUE’s 'function' match + }; + + /* Rule-Level Modes */ + + const RULE_MODE = { + begin: INTERP_IDENT_RE + '\\s*:', + returnBegin: true, + end: /[;}]/, + relevance: 0, + contains: [ + { + begin: /-(webkit|moz|ms|o)-/ + }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b', + end: /(?=:)/, + starts: { + endsWithParent: true, + illegal: '[<=$]', + relevance: 0, + contains: VALUE_MODES + } + } + ] + }; + + const AT_RULE_MODE = { + className: 'keyword', + begin: '@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b', + starts: { + end: '[;{}]', + keywords: AT_KEYWORDS, + returnEnd: true, + contains: VALUE_MODES, + relevance: 0 + } + }; + + // variable definitions and calls + const VAR_RULE_MODE = { + className: 'variable', + variants: [ + // using more strict pattern for higher relevance to increase chances of Less detection. + // this is *the only* Less specific statement used in most of the sources, so... + // (we’ll still often loose to the css-parser unless there's '//' comment, + // simply because 1 variable just can't beat 99 properties :) + { + begin: '@' + IDENT_RE + '\\s*:', + relevance: 15 + }, + { + begin: '@' + IDENT_RE + } + ], + starts: { + end: '[;}]', + returnEnd: true, + contains: VALUE_WITH_RULESETS + } + }; + + const SELECTOR_MODE = { + // first parse unambiguous selectors (i.e. those not starting with tag) + // then fall into the scary lookahead-discriminator variant. + // this mode also handles mixin definitions and calls + variants: [ + { + begin: '[\\.#:&\\[>]', + end: '[;{}]' // mixin calls end with ';' + }, + { + begin: INTERP_IDENT_RE, + end: /\{/ + } + ], + returnBegin: true, + returnEnd: true, + illegal: '[<=\'$"]', + relevance: 0, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + MIXIN_GUARD_MODE, + IDENT_MODE('keyword', 'all\\b'), + IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'), // otherwise it’s identified as tag + { + begin: '\\b(' + TAGS.join('|') + ')\\b', + className: 'selector-tag' + }, + IDENT_MODE('selector-tag', INTERP_IDENT_RE + '%?', 0), // '%' for more consistent coloring of @keyframes "tags" + IDENT_MODE('selector-id', '#' + INTERP_IDENT_RE), + IDENT_MODE('selector-class', '\\.' + INTERP_IDENT_RE, 0), + IDENT_MODE('selector-tag', '&', 0), + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-pseudo', + begin: ':(' + PSEUDO_CLASSES.join('|') + ')' + }, + { + className: 'selector-pseudo', + begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')' + }, + { + begin: '\\(', + end: '\\)', + contains: VALUE_WITH_RULESETS + }, // argument list of parametric mixins + { + begin: '!important' + } // eat !important after mixin call or it will be colored as tag + ] + }; + + const PSEUDO_SELECTOR_MODE = { + begin: IDENT_RE + ':(:)?' + `(${PSEUDO_SELECTORS$1.join('|')})`, + returnBegin: true, + contains: [ SELECTOR_MODE ] + }; + + RULES.push( + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + AT_RULE_MODE, + VAR_RULE_MODE, + PSEUDO_SELECTOR_MODE, + RULE_MODE, + SELECTOR_MODE + ); + + return { + name: 'Less', + case_insensitive: true, + illegal: '[=>\'/<($"]', + contains: RULES + }; +} + +module.exports = less; + + +/***/ }), + +/***/ 81388: +/***/ ((module) => { + +/* +Language: Lisp +Description: Generic lisp syntax +Author: Vasily Polovnyov +Category: lisp +*/ + +function lisp(hljs) { + var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*'; + var MEC_RE = '\\|[^]*?\\|'; + var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?'; + var LITERAL = { + className: 'literal', + begin: '\\b(t{1}|nil)\\b' + }; + var NUMBER = { + className: 'number', + variants: [ + {begin: LISP_SIMPLE_NUMBER_RE, relevance: 0}, + {begin: '#(b|B)[0-1]+(/[0-1]+)?'}, + {begin: '#(o|O)[0-7]+(/[0-7]+)?'}, + {begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'}, + {begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'} + ] + }; + var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); + var COMMENT = hljs.COMMENT( + ';', '$', + { + relevance: 0 + } + ); + var VARIABLE = { + begin: '\\*', end: '\\*' + }; + var KEYWORD = { + className: 'symbol', + begin: '[:&]' + LISP_IDENT_RE + }; + var IDENT = { + begin: LISP_IDENT_RE, + relevance: 0 + }; + var MEC = { + begin: MEC_RE + }; + var QUOTED_LIST = { + begin: '\\(', end: '\\)', + contains: ['self', LITERAL, STRING, NUMBER, IDENT] + }; + var QUOTED = { + contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT], + variants: [ + { + begin: '[\'`]\\(', end: '\\)' + }, + { + begin: '\\(quote ', end: '\\)', + keywords: {name: 'quote'} + }, + { + begin: '\'' + MEC_RE + } + ] + }; + var QUOTED_ATOM = { + variants: [ + {begin: '\'' + LISP_IDENT_RE}, + {begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'} + ] + }; + var LIST = { + begin: '\\(\\s*', end: '\\)' + }; + var BODY = { + endsWithParent: true, + relevance: 0 + }; + LIST.contains = [ + { + className: 'name', + variants: [ + { + begin: LISP_IDENT_RE, + relevance: 0, + }, + {begin: MEC_RE} + ] + }, + BODY + ]; + BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT]; + + return { + name: 'Lisp', + illegal: /\S/, + contains: [ + NUMBER, + hljs.SHEBANG(), + LITERAL, + STRING, + COMMENT, + QUOTED, + QUOTED_ATOM, + LIST, + IDENT + ] + }; +} + +module.exports = lisp; + + +/***/ }), + +/***/ 57232: +/***/ ((module) => { + +/* +Language: LiveCode +Author: Ralf Bitter +Description: Language definition for LiveCode server accounting for revIgniter (a web application framework) characteristics. +Version: 1.1 +Date: 2019-04-17 +Category: enterprise +*/ + +function livecodeserver(hljs) { + const VARIABLE = { + className: 'variable', + variants: [ + { + begin: '\\b([gtps][A-Z]{1}[a-zA-Z0-9]*)(\\[.+\\])?(?:\\s*?)' + }, + { + begin: '\\$_[A-Z]+' + } + ], + relevance: 0 + }; + const COMMENT_MODES = [ + hljs.C_BLOCK_COMMENT_MODE, + hljs.HASH_COMMENT_MODE, + hljs.COMMENT('--', '$'), + hljs.COMMENT('[^:]//', '$') + ]; + const TITLE1 = hljs.inherit(hljs.TITLE_MODE, { + variants: [ + { + begin: '\\b_*rig[A-Z][A-Za-z0-9_\\-]*' + }, + { + begin: '\\b_[a-z0-9\\-]+' + } + ] + }); + const TITLE2 = hljs.inherit(hljs.TITLE_MODE, { + begin: '\\b([A-Za-z0-9_\\-]+)\\b' + }); + return { + name: 'LiveCode', + case_insensitive: false, + keywords: { + keyword: + '$_COOKIE $_FILES $_GET $_GET_BINARY $_GET_RAW $_POST $_POST_BINARY $_POST_RAW $_SESSION $_SERVER ' + + 'codepoint codepoints segment segments codeunit codeunits sentence sentences trueWord trueWords paragraph ' + + 'after byte bytes english the until http forever descending using line real8 with seventh ' + + 'for stdout finally element word words fourth before black ninth sixth characters chars stderr ' + + 'uInt1 uInt1s uInt2 uInt2s stdin string lines relative rel any fifth items from middle mid ' + + 'at else of catch then third it file milliseconds seconds second secs sec int1 int1s int4 ' + + 'int4s internet int2 int2s normal text item last long detailed effective uInt4 uInt4s repeat ' + + 'end repeat URL in try into switch to words https token binfile each tenth as ticks tick ' + + 'system real4 by dateItems without char character ascending eighth whole dateTime numeric short ' + + 'first ftp integer abbreviated abbr abbrev private case while if ' + + 'div mod wrap and or bitAnd bitNot bitOr bitXor among not in a an within ' + + 'contains ends with begins the keys of keys', + literal: + 'SIX TEN FORMFEED NINE ZERO NONE SPACE FOUR FALSE COLON CRLF PI COMMA ENDOFFILE EOF EIGHT FIVE ' + + 'QUOTE EMPTY ONE TRUE RETURN CR LINEFEED RIGHT BACKSLASH NULL SEVEN TAB THREE TWO ' + + 'six ten formfeed nine zero none space four false colon crlf pi comma endoffile eof eight five ' + + 'quote empty one true return cr linefeed right backslash null seven tab three two ' + + 'RIVERSION RISTATE FILE_READ_MODE FILE_WRITE_MODE FILE_WRITE_MODE DIR_WRITE_MODE FILE_READ_UMASK ' + + 'FILE_WRITE_UMASK DIR_READ_UMASK DIR_WRITE_UMASK', + built_in: + 'put abs acos aliasReference annuity arrayDecode arrayEncode asin atan atan2 average avg avgDev base64Decode ' + + 'base64Encode baseConvert binaryDecode binaryEncode byteOffset byteToNum cachedURL cachedURLs charToNum ' + + 'cipherNames codepointOffset codepointProperty codepointToNum codeunitOffset commandNames compound compress ' + + 'constantNames cos date dateFormat decompress difference directories ' + + 'diskSpace DNSServers exp exp1 exp2 exp10 extents files flushEvents folders format functionNames geometricMean global ' + + 'globals hasMemory harmonicMean hostAddress hostAddressToName hostName hostNameToAddress isNumber ISOToMac itemOffset ' + + 'keys len length libURLErrorData libUrlFormData libURLftpCommand libURLLastHTTPHeaders libURLLastRHHeaders ' + + 'libUrlMultipartFormAddPart libUrlMultipartFormData libURLVersion lineOffset ln ln1 localNames log log2 log10 ' + + 'longFilePath lower macToISO matchChunk matchText matrixMultiply max md5Digest median merge messageAuthenticationCode messageDigest millisec ' + + 'millisecs millisecond milliseconds min monthNames nativeCharToNum normalizeText num number numToByte numToChar ' + + 'numToCodepoint numToNativeChar offset open openfiles openProcesses openProcessIDs openSockets ' + + 'paragraphOffset paramCount param params peerAddress pendingMessages platform popStdDev populationStandardDeviation ' + + 'populationVariance popVariance processID random randomBytes replaceText result revCreateXMLTree revCreateXMLTreeFromFile ' + + 'revCurrentRecord revCurrentRecordIsFirst revCurrentRecordIsLast revDatabaseColumnCount revDatabaseColumnIsNull ' + + 'revDatabaseColumnLengths revDatabaseColumnNames revDatabaseColumnNamed revDatabaseColumnNumbered ' + + 'revDatabaseColumnTypes revDatabaseConnectResult revDatabaseCursors revDatabaseID revDatabaseTableNames ' + + 'revDatabaseType revDataFromQuery revdb_closeCursor revdb_columnbynumber revdb_columncount revdb_columnisnull ' + + 'revdb_columnlengths revdb_columnnames revdb_columntypes revdb_commit revdb_connect revdb_connections ' + + 'revdb_connectionerr revdb_currentrecord revdb_cursorconnection revdb_cursorerr revdb_cursors revdb_dbtype ' + + 'revdb_disconnect revdb_execute revdb_iseof revdb_isbof revdb_movefirst revdb_movelast revdb_movenext ' + + 'revdb_moveprev revdb_query revdb_querylist revdb_recordcount revdb_rollback revdb_tablenames ' + + 'revGetDatabaseDriverPath revNumberOfRecords revOpenDatabase revOpenDatabases revQueryDatabase ' + + 'revQueryDatabaseBlob revQueryResult revQueryIsAtStart revQueryIsAtEnd revUnixFromMacPath revXMLAttribute ' + + 'revXMLAttributes revXMLAttributeValues revXMLChildContents revXMLChildNames revXMLCreateTreeFromFileWithNamespaces ' + + 'revXMLCreateTreeWithNamespaces revXMLDataFromXPathQuery revXMLEvaluateXPath revXMLFirstChild revXMLMatchingNode ' + + 'revXMLNextSibling revXMLNodeContents revXMLNumberOfChildren revXMLParent revXMLPreviousSibling ' + + 'revXMLRootNode revXMLRPC_CreateRequest revXMLRPC_Documents revXMLRPC_Error ' + + 'revXMLRPC_GetHost revXMLRPC_GetMethod revXMLRPC_GetParam revXMLText revXMLRPC_Execute ' + + 'revXMLRPC_GetParamCount revXMLRPC_GetParamNode revXMLRPC_GetParamType revXMLRPC_GetPath revXMLRPC_GetPort ' + + 'revXMLRPC_GetProtocol revXMLRPC_GetRequest revXMLRPC_GetResponse revXMLRPC_GetSocket revXMLTree ' + + 'revXMLTrees revXMLValidateDTD revZipDescribeItem revZipEnumerateItems revZipOpenArchives round sampVariance ' + + 'sec secs seconds sentenceOffset sha1Digest shell shortFilePath sin specialFolderPath sqrt standardDeviation statRound ' + + 'stdDev sum sysError systemVersion tan tempName textDecode textEncode tick ticks time to tokenOffset toLower toUpper ' + + 'transpose truewordOffset trunc uniDecode uniEncode upper URLDecode URLEncode URLStatus uuid value variableNames ' + + 'variance version waitDepth weekdayNames wordOffset xsltApplyStylesheet xsltApplyStylesheetFromFile xsltLoadStylesheet ' + + 'xsltLoadStylesheetFromFile add breakpoint cancel clear local variable file word line folder directory URL close socket process ' + + 'combine constant convert create new alias folder directory decrypt delete variable word line folder ' + + 'directory URL dispatch divide do encrypt filter get include intersect kill libURLDownloadToFile ' + + 'libURLFollowHttpRedirects libURLftpUpload libURLftpUploadFile libURLresetAll libUrlSetAuthCallback libURLSetDriver ' + + 'libURLSetCustomHTTPHeaders libUrlSetExpect100 libURLSetFTPListCommand libURLSetFTPMode libURLSetFTPStopTime ' + + 'libURLSetStatusCallback load extension loadedExtensions multiply socket prepare process post seek rel relative read from process rename ' + + 'replace require resetAll resolve revAddXMLNode revAppendXML revCloseCursor revCloseDatabase revCommitDatabase ' + + 'revCopyFile revCopyFolder revCopyXMLNode revDeleteFolder revDeleteXMLNode revDeleteAllXMLTrees ' + + 'revDeleteXMLTree revExecuteSQL revGoURL revInsertXMLNode revMoveFolder revMoveToFirstRecord revMoveToLastRecord ' + + 'revMoveToNextRecord revMoveToPreviousRecord revMoveToRecord revMoveXMLNode revPutIntoXMLNode revRollBackDatabase ' + + 'revSetDatabaseDriverPath revSetXMLAttribute revXMLRPC_AddParam revXMLRPC_DeleteAllDocuments revXMLAddDTD ' + + 'revXMLRPC_Free revXMLRPC_FreeAll revXMLRPC_DeleteDocument revXMLRPC_DeleteParam revXMLRPC_SetHost ' + + 'revXMLRPC_SetMethod revXMLRPC_SetPort revXMLRPC_SetProtocol revXMLRPC_SetSocket revZipAddItemWithData ' + + 'revZipAddItemWithFile revZipAddUncompressedItemWithData revZipAddUncompressedItemWithFile revZipCancel ' + + 'revZipCloseArchive revZipDeleteItem revZipExtractItemToFile revZipExtractItemToVariable revZipSetProgressCallback ' + + 'revZipRenameItem revZipReplaceItemWithData revZipReplaceItemWithFile revZipOpenArchive send set sort split start stop ' + + 'subtract symmetric union unload vectorDotProduct wait write' + }, + contains: [ + VARIABLE, + { + className: 'keyword', + begin: '\\bend\\sif\\b' + }, + { + className: 'function', + beginKeywords: 'function', + end: '$', + contains: [ + VARIABLE, + TITLE2, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ] + }, + { + className: 'function', + begin: '\\bend\\s+', + end: '$', + keywords: 'end', + contains: [ + TITLE2, + TITLE1 + ], + relevance: 0 + }, + { + beginKeywords: 'command on', + end: '$', + contains: [ + VARIABLE, + TITLE2, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ] + }, + { + className: 'meta', + variants: [ + { + begin: '<\\?(rev|lc|livecode)', + relevance: 10 + }, + { + begin: '<\\?' + }, + { + begin: '\\?>' + } + ] + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.BINARY_NUMBER_MODE, + hljs.C_NUMBER_MODE, + TITLE1 + ].concat(COMMENT_MODES), + illegal: ';$|^\\[|^=|&|\\{' + }; +} + +module.exports = livecodeserver; + + +/***/ }), + +/***/ 79369: +/***/ ((module) => { + +const KEYWORDS = [ + "as", // for exports + "in", + "of", + "if", + "for", + "while", + "finally", + "var", + "new", + "function", + "do", + "return", + "void", + "else", + "break", + "catch", + "instanceof", + "with", + "throw", + "case", + "default", + "try", + "switch", + "continue", + "typeof", + "delete", + "let", + "yield", + "const", + "class", + // JS handles these with a special rule + // "get", + // "set", + "debugger", + "async", + "await", + "static", + "import", + "from", + "export", + "extends" +]; +const LITERALS = [ + "true", + "false", + "null", + "undefined", + "NaN", + "Infinity" +]; + +const TYPES = [ + "Intl", + "DataView", + "Number", + "Math", + "Date", + "String", + "RegExp", + "Object", + "Function", + "Boolean", + "Error", + "Symbol", + "Set", + "Map", + "WeakSet", + "WeakMap", + "Proxy", + "Reflect", + "JSON", + "Promise", + "Float64Array", + "Int16Array", + "Int32Array", + "Int8Array", + "Uint16Array", + "Uint32Array", + "Float32Array", + "Array", + "Uint8Array", + "Uint8ClampedArray", + "ArrayBuffer", + "BigInt64Array", + "BigUint64Array", + "BigInt" +]; + +const ERROR_TYPES = [ + "EvalError", + "InternalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError" +]; + +const BUILT_IN_GLOBALS = [ + "setInterval", + "setTimeout", + "clearInterval", + "clearTimeout", + + "require", + "exports", + + "eval", + "isFinite", + "isNaN", + "parseFloat", + "parseInt", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape" +]; + +const BUILT_IN_VARIABLES = [ + "arguments", + "this", + "super", + "console", + "window", + "document", + "localStorage", + "module", + "global" // Node.js +]; + +const BUILT_INS = [].concat( + BUILT_IN_GLOBALS, + BUILT_IN_VARIABLES, + TYPES, + ERROR_TYPES +); + +/* +Language: LiveScript +Author: Taneli Vatanen +Contributors: Jen Evers-Corvina +Origin: coffeescript.js +Description: LiveScript is a programming language that transcompiles to JavaScript. For info about language see http://livescript.net/ +Website: https://livescript.net +Category: scripting +*/ + +function livescript(hljs) { + const LIVESCRIPT_BUILT_INS = [ + 'npm', + 'print' + ]; + const LIVESCRIPT_LITERALS = [ + 'yes', + 'no', + 'on', + 'off', + 'it', + 'that', + 'void' + ]; + const LIVESCRIPT_KEYWORDS = [ + 'then', + 'unless', + 'until', + 'loop', + 'of', + 'by', + 'when', + 'and', + 'or', + 'is', + 'isnt', + 'not', + 'it', + 'that', + 'otherwise', + 'from', + 'to', + 'til', + 'fallthrough', + 'case', + 'enum', + 'native', + 'list', + 'map', + '__hasProp', + '__extends', + '__slice', + '__bind', + '__indexOf' + ]; + const KEYWORDS$1 = { + keyword: KEYWORDS.concat(LIVESCRIPT_KEYWORDS), + literal: LITERALS.concat(LIVESCRIPT_LITERALS), + built_in: BUILT_INS.concat(LIVESCRIPT_BUILT_INS) + }; + const JS_IDENT_RE = '[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*'; + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: JS_IDENT_RE + }); + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: KEYWORDS$1 + }; + const SUBST_SIMPLE = { + className: 'subst', + begin: /#[A-Za-z$_]/, + end: /(?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/, + keywords: KEYWORDS$1 + }; + const EXPRESSIONS = [ + hljs.BINARY_NUMBER_MODE, + { + className: 'number', + begin: '(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)', + relevance: 0, + starts: { + end: '(\\s*/)?', + relevance: 0 + } // a number tries to eat the following slash to prevent treating it as a regexp + }, + { + className: 'string', + variants: [ + { + begin: /'''/, + end: /'''/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /'/, + end: /'/, + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + begin: /"""/, + end: /"""/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + SUBST_SIMPLE + ] + }, + { + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST, + SUBST_SIMPLE + ] + }, + { + begin: /\\/, + end: /(\s|$)/, + excludeEnd: true + } + ] + }, + { + className: 'regexp', + variants: [ + { + begin: '//', + end: '//[gim]*', + contains: [ + SUBST, + hljs.HASH_COMMENT_MODE + ] + }, + { + // regex can't start with space to parse x / 2 / 3 as two divisions + // regex can't start with *, and it supports an "illegal" in the main mode + begin: /\/(?![ *])(\\.|[^\\\n])*?\/[gim]*(?=\W)/ + } + ] + }, + { + begin: '@' + JS_IDENT_RE + }, + { + begin: '``', + end: '``', + excludeBegin: true, + excludeEnd: true, + subLanguage: 'javascript' + } + ]; + SUBST.contains = EXPRESSIONS; + + const PARAMS = { + className: 'params', + begin: '\\(', + returnBegin: true, + /* We need another contained nameless mode to not have every nested + pair of parens to be called "params" */ + contains: [ + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS$1, + contains: ['self'].concat(EXPRESSIONS) + } + ] + }; + + const SYMBOLS = { + begin: '(#=>|=>|\\|>>|-?->|!->)' + }; + + return { + name: 'LiveScript', + aliases: ['ls'], + keywords: KEYWORDS$1, + illegal: /\/\*/, + contains: EXPRESSIONS.concat([ + hljs.COMMENT('\\/\\*', '\\*\\/'), + hljs.HASH_COMMENT_MODE, + SYMBOLS, // relevance booster + { + className: 'function', + contains: [ + TITLE, + PARAMS + ], + returnBegin: true, + variants: [ + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B->\\*?', + end: '->\\*?' + }, + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?!?(\\(.*\\)\\s*)?\\B[-~]{1,2}>\\*?', + end: '[-~]{1,2}>\\*?' + }, + { + begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B!?[-~]{1,2}>\\*?', + end: '!?[-~]{1,2}>\\*?' + } + ] + }, + { + className: 'class', + beginKeywords: 'class', + end: '$', + illegal: /[:="\[\]]/, + contains: [ + { + beginKeywords: 'extends', + endsWithParent: true, + illegal: /[:="\[\]]/, + contains: [TITLE] + }, + TITLE + ] + }, + { + begin: JS_IDENT_RE + ':', + end: ':', + returnBegin: true, + returnEnd: true, + relevance: 0 + } + ]) + }; +} + +module.exports = livescript; + + +/***/ }), + +/***/ 64881: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: LLVM IR +Author: Michael Rodler +Description: language used as intermediate representation in the LLVM compiler framework +Website: https://llvm.org/docs/LangRef.html +Category: assembler +Audit: 2020 +*/ + +/** @type LanguageFn */ +function llvm(hljs) { + const IDENT_RE = /([-a-zA-Z$._][\w$.-]*)/; + const TYPE = { + className: 'type', + begin: /\bi\d+(?=\s|\b)/ + }; + const OPERATOR = { + className: 'operator', + relevance: 0, + begin: /=/ + }; + const PUNCTUATION = { + className: 'punctuation', + relevance: 0, + begin: /,/ + }; + const NUMBER = { + className: 'number', + variants: [ + { begin: /0[xX][a-fA-F0-9]+/ }, + { begin: /-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?/ } + ], + relevance: 0 + }; + const LABEL = { + className: 'symbol', + variants: [ + { begin: /^\s*[a-z]+:/ }, // labels + ], + relevance: 0 + }; + const VARIABLE = { + className: 'variable', + variants: [ + { begin: concat(/%/, IDENT_RE) }, + { begin: /%\d+/ }, + { begin: /#\d+/ }, + ] + }; + const FUNCTION = { + className: 'title', + variants: [ + { begin: concat(/@/, IDENT_RE) }, + { begin: /@\d+/ }, + { begin: concat(/!/, IDENT_RE) }, + { begin: concat(/!\d+/, IDENT_RE) }, + // https://llvm.org/docs/LangRef.html#namedmetadatastructure + // obviously a single digit can also be used in this fashion + { begin: /!\d+/ } + ] + }; + + return { + name: 'LLVM IR', + // TODO: split into different categories of keywords + keywords: + 'begin end true false declare define global ' + + 'constant private linker_private internal ' + + 'available_externally linkonce linkonce_odr weak ' + + 'weak_odr appending dllimport dllexport common ' + + 'default hidden protected extern_weak external ' + + 'thread_local zeroinitializer undef null to tail ' + + 'target triple datalayout volatile nuw nsw nnan ' + + 'ninf nsz arcp fast exact inbounds align ' + + 'addrspace section alias module asm sideeffect ' + + 'gc dbg linker_private_weak attributes blockaddress ' + + 'initialexec localdynamic localexec prefix unnamed_addr ' + + 'ccc fastcc coldcc x86_stdcallcc x86_fastcallcc ' + + 'arm_apcscc arm_aapcscc arm_aapcs_vfpcc ptx_device ' + + 'ptx_kernel intel_ocl_bicc msp430_intrcc spir_func ' + + 'spir_kernel x86_64_sysvcc x86_64_win64cc x86_thiscallcc ' + + 'cc c signext zeroext inreg sret nounwind ' + + 'noreturn noalias nocapture byval nest readnone ' + + 'readonly inlinehint noinline alwaysinline optsize ssp ' + + 'sspreq noredzone noimplicitfloat naked builtin cold ' + + 'nobuiltin noduplicate nonlazybind optnone returns_twice ' + + 'sanitize_address sanitize_memory sanitize_thread sspstrong ' + + 'uwtable returned type opaque eq ne slt sgt ' + + 'sle sge ult ugt ule uge oeq one olt ogt ' + + 'ole oge ord uno ueq une x acq_rel acquire ' + + 'alignstack atomic catch cleanup filter inteldialect ' + + 'max min monotonic nand personality release seq_cst ' + + 'singlethread umax umin unordered xchg add fadd ' + + 'sub fsub mul fmul udiv sdiv fdiv urem srem ' + + 'frem shl lshr ashr and or xor icmp fcmp ' + + 'phi call trunc zext sext fptrunc fpext uitofp ' + + 'sitofp fptoui fptosi inttoptr ptrtoint bitcast ' + + 'addrspacecast select va_arg ret br switch invoke ' + + 'unwind unreachable indirectbr landingpad resume ' + + 'malloc alloca free load store getelementptr ' + + 'extractelement insertelement shufflevector getresult ' + + 'extractvalue insertvalue atomicrmw cmpxchg fence ' + + 'argmemonly double', + contains: [ + TYPE, + // this matches "empty comments"... + // ...because it's far more likely this is a statement terminator in + // another language than an actual comment + hljs.COMMENT(/;\s*$/, null, { relevance: 0 }), + hljs.COMMENT(/;/, /$/), + hljs.QUOTE_STRING_MODE, + { + className: 'string', + variants: [ + // Double-quoted string + { begin: /"/, end: /[^\\]"/ }, + ] + }, + FUNCTION, + PUNCTUATION, + OPERATOR, + VARIABLE, + LABEL, + NUMBER + ] + }; +} + +module.exports = llvm; + + +/***/ }), + +/***/ 38477: +/***/ ((module) => { + +/* +Language: LSL (Linden Scripting Language) +Description: The Linden Scripting Language is used in Second Life by Linden Labs. +Author: Builder's Brewery +Website: http://wiki.secondlife.com/wiki/LSL_Portal +Category: scripting +*/ + +function lsl(hljs) { + + var LSL_STRING_ESCAPE_CHARS = { + className: 'subst', + begin: /\\[tn"\\]/ + }; + + var LSL_STRINGS = { + className: 'string', + begin: '"', + end: '"', + contains: [ + LSL_STRING_ESCAPE_CHARS + ] + }; + + var LSL_NUMBERS = { + className: 'number', + relevance:0, + begin: hljs.C_NUMBER_RE + }; + + var LSL_CONSTANTS = { + className: 'literal', + variants: [ + { + begin: '\\b(PI|TWO_PI|PI_BY_TWO|DEG_TO_RAD|RAD_TO_DEG|SQRT2)\\b' + }, + { + begin: '\\b(XP_ERROR_(EXPERIENCES_DISABLED|EXPERIENCE_(DISABLED|SUSPENDED)|INVALID_(EXPERIENCE|PARAMETERS)|KEY_NOT_FOUND|MATURITY_EXCEEDED|NONE|NOT_(FOUND|PERMITTED(_LAND)?)|NO_EXPERIENCE|QUOTA_EXCEEDED|RETRY_UPDATE|STORAGE_EXCEPTION|STORE_DISABLED|THROTTLED|UNKNOWN_ERROR)|JSON_APPEND|STATUS_(PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(_OBJECT)?|(DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(_(BY_(LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(PARCEL(_OWNER)?|REGION)))?|CAMERA_(PITCH|DISTANCE|BEHINDNESS_(ANGLE|LAG)|(FOCUS|POSITION)(_(THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(ROOT|SET|ALL_(OTHERS|CHILDREN)|THIS)|ACTIVE|PASS(IVE|_(ALWAYS|IF_NOT_HANDLED|NEVER))|SCRIPTED|CONTROL_(FWD|BACK|(ROT_)?(LEFT|RIGHT)|UP|DOWN|(ML_)?LBUTTON)|PERMISSION_(RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(_START)?|TELEPORT|MEDIA)|OBJECT_(CLICK_ACTION|HOVER_HEIGHT|LAST_OWNER_ID|(PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_(ATTACHED|ON_REZ)|NAME|DESC|POS|PRIM_(COUNT|EQUIVALENCE)|RETURN_(PARCEL(_OWNER)?|REGION)|REZZER_KEY|ROO?T|VELOCITY|OMEGA|OWNER|GROUP(_TAG)?|CREATOR|ATTACHED_(POINT|SLOTS_AVAILABLE)|RENDER_WEIGHT|(BODY_SHAPE|PATHFINDING)_TYPE|(RUNNING|TOTAL)_SCRIPT_COUNT|TOTAL_INVENTORY_COUNT|SCRIPT_(MEMORY|TIME))|TYPE_(INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(DEBUG|PUBLIC)_CHANNEL|ATTACH_(AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](SHOULDER|HAND|FOOT|EAR|EYE|[UL](ARM|LEG)|HIP)|(LEFT|RIGHT)_PEC|HUD_(CENTER_[12]|TOP_(RIGHT|CENTER|LEFT)|BOTTOM(_(RIGHT|LEFT))?)|[LR]HAND_RING1|TAIL_(BASE|TIP)|[LR]WING|FACE_(JAW|[LR]EAR|[LR]EYE|TOUNGE)|GROIN|HIND_[LR]FOOT)|LAND_(LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(ONLINE|NAME|BORN|SIM_(POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(ON_FILE|USED)|REMOTE_DATA_(CHANNEL|REQUEST|REPLY)|PSYS_(PART_(BF_(ZERO|ONE(_MINUS_(DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(START|END)_(COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(RIBBON|WIND|INTERP_(COLOR|SCALE)|BOUNCE|FOLLOW_(SRC|VELOCITY)|TARGET_(POS|LINEAR)|EMISSIVE)_MASK)|SRC_(MAX_AGE|PATTERN|ANGLE_(BEGIN|END)|BURST_(RATE|PART_COUNT|RADIUS|SPEED_(MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(DROP|EXPLODE|ANGLE(_CONE(_EMPTY)?)?)))|VEHICLE_(REFERENCE_FRAME|TYPE_(NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(LINEAR|ANGULAR)_(FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(LINEAR|ANGULAR)_(DEFLECTION_(EFFICIENCY|TIMESCALE)|MOTOR_(DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(EFFICIENCY|TIMESCALE)|BANKING_(EFFICIENCY|MIX|TIMESCALE)|FLAG_(NO_DEFLECTION_UP|LIMIT_(ROLL_ONLY|MOTOR_UP)|HOVER_((WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(ALLOW_UNSIT|ALPHA_MODE(_(BLEND|EMISSIVE|MASK|NONE))?|NORMAL|SPECULAR|TYPE(_(BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(_(STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(NONE|LOW|MEDIUM|HIGH)|BUMP_(NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(DEFAULT|PLANAR)|SCRIPTED_SIT_ONLY|SCULPT_(TYPE_(SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(MIRROR|INVERT))|PHYSICS(_(SHAPE_(CONVEX|NONE|PRIM|TYPE)))?|(POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIT_TARGET|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(ALT_IMAGE_ENABLE|CONTROLS|(CURRENT|HOME)_URL|AUTO_(LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(WIDTH|HEIGHT)_PIXELS|WHITELIST(_ENABLE)?|PERMS_(INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(STANDARD|MINI)|PERM_(NONE|OWNER|GROUP|ANYONE)|MAX_(URL_LENGTH|WHITELIST_(SIZE|COUNT)|(WIDTH|HEIGHT)_PIXELS)))|MASK_(BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(MEDIA_COMMAND_(STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(ALLOW_(FLY|(GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(GROUP_)?OBJECTS)|USE_(ACCESS_(GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(GROUP|ALL)_OBJECT_ENTRY)|COUNT_(TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(HIDE|DEFAULT)|REGION_FLAG_(ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(METHOD|MIMETYPE|BODY_(MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|SIT_(INVALID_(AGENT|LINK_OBJECT)|NO(T_EXPERIENCE|_(ACCESS|EXPERIENCE_PERMISSION|SIT_TARGET)))|STRING_(TRIM(_(HEAD|TAIL))?)|CLICK_ACTION_(NONE|TOUCH|SIT|BUY|PAY|OPEN(_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(NONE|SCRIPT_MEMORY)|RC_(DATA_FLAGS|DETECT_PHANTOM|GET_(LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(TYPES|AGENTS|(NON)?PHYSICAL|LAND))|RCERR_(CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(ALLOWED_(AGENT|GROUP)_(ADD|REMOVE)|BANNED_AGENT_(ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(COMMAND|CMD_(PLAY|STOP|PAUSE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(CMD_((SMOOTH_)?STOP|JUMP)|DESIRED_(TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(_([ABCD]|NONE))?|MAX_(DECEL|TURN_RADIUS|(ACCEL|SPEED)))|PURSUIT_(OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(EVADE_(HIDDEN|SPOTTED)|FAILURE_(DYNAMIC_PATHFINDING_DISABLED|INVALID_(GOAL|START)|NO_(NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(PARCEL_)?UNREACHABLE)|(GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(_(FAST|NONE|SLOW))?|CONTENT_TYPE_(ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(RADIUS|STATIC)|(PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\\b' + }, + { + begin: '\\b(FALSE|TRUE)\\b' + }, + { + begin: '\\b(ZERO_ROTATION)\\b' + }, + { + begin: '\\b(EOF|JSON_(ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(GRANTED|DENIED))\\b' + }, + { + begin: '\\b(ZERO_VECTOR|TOUCH_INVALID_(TEXCOORD|VECTOR))\\b' + } + ] + }; + + var LSL_FUNCTIONS = { + className: 'built_in', + begin: '\\b(ll(AgentInExperience|(Create|DataSize|Delete|KeyCount|Keys|Read|Update)KeyValue|GetExperience(Details|ErrorMessage)|ReturnObjectsBy(ID|Owner)|Json(2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(Mag|Norm|Dist)|Rot(Between|2(Euler|Fwd|Left|Up))|(Euler|Axes)2Rot|Whisper|(Region|Owner)?Say|Shout|Listen(Control|Remove)?|Sensor(Repeat|Remove)?|Detected(Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|([GS]et)(AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(Scale|Offset|Rotate)Texture|(Rot)?Target(Remove)?|(Stop)?MoveToTarget|Apply(Rotational)?Impulse|Set(KeyframedMotion|ContentType|RegionPos|(Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(Queueing|Radius)|Vehicle(Type|(Float|Vector|Rotation)Param)|(Touch|Sit)?Text|Camera(Eye|At)Offset|PrimitiveParams|ClickAction|Link(Alpha|Color|PrimitiveParams(Fast)?|Texture(Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get((Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(PrimitiveParams|Number(OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(Details|PermMask|PrimCount)|Parcel(MaxPrims|Details|Prim(Count|Owners))|Attached(List)?|(SPMax|Free|Used)Memory|Region(Name|TimeDilation|FPS|Corner|AgentCount)|Root(Position|Rotation)|UnixTime|(Parcel|Region)Flags|(Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(Prims|NotecardLines|Sides)|Animation(List)?|(Camera|Local)(Pos|Rot)|Vel|Accel|Omega|Time(stamp|OfDay)|(Object|CenterOf)?Mass|MassMKS|Energy|Owner|(Owner)?Key|SunDirection|Texture(Offset|Scale|Rot)|Inventory(Number|Name|Key|Type|Creator|PermMask)|Permissions(Key)?|StartParameter|List(Length|EntryType)|Date|Agent(Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(Name|State))|(Get|Reset|GetAndReset)Time|PlaySound(Slave)?|LoopSound(Master|Slave)?|(Trigger|Stop|Preload)Sound|((Get|Delete)Sub|Insert)String|To(Upper|Lower)|Give(InventoryList|Money)|RezObject|(Stop)?LookAt|Sleep|CollisionFilter|(Take|Release)Controls|DetachFromAvatar|AttachToAvatar(Temp)?|InstantMessage|(GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(Length|Trim)|(Start|Stop)Animation|TargetOmega|Request(Experience)?Permissions|(Create|Break)Link|BreakAllLinks|(Give|Remove)Inventory|Water|PassTouches|Request(Agent|Inventory)Data|TeleportAgent(Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(Axis|Angle)|A(cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(CSV|Integer|Json|Float|String|Key|Vector|Rot|List(Strided)?)|DeleteSubList|List(Statistics|Sort|Randomize|(Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(Slope|Normal|Contour)|GroundRepel|(Set|Remove)VehicleFlags|SitOnLink|(AvatarOn)?(Link)?SitTarget|Script(Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(Integer|String)ToBase64|XorBase64|Log(10)?|Base64To(String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(Load|Release|(E|Une)scape)URL|ParcelMedia(CommandList|Query)|ModPow|MapDestination|(RemoveFrom|AddTo|Reset)Land(Pass|Ban)List|(Set|Clear)CameraParams|HTTP(Request|Response)|TextBox|DetectedTouch(UV|Face|Pos|(N|Bin)ormal|ST)|(MD5|SHA1|DumpList2)String|Request(Secure)?URL|Clear(Prim|Link)Media|(Link)?ParticleSystem|(Get|Request)(Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\\b' + }; + + return { + name: 'LSL (Linden Scripting Language)', + illegal: ':', + contains: [ + LSL_STRINGS, + { + className: 'comment', + variants: [ + hljs.COMMENT('//', '$'), + hljs.COMMENT('/\\*', '\\*/') + ], + relevance: 0 + }, + LSL_NUMBERS, + { + className: 'section', + variants: [ + { + begin: '\\b(state|default)\\b' + }, + { + begin: '\\b(state_(entry|exit)|touch(_(start|end))?|(land_)?collision(_(start|end))?|timer|listen|(no_)?sensor|control|(not_)?at_(rot_)?target|money|email|experience_permissions(_denied)?|run_time_permissions|changed|attach|dataserver|moving_(start|end)|link_message|(on|object)_rez|remote_data|http_re(sponse|quest)|path_update|transaction_result)\\b' + } + ] + }, + LSL_FUNCTIONS, + LSL_CONSTANTS, + { + className: 'type', + begin: '\\b(integer|float|string|key|vector|quaternion|rotation|list)\\b' + } + ] + }; +} + +module.exports = lsl; + + +/***/ }), + +/***/ 11388: +/***/ ((module) => { + +/* +Language: Makefile +Author: Ivan Sagalaev +Contributors: Joël Porquet +Website: https://www.gnu.org/software/make/manual/html_node/Introduction.html +Category: common +*/ + +function makefile(hljs) { + /* Variables: simple (eg $(var)) and special (eg $@) */ + const VARIABLE = { + className: 'variable', + variants: [ + { + begin: '\\$\\(' + hljs.UNDERSCORE_IDENT_RE + '\\)', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: /\$[@% { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Markdown +Requires: xml.js +Author: John Crepezzi +Website: https://daringfireball.net/projects/markdown/ +Category: common, markup +*/ + +function markdown(hljs) { + const INLINE_HTML = { + begin: /<\/?[A-Za-z_]/, + end: '>', + subLanguage: 'xml', + relevance: 0 + }; + const HORIZONTAL_RULE = { + begin: '^[-\\*]{3,}', + end: '$' + }; + const CODE = { + className: 'code', + variants: [ + // TODO: fix to allow these to work with sublanguage also + { + begin: '(`{3,})[^`](.|\\n)*?\\1`*[ ]*' + }, + { + begin: '(~{3,})[^~](.|\\n)*?\\1~*[ ]*' + }, + // needed to allow markdown as a sublanguage to work + { + begin: '```', + end: '```+[ ]*$' + }, + { + begin: '~~~', + end: '~~~+[ ]*$' + }, + { + begin: '`.+?`' + }, + { + begin: '(?=^( {4}|\\t))', + // use contains to gobble up multiple lines to allow the block to be whatever size + // but only have a single open/close tag vs one per line + contains: [ + { + begin: '^( {4}|\\t)', + end: '(\\n)$' + } + ], + relevance: 0 + } + ] + }; + const LIST = { + className: 'bullet', + begin: '^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)', + end: '\\s+', + excludeEnd: true + }; + const LINK_REFERENCE = { + begin: /^\[[^\n]+\]:/, + returnBegin: true, + contains: [ + { + className: 'symbol', + begin: /\[/, + end: /\]/, + excludeBegin: true, + excludeEnd: true + }, + { + className: 'link', + begin: /:\s*/, + end: /$/, + excludeBegin: true + } + ] + }; + const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/; + const LINK = { + variants: [ + // too much like nested array access in so many languages + // to have any real relevance + { + begin: /\[.+?\]\[.*?\]/, + relevance: 0 + }, + // popular internet URLs + { + begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/, + relevance: 2 + }, + { + begin: concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/), + relevance: 2 + }, + // relative urls + { + begin: /\[.+?\]\([./?&#].*?\)/, + relevance: 1 + }, + // whatever else, lower relevance (might not be a link at all) + { + begin: /\[.+?\]\(.*?\)/, + relevance: 0 + } + ], + returnBegin: true, + contains: [ + { + className: 'string', + relevance: 0, + begin: '\\[', + end: '\\]', + excludeBegin: true, + returnEnd: true + }, + { + className: 'link', + relevance: 0, + begin: '\\]\\(', + end: '\\)', + excludeBegin: true, + excludeEnd: true + }, + { + className: 'symbol', + relevance: 0, + begin: '\\]\\[', + end: '\\]', + excludeBegin: true, + excludeEnd: true + } + ] + }; + const BOLD = { + className: 'strong', + contains: [], // defined later + variants: [ + { + begin: /_{2}/, + end: /_{2}/ + }, + { + begin: /\*{2}/, + end: /\*{2}/ + } + ] + }; + const ITALIC = { + className: 'emphasis', + contains: [], // defined later + variants: [ + { + begin: /\*(?!\*)/, + end: /\*/ + }, + { + begin: /_(?!_)/, + end: /_/, + relevance: 0 + } + ] + }; + BOLD.contains.push(ITALIC); + ITALIC.contains.push(BOLD); + + let CONTAINABLE = [ + INLINE_HTML, + LINK + ]; + + BOLD.contains = BOLD.contains.concat(CONTAINABLE); + ITALIC.contains = ITALIC.contains.concat(CONTAINABLE); + + CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC); + + const HEADER = { + className: 'section', + variants: [ + { + begin: '^#{1,6}', + end: '$', + contains: CONTAINABLE + }, + { + begin: '(?=^.+?\\n[=-]{2,}$)', + contains: [ + { + begin: '^[=-]*$' + }, + { + begin: '^', + end: "\\n", + contains: CONTAINABLE + } + ] + } + ] + }; + + const BLOCKQUOTE = { + className: 'quote', + begin: '^>\\s+', + contains: CONTAINABLE, + end: '$' + }; + + return { + name: 'Markdown', + aliases: [ + 'md', + 'mkdown', + 'mkd' + ], + contains: [ + HEADER, + INLINE_HTML, + LIST, + BOLD, + ITALIC, + BLOCKQUOTE, + CODE, + HORIZONTAL_RULE, + LINK, + LINK_REFERENCE + ] + }; +} + +module.exports = markdown; + + +/***/ }), + +/***/ 92982: +/***/ ((module) => { + +const SYSTEM_SYMBOLS = [ + "AASTriangle", + "AbelianGroup", + "Abort", + "AbortKernels", + "AbortProtect", + "AbortScheduledTask", + "Above", + "Abs", + "AbsArg", + "AbsArgPlot", + "Absolute", + "AbsoluteCorrelation", + "AbsoluteCorrelationFunction", + "AbsoluteCurrentValue", + "AbsoluteDashing", + "AbsoluteFileName", + "AbsoluteOptions", + "AbsolutePointSize", + "AbsoluteThickness", + "AbsoluteTime", + "AbsoluteTiming", + "AcceptanceThreshold", + "AccountingForm", + "Accumulate", + "Accuracy", + "AccuracyGoal", + "ActionDelay", + "ActionMenu", + "ActionMenuBox", + "ActionMenuBoxOptions", + "Activate", + "Active", + "ActiveClassification", + "ActiveClassificationObject", + "ActiveItem", + "ActivePrediction", + "ActivePredictionObject", + "ActiveStyle", + "AcyclicGraphQ", + "AddOnHelpPath", + "AddSides", + "AddTo", + "AddToSearchIndex", + "AddUsers", + "AdjacencyGraph", + "AdjacencyList", + "AdjacencyMatrix", + "AdjacentMeshCells", + "AdjustmentBox", + "AdjustmentBoxOptions", + "AdjustTimeSeriesForecast", + "AdministrativeDivisionData", + "AffineHalfSpace", + "AffineSpace", + "AffineStateSpaceModel", + "AffineTransform", + "After", + "AggregatedEntityClass", + "AggregationLayer", + "AircraftData", + "AirportData", + "AirPressureData", + "AirTemperatureData", + "AiryAi", + "AiryAiPrime", + "AiryAiZero", + "AiryBi", + "AiryBiPrime", + "AiryBiZero", + "AlgebraicIntegerQ", + "AlgebraicNumber", + "AlgebraicNumberDenominator", + "AlgebraicNumberNorm", + "AlgebraicNumberPolynomial", + "AlgebraicNumberTrace", + "AlgebraicRules", + "AlgebraicRulesData", + "Algebraics", + "AlgebraicUnitQ", + "Alignment", + "AlignmentMarker", + "AlignmentPoint", + "All", + "AllowAdultContent", + "AllowedCloudExtraParameters", + "AllowedCloudParameterExtensions", + "AllowedDimensions", + "AllowedFrequencyRange", + "AllowedHeads", + "AllowGroupClose", + "AllowIncomplete", + "AllowInlineCells", + "AllowKernelInitialization", + "AllowLooseGrammar", + "AllowReverseGroupClose", + "AllowScriptLevelChange", + "AllowVersionUpdate", + "AllTrue", + "Alphabet", + "AlphabeticOrder", + "AlphabeticSort", + "AlphaChannel", + "AlternateImage", + "AlternatingFactorial", + "AlternatingGroup", + "AlternativeHypothesis", + "Alternatives", + "AltitudeMethod", + "AmbientLight", + "AmbiguityFunction", + "AmbiguityList", + "Analytic", + "AnatomyData", + "AnatomyForm", + "AnatomyPlot3D", + "AnatomySkinStyle", + "AnatomyStyling", + "AnchoredSearch", + "And", + "AndersonDarlingTest", + "AngerJ", + "AngleBisector", + "AngleBracket", + "AnglePath", + "AnglePath3D", + "AngleVector", + "AngularGauge", + "Animate", + "AnimationCycleOffset", + "AnimationCycleRepetitions", + "AnimationDirection", + "AnimationDisplayTime", + "AnimationRate", + "AnimationRepetitions", + "AnimationRunning", + "AnimationRunTime", + "AnimationTimeIndex", + "Animator", + "AnimatorBox", + "AnimatorBoxOptions", + "AnimatorElements", + "Annotate", + "Annotation", + "AnnotationDelete", + "AnnotationKeys", + "AnnotationRules", + "AnnotationValue", + "Annuity", + "AnnuityDue", + "Annulus", + "AnomalyDetection", + "AnomalyDetector", + "AnomalyDetectorFunction", + "Anonymous", + "Antialiasing", + "AntihermitianMatrixQ", + "Antisymmetric", + "AntisymmetricMatrixQ", + "Antonyms", + "AnyOrder", + "AnySubset", + "AnyTrue", + "Apart", + "ApartSquareFree", + "APIFunction", + "Appearance", + "AppearanceElements", + "AppearanceRules", + "AppellF1", + "Append", + "AppendCheck", + "AppendLayer", + "AppendTo", + "Apply", + "ApplySides", + "ArcCos", + "ArcCosh", + "ArcCot", + "ArcCoth", + "ArcCsc", + "ArcCsch", + "ArcCurvature", + "ARCHProcess", + "ArcLength", + "ArcSec", + "ArcSech", + "ArcSin", + "ArcSinDistribution", + "ArcSinh", + "ArcTan", + "ArcTanh", + "Area", + "Arg", + "ArgMax", + "ArgMin", + "ArgumentCountQ", + "ARIMAProcess", + "ArithmeticGeometricMean", + "ARMAProcess", + "Around", + "AroundReplace", + "ARProcess", + "Array", + "ArrayComponents", + "ArrayDepth", + "ArrayFilter", + "ArrayFlatten", + "ArrayMesh", + "ArrayPad", + "ArrayPlot", + "ArrayQ", + "ArrayResample", + "ArrayReshape", + "ArrayRules", + "Arrays", + "Arrow", + "Arrow3DBox", + "ArrowBox", + "Arrowheads", + "ASATriangle", + "Ask", + "AskAppend", + "AskConfirm", + "AskDisplay", + "AskedQ", + "AskedValue", + "AskFunction", + "AskState", + "AskTemplateDisplay", + "AspectRatio", + "AspectRatioFixed", + "Assert", + "AssociateTo", + "Association", + "AssociationFormat", + "AssociationMap", + "AssociationQ", + "AssociationThread", + "AssumeDeterministic", + "Assuming", + "Assumptions", + "AstronomicalData", + "Asymptotic", + "AsymptoticDSolveValue", + "AsymptoticEqual", + "AsymptoticEquivalent", + "AsymptoticGreater", + "AsymptoticGreaterEqual", + "AsymptoticIntegrate", + "AsymptoticLess", + "AsymptoticLessEqual", + "AsymptoticOutputTracker", + "AsymptoticProduct", + "AsymptoticRSolveValue", + "AsymptoticSolve", + "AsymptoticSum", + "Asynchronous", + "AsynchronousTaskObject", + "AsynchronousTasks", + "Atom", + "AtomCoordinates", + "AtomCount", + "AtomDiagramCoordinates", + "AtomList", + "AtomQ", + "AttentionLayer", + "Attributes", + "Audio", + "AudioAmplify", + "AudioAnnotate", + "AudioAnnotationLookup", + "AudioBlockMap", + "AudioCapture", + "AudioChannelAssignment", + "AudioChannelCombine", + "AudioChannelMix", + "AudioChannels", + "AudioChannelSeparate", + "AudioData", + "AudioDelay", + "AudioDelete", + "AudioDevice", + "AudioDistance", + "AudioEncoding", + "AudioFade", + "AudioFrequencyShift", + "AudioGenerator", + "AudioIdentify", + "AudioInputDevice", + "AudioInsert", + "AudioInstanceQ", + "AudioIntervals", + "AudioJoin", + "AudioLabel", + "AudioLength", + "AudioLocalMeasurements", + "AudioLooping", + "AudioLoudness", + "AudioMeasurements", + "AudioNormalize", + "AudioOutputDevice", + "AudioOverlay", + "AudioPad", + "AudioPan", + "AudioPartition", + "AudioPause", + "AudioPitchShift", + "AudioPlay", + "AudioPlot", + "AudioQ", + "AudioRecord", + "AudioReplace", + "AudioResample", + "AudioReverb", + "AudioReverse", + "AudioSampleRate", + "AudioSpectralMap", + "AudioSpectralTransformation", + "AudioSplit", + "AudioStop", + "AudioStream", + "AudioStreams", + "AudioTimeStretch", + "AudioTracks", + "AudioTrim", + "AudioType", + "AugmentedPolyhedron", + "AugmentedSymmetricPolynomial", + "Authenticate", + "Authentication", + "AuthenticationDialog", + "AutoAction", + "Autocomplete", + "AutocompletionFunction", + "AutoCopy", + "AutocorrelationTest", + "AutoDelete", + "AutoEvaluateEvents", + "AutoGeneratedPackage", + "AutoIndent", + "AutoIndentSpacings", + "AutoItalicWords", + "AutoloadPath", + "AutoMatch", + "Automatic", + "AutomaticImageSize", + "AutoMultiplicationSymbol", + "AutoNumberFormatting", + "AutoOpenNotebooks", + "AutoOpenPalettes", + "AutoQuoteCharacters", + "AutoRefreshed", + "AutoRemove", + "AutorunSequencing", + "AutoScaling", + "AutoScroll", + "AutoSpacing", + "AutoStyleOptions", + "AutoStyleWords", + "AutoSubmitting", + "Axes", + "AxesEdge", + "AxesLabel", + "AxesOrigin", + "AxesStyle", + "AxiomaticTheory", + "Axis", + "BabyMonsterGroupB", + "Back", + "Background", + "BackgroundAppearance", + "BackgroundTasksSettings", + "Backslash", + "Backsubstitution", + "Backward", + "Ball", + "Band", + "BandpassFilter", + "BandstopFilter", + "BarabasiAlbertGraphDistribution", + "BarChart", + "BarChart3D", + "BarcodeImage", + "BarcodeRecognize", + "BaringhausHenzeTest", + "BarLegend", + "BarlowProschanImportance", + "BarnesG", + "BarOrigin", + "BarSpacing", + "BartlettHannWindow", + "BartlettWindow", + "BaseDecode", + "BaseEncode", + "BaseForm", + "Baseline", + "BaselinePosition", + "BaseStyle", + "BasicRecurrentLayer", + "BatchNormalizationLayer", + "BatchSize", + "BatesDistribution", + "BattleLemarieWavelet", + "BayesianMaximization", + "BayesianMaximizationObject", + "BayesianMinimization", + "BayesianMinimizationObject", + "Because", + "BeckmannDistribution", + "Beep", + "Before", + "Begin", + "BeginDialogPacket", + "BeginFrontEndInteractionPacket", + "BeginPackage", + "BellB", + "BellY", + "Below", + "BenfordDistribution", + "BeniniDistribution", + "BenktanderGibratDistribution", + "BenktanderWeibullDistribution", + "BernoulliB", + "BernoulliDistribution", + "BernoulliGraphDistribution", + "BernoulliProcess", + "BernsteinBasis", + "BesselFilterModel", + "BesselI", + "BesselJ", + "BesselJZero", + "BesselK", + "BesselY", + "BesselYZero", + "Beta", + "BetaBinomialDistribution", + "BetaDistribution", + "BetaNegativeBinomialDistribution", + "BetaPrimeDistribution", + "BetaRegularized", + "Between", + "BetweennessCentrality", + "BeveledPolyhedron", + "BezierCurve", + "BezierCurve3DBox", + "BezierCurve3DBoxOptions", + "BezierCurveBox", + "BezierCurveBoxOptions", + "BezierFunction", + "BilateralFilter", + "Binarize", + "BinaryDeserialize", + "BinaryDistance", + "BinaryFormat", + "BinaryImageQ", + "BinaryRead", + "BinaryReadList", + "BinarySerialize", + "BinaryWrite", + "BinCounts", + "BinLists", + "Binomial", + "BinomialDistribution", + "BinomialProcess", + "BinormalDistribution", + "BiorthogonalSplineWavelet", + "BipartiteGraphQ", + "BiquadraticFilterModel", + "BirnbaumImportance", + "BirnbaumSaundersDistribution", + "BitAnd", + "BitClear", + "BitGet", + "BitLength", + "BitNot", + "BitOr", + "BitSet", + "BitShiftLeft", + "BitShiftRight", + "BitXor", + "BiweightLocation", + "BiweightMidvariance", + "Black", + "BlackmanHarrisWindow", + "BlackmanNuttallWindow", + "BlackmanWindow", + "Blank", + "BlankForm", + "BlankNullSequence", + "BlankSequence", + "Blend", + "Block", + "BlockchainAddressData", + "BlockchainBase", + "BlockchainBlockData", + "BlockchainContractValue", + "BlockchainData", + "BlockchainGet", + "BlockchainKeyEncode", + "BlockchainPut", + "BlockchainTokenData", + "BlockchainTransaction", + "BlockchainTransactionData", + "BlockchainTransactionSign", + "BlockchainTransactionSubmit", + "BlockMap", + "BlockRandom", + "BlomqvistBeta", + "BlomqvistBetaTest", + "Blue", + "Blur", + "BodePlot", + "BohmanWindow", + "Bold", + "Bond", + "BondCount", + "BondList", + "BondQ", + "Bookmarks", + "Boole", + "BooleanConsecutiveFunction", + "BooleanConvert", + "BooleanCountingFunction", + "BooleanFunction", + "BooleanGraph", + "BooleanMaxterms", + "BooleanMinimize", + "BooleanMinterms", + "BooleanQ", + "BooleanRegion", + "Booleans", + "BooleanStrings", + "BooleanTable", + "BooleanVariables", + "BorderDimensions", + "BorelTannerDistribution", + "Bottom", + "BottomHatTransform", + "BoundaryDiscretizeGraphics", + "BoundaryDiscretizeRegion", + "BoundaryMesh", + "BoundaryMeshRegion", + "BoundaryMeshRegionQ", + "BoundaryStyle", + "BoundedRegionQ", + "BoundingRegion", + "Bounds", + "Box", + "BoxBaselineShift", + "BoxData", + "BoxDimensions", + "Boxed", + "Boxes", + "BoxForm", + "BoxFormFormatTypes", + "BoxFrame", + "BoxID", + "BoxMargins", + "BoxMatrix", + "BoxObject", + "BoxRatios", + "BoxRotation", + "BoxRotationPoint", + "BoxStyle", + "BoxWhiskerChart", + "Bra", + "BracketingBar", + "BraKet", + "BrayCurtisDistance", + "BreadthFirstScan", + "Break", + "BridgeData", + "BrightnessEqualize", + "BroadcastStationData", + "Brown", + "BrownForsytheTest", + "BrownianBridgeProcess", + "BrowserCategory", + "BSplineBasis", + "BSplineCurve", + "BSplineCurve3DBox", + "BSplineCurve3DBoxOptions", + "BSplineCurveBox", + "BSplineCurveBoxOptions", + "BSplineFunction", + "BSplineSurface", + "BSplineSurface3DBox", + "BSplineSurface3DBoxOptions", + "BubbleChart", + "BubbleChart3D", + "BubbleScale", + "BubbleSizes", + "BuildingData", + "BulletGauge", + "BusinessDayQ", + "ButterflyGraph", + "ButterworthFilterModel", + "Button", + "ButtonBar", + "ButtonBox", + "ButtonBoxOptions", + "ButtonCell", + "ButtonContents", + "ButtonData", + "ButtonEvaluator", + "ButtonExpandable", + "ButtonFrame", + "ButtonFunction", + "ButtonMargins", + "ButtonMinHeight", + "ButtonNote", + "ButtonNotebook", + "ButtonSource", + "ButtonStyle", + "ButtonStyleMenuListing", + "Byte", + "ByteArray", + "ByteArrayFormat", + "ByteArrayQ", + "ByteArrayToString", + "ByteCount", + "ByteOrdering", + "C", + "CachedValue", + "CacheGraphics", + "CachePersistence", + "CalendarConvert", + "CalendarData", + "CalendarType", + "Callout", + "CalloutMarker", + "CalloutStyle", + "CallPacket", + "CanberraDistance", + "Cancel", + "CancelButton", + "CandlestickChart", + "CanonicalGraph", + "CanonicalizePolygon", + "CanonicalizePolyhedron", + "CanonicalName", + "CanonicalWarpingCorrespondence", + "CanonicalWarpingDistance", + "CantorMesh", + "CantorStaircase", + "Cap", + "CapForm", + "CapitalDifferentialD", + "Capitalize", + "CapsuleShape", + "CaptureRunning", + "CardinalBSplineBasis", + "CarlemanLinearize", + "CarmichaelLambda", + "CaseOrdering", + "Cases", + "CaseSensitive", + "Cashflow", + "Casoratian", + "Catalan", + "CatalanNumber", + "Catch", + "CategoricalDistribution", + "Catenate", + "CatenateLayer", + "CauchyDistribution", + "CauchyWindow", + "CayleyGraph", + "CDF", + "CDFDeploy", + "CDFInformation", + "CDFWavelet", + "Ceiling", + "CelestialSystem", + "Cell", + "CellAutoOverwrite", + "CellBaseline", + "CellBoundingBox", + "CellBracketOptions", + "CellChangeTimes", + "CellContents", + "CellContext", + "CellDingbat", + "CellDynamicExpression", + "CellEditDuplicate", + "CellElementsBoundingBox", + "CellElementSpacings", + "CellEpilog", + "CellEvaluationDuplicate", + "CellEvaluationFunction", + "CellEvaluationLanguage", + "CellEventActions", + "CellFrame", + "CellFrameColor", + "CellFrameLabelMargins", + "CellFrameLabels", + "CellFrameMargins", + "CellGroup", + "CellGroupData", + "CellGrouping", + "CellGroupingRules", + "CellHorizontalScrolling", + "CellID", + "CellLabel", + "CellLabelAutoDelete", + "CellLabelMargins", + "CellLabelPositioning", + "CellLabelStyle", + "CellLabelTemplate", + "CellMargins", + "CellObject", + "CellOpen", + "CellPrint", + "CellProlog", + "Cells", + "CellSize", + "CellStyle", + "CellTags", + "CellularAutomaton", + "CensoredDistribution", + "Censoring", + "Center", + "CenterArray", + "CenterDot", + "CentralFeature", + "CentralMoment", + "CentralMomentGeneratingFunction", + "Cepstrogram", + "CepstrogramArray", + "CepstrumArray", + "CForm", + "ChampernowneNumber", + "ChangeOptions", + "ChannelBase", + "ChannelBrokerAction", + "ChannelDatabin", + "ChannelHistoryLength", + "ChannelListen", + "ChannelListener", + "ChannelListeners", + "ChannelListenerWait", + "ChannelObject", + "ChannelPreSendFunction", + "ChannelReceiverFunction", + "ChannelSend", + "ChannelSubscribers", + "ChanVeseBinarize", + "Character", + "CharacterCounts", + "CharacterEncoding", + "CharacterEncodingsPath", + "CharacteristicFunction", + "CharacteristicPolynomial", + "CharacterName", + "CharacterNormalize", + "CharacterRange", + "Characters", + "ChartBaseStyle", + "ChartElementData", + "ChartElementDataFunction", + "ChartElementFunction", + "ChartElements", + "ChartLabels", + "ChartLayout", + "ChartLegends", + "ChartStyle", + "Chebyshev1FilterModel", + "Chebyshev2FilterModel", + "ChebyshevDistance", + "ChebyshevT", + "ChebyshevU", + "Check", + "CheckAbort", + "CheckAll", + "Checkbox", + "CheckboxBar", + "CheckboxBox", + "CheckboxBoxOptions", + "ChemicalData", + "ChessboardDistance", + "ChiDistribution", + "ChineseRemainder", + "ChiSquareDistribution", + "ChoiceButtons", + "ChoiceDialog", + "CholeskyDecomposition", + "Chop", + "ChromaticityPlot", + "ChromaticityPlot3D", + "ChromaticPolynomial", + "Circle", + "CircleBox", + "CircleDot", + "CircleMinus", + "CirclePlus", + "CirclePoints", + "CircleThrough", + "CircleTimes", + "CirculantGraph", + "CircularOrthogonalMatrixDistribution", + "CircularQuaternionMatrixDistribution", + "CircularRealMatrixDistribution", + "CircularSymplecticMatrixDistribution", + "CircularUnitaryMatrixDistribution", + "Circumsphere", + "CityData", + "ClassifierFunction", + "ClassifierInformation", + "ClassifierMeasurements", + "ClassifierMeasurementsObject", + "Classify", + "ClassPriors", + "Clear", + "ClearAll", + "ClearAttributes", + "ClearCookies", + "ClearPermissions", + "ClearSystemCache", + "ClebschGordan", + "ClickPane", + "Clip", + "ClipboardNotebook", + "ClipFill", + "ClippingStyle", + "ClipPlanes", + "ClipPlanesStyle", + "ClipRange", + "Clock", + "ClockGauge", + "ClockwiseContourIntegral", + "Close", + "Closed", + "CloseKernels", + "ClosenessCentrality", + "Closing", + "ClosingAutoSave", + "ClosingEvent", + "ClosingSaveDialog", + "CloudAccountData", + "CloudBase", + "CloudConnect", + "CloudConnections", + "CloudDeploy", + "CloudDirectory", + "CloudDisconnect", + "CloudEvaluate", + "CloudExport", + "CloudExpression", + "CloudExpressions", + "CloudFunction", + "CloudGet", + "CloudImport", + "CloudLoggingData", + "CloudObject", + "CloudObjectInformation", + "CloudObjectInformationData", + "CloudObjectNameFormat", + "CloudObjects", + "CloudObjectURLType", + "CloudPublish", + "CloudPut", + "CloudRenderingMethod", + "CloudSave", + "CloudShare", + "CloudSubmit", + "CloudSymbol", + "CloudUnshare", + "CloudUserID", + "ClusterClassify", + "ClusterDissimilarityFunction", + "ClusteringComponents", + "ClusteringTree", + "CMYKColor", + "Coarse", + "CodeAssistOptions", + "Coefficient", + "CoefficientArrays", + "CoefficientDomain", + "CoefficientList", + "CoefficientRules", + "CoifletWavelet", + "Collect", + "Colon", + "ColonForm", + "ColorBalance", + "ColorCombine", + "ColorConvert", + "ColorCoverage", + "ColorData", + "ColorDataFunction", + "ColorDetect", + "ColorDistance", + "ColorFunction", + "ColorFunctionScaling", + "Colorize", + "ColorNegate", + "ColorOutput", + "ColorProfileData", + "ColorQ", + "ColorQuantize", + "ColorReplace", + "ColorRules", + "ColorSelectorSettings", + "ColorSeparate", + "ColorSetter", + "ColorSetterBox", + "ColorSetterBoxOptions", + "ColorSlider", + "ColorsNear", + "ColorSpace", + "ColorToneMapping", + "Column", + "ColumnAlignments", + "ColumnBackgrounds", + "ColumnForm", + "ColumnLines", + "ColumnsEqual", + "ColumnSpacings", + "ColumnWidths", + "CombinedEntityClass", + "CombinerFunction", + "CometData", + "CommonDefaultFormatTypes", + "Commonest", + "CommonestFilter", + "CommonName", + "CommonUnits", + "CommunityBoundaryStyle", + "CommunityGraphPlot", + "CommunityLabels", + "CommunityRegionStyle", + "CompanyData", + "CompatibleUnitQ", + "CompilationOptions", + "CompilationTarget", + "Compile", + "Compiled", + "CompiledCodeFunction", + "CompiledFunction", + "CompilerOptions", + "Complement", + "ComplementedEntityClass", + "CompleteGraph", + "CompleteGraphQ", + "CompleteKaryTree", + "CompletionsListPacket", + "Complex", + "ComplexContourPlot", + "Complexes", + "ComplexExpand", + "ComplexInfinity", + "ComplexityFunction", + "ComplexListPlot", + "ComplexPlot", + "ComplexPlot3D", + "ComplexRegionPlot", + "ComplexStreamPlot", + "ComplexVectorPlot", + "ComponentMeasurements", + "ComponentwiseContextMenu", + "Compose", + "ComposeList", + "ComposeSeries", + "CompositeQ", + "Composition", + "CompoundElement", + "CompoundExpression", + "CompoundPoissonDistribution", + "CompoundPoissonProcess", + "CompoundRenewalProcess", + "Compress", + "CompressedData", + "CompressionLevel", + "ComputeUncertainty", + "Condition", + "ConditionalExpression", + "Conditioned", + "Cone", + "ConeBox", + "ConfidenceLevel", + "ConfidenceRange", + "ConfidenceTransform", + "ConfigurationPath", + "ConformAudio", + "ConformImages", + "Congruent", + "ConicHullRegion", + "ConicHullRegion3DBox", + "ConicHullRegionBox", + "ConicOptimization", + "Conjugate", + "ConjugateTranspose", + "Conjunction", + "Connect", + "ConnectedComponents", + "ConnectedGraphComponents", + "ConnectedGraphQ", + "ConnectedMeshComponents", + "ConnectedMoleculeComponents", + "ConnectedMoleculeQ", + "ConnectionSettings", + "ConnectLibraryCallbackFunction", + "ConnectSystemModelComponents", + "ConnesWindow", + "ConoverTest", + "ConsoleMessage", + "ConsoleMessagePacket", + "Constant", + "ConstantArray", + "ConstantArrayLayer", + "ConstantImage", + "ConstantPlusLayer", + "ConstantRegionQ", + "Constants", + "ConstantTimesLayer", + "ConstellationData", + "ConstrainedMax", + "ConstrainedMin", + "Construct", + "Containing", + "ContainsAll", + "ContainsAny", + "ContainsExactly", + "ContainsNone", + "ContainsOnly", + "ContentFieldOptions", + "ContentLocationFunction", + "ContentObject", + "ContentPadding", + "ContentsBoundingBox", + "ContentSelectable", + "ContentSize", + "Context", + "ContextMenu", + "Contexts", + "ContextToFileName", + "Continuation", + "Continue", + "ContinuedFraction", + "ContinuedFractionK", + "ContinuousAction", + "ContinuousMarkovProcess", + "ContinuousTask", + "ContinuousTimeModelQ", + "ContinuousWaveletData", + "ContinuousWaveletTransform", + "ContourDetect", + "ContourGraphics", + "ContourIntegral", + "ContourLabels", + "ContourLines", + "ContourPlot", + "ContourPlot3D", + "Contours", + "ContourShading", + "ContourSmoothing", + "ContourStyle", + "ContraharmonicMean", + "ContrastiveLossLayer", + "Control", + "ControlActive", + "ControlAlignment", + "ControlGroupContentsBox", + "ControllabilityGramian", + "ControllabilityMatrix", + "ControllableDecomposition", + "ControllableModelQ", + "ControllerDuration", + "ControllerInformation", + "ControllerInformationData", + "ControllerLinking", + "ControllerManipulate", + "ControllerMethod", + "ControllerPath", + "ControllerState", + "ControlPlacement", + "ControlsRendering", + "ControlType", + "Convergents", + "ConversionOptions", + "ConversionRules", + "ConvertToBitmapPacket", + "ConvertToPostScript", + "ConvertToPostScriptPacket", + "ConvexHullMesh", + "ConvexPolygonQ", + "ConvexPolyhedronQ", + "ConvolutionLayer", + "Convolve", + "ConwayGroupCo1", + "ConwayGroupCo2", + "ConwayGroupCo3", + "CookieFunction", + "Cookies", + "CoordinateBoundingBox", + "CoordinateBoundingBoxArray", + "CoordinateBounds", + "CoordinateBoundsArray", + "CoordinateChartData", + "CoordinatesToolOptions", + "CoordinateTransform", + "CoordinateTransformData", + "CoprimeQ", + "Coproduct", + "CopulaDistribution", + "Copyable", + "CopyDatabin", + "CopyDirectory", + "CopyFile", + "CopyTag", + "CopyToClipboard", + "CornerFilter", + "CornerNeighbors", + "Correlation", + "CorrelationDistance", + "CorrelationFunction", + "CorrelationTest", + "Cos", + "Cosh", + "CoshIntegral", + "CosineDistance", + "CosineWindow", + "CosIntegral", + "Cot", + "Coth", + "Count", + "CountDistinct", + "CountDistinctBy", + "CounterAssignments", + "CounterBox", + "CounterBoxOptions", + "CounterClockwiseContourIntegral", + "CounterEvaluator", + "CounterFunction", + "CounterIncrements", + "CounterStyle", + "CounterStyleMenuListing", + "CountRoots", + "CountryData", + "Counts", + "CountsBy", + "Covariance", + "CovarianceEstimatorFunction", + "CovarianceFunction", + "CoxianDistribution", + "CoxIngersollRossProcess", + "CoxModel", + "CoxModelFit", + "CramerVonMisesTest", + "CreateArchive", + "CreateCellID", + "CreateChannel", + "CreateCloudExpression", + "CreateDatabin", + "CreateDataStructure", + "CreateDataSystemModel", + "CreateDialog", + "CreateDirectory", + "CreateDocument", + "CreateFile", + "CreateIntermediateDirectories", + "CreateManagedLibraryExpression", + "CreateNotebook", + "CreatePacletArchive", + "CreatePalette", + "CreatePalettePacket", + "CreatePermissionsGroup", + "CreateScheduledTask", + "CreateSearchIndex", + "CreateSystemModel", + "CreateTemporary", + "CreateUUID", + "CreateWindow", + "CriterionFunction", + "CriticalityFailureImportance", + "CriticalitySuccessImportance", + "CriticalSection", + "Cross", + "CrossEntropyLossLayer", + "CrossingCount", + "CrossingDetect", + "CrossingPolygon", + "CrossMatrix", + "Csc", + "Csch", + "CTCLossLayer", + "Cube", + "CubeRoot", + "Cubics", + "Cuboid", + "CuboidBox", + "Cumulant", + "CumulantGeneratingFunction", + "Cup", + "CupCap", + "Curl", + "CurlyDoubleQuote", + "CurlyQuote", + "CurrencyConvert", + "CurrentDate", + "CurrentImage", + "CurrentlySpeakingPacket", + "CurrentNotebookImage", + "CurrentScreenImage", + "CurrentValue", + "Curry", + "CurryApplied", + "CurvatureFlowFilter", + "CurveClosed", + "Cyan", + "CycleGraph", + "CycleIndexPolynomial", + "Cycles", + "CyclicGroup", + "Cyclotomic", + "Cylinder", + "CylinderBox", + "CylindricalDecomposition", + "D", + "DagumDistribution", + "DamData", + "DamerauLevenshteinDistance", + "DampingFactor", + "Darker", + "Dashed", + "Dashing", + "DatabaseConnect", + "DatabaseDisconnect", + "DatabaseReference", + "Databin", + "DatabinAdd", + "DatabinRemove", + "Databins", + "DatabinUpload", + "DataCompression", + "DataDistribution", + "DataRange", + "DataReversed", + "Dataset", + "DatasetDisplayPanel", + "DataStructure", + "DataStructureQ", + "Date", + "DateBounds", + "Dated", + "DateDelimiters", + "DateDifference", + "DatedUnit", + "DateFormat", + "DateFunction", + "DateHistogram", + "DateInterval", + "DateList", + "DateListLogPlot", + "DateListPlot", + "DateListStepPlot", + "DateObject", + "DateObjectQ", + "DateOverlapsQ", + "DatePattern", + "DatePlus", + "DateRange", + "DateReduction", + "DateString", + "DateTicksFormat", + "DateValue", + "DateWithinQ", + "DaubechiesWavelet", + "DavisDistribution", + "DawsonF", + "DayCount", + "DayCountConvention", + "DayHemisphere", + "DaylightQ", + "DayMatchQ", + "DayName", + "DayNightTerminator", + "DayPlus", + "DayRange", + "DayRound", + "DeBruijnGraph", + "DeBruijnSequence", + "Debug", + "DebugTag", + "Decapitalize", + "Decimal", + "DecimalForm", + "DeclareKnownSymbols", + "DeclarePackage", + "Decompose", + "DeconvolutionLayer", + "Decrement", + "Decrypt", + "DecryptFile", + "DedekindEta", + "DeepSpaceProbeData", + "Default", + "DefaultAxesStyle", + "DefaultBaseStyle", + "DefaultBoxStyle", + "DefaultButton", + "DefaultColor", + "DefaultControlPlacement", + "DefaultDuplicateCellStyle", + "DefaultDuration", + "DefaultElement", + "DefaultFaceGridsStyle", + "DefaultFieldHintStyle", + "DefaultFont", + "DefaultFontProperties", + "DefaultFormatType", + "DefaultFormatTypeForStyle", + "DefaultFrameStyle", + "DefaultFrameTicksStyle", + "DefaultGridLinesStyle", + "DefaultInlineFormatType", + "DefaultInputFormatType", + "DefaultLabelStyle", + "DefaultMenuStyle", + "DefaultNaturalLanguage", + "DefaultNewCellStyle", + "DefaultNewInlineCellStyle", + "DefaultNotebook", + "DefaultOptions", + "DefaultOutputFormatType", + "DefaultPrintPrecision", + "DefaultStyle", + "DefaultStyleDefinitions", + "DefaultTextFormatType", + "DefaultTextInlineFormatType", + "DefaultTicksStyle", + "DefaultTooltipStyle", + "DefaultValue", + "DefaultValues", + "Defer", + "DefineExternal", + "DefineInputStreamMethod", + "DefineOutputStreamMethod", + "DefineResourceFunction", + "Definition", + "Degree", + "DegreeCentrality", + "DegreeGraphDistribution", + "DegreeLexicographic", + "DegreeReverseLexicographic", + "DEigensystem", + "DEigenvalues", + "Deinitialization", + "Del", + "DelaunayMesh", + "Delayed", + "Deletable", + "Delete", + "DeleteAnomalies", + "DeleteBorderComponents", + "DeleteCases", + "DeleteChannel", + "DeleteCloudExpression", + "DeleteContents", + "DeleteDirectory", + "DeleteDuplicates", + "DeleteDuplicatesBy", + "DeleteFile", + "DeleteMissing", + "DeleteObject", + "DeletePermissionsKey", + "DeleteSearchIndex", + "DeleteSmallComponents", + "DeleteStopwords", + "DeleteWithContents", + "DeletionWarning", + "DelimitedArray", + "DelimitedSequence", + "Delimiter", + "DelimiterFlashTime", + "DelimiterMatching", + "Delimiters", + "DeliveryFunction", + "Dendrogram", + "Denominator", + "DensityGraphics", + "DensityHistogram", + "DensityPlot", + "DensityPlot3D", + "DependentVariables", + "Deploy", + "Deployed", + "Depth", + "DepthFirstScan", + "Derivative", + "DerivativeFilter", + "DerivedKey", + "DescriptorStateSpace", + "DesignMatrix", + "DestroyAfterEvaluation", + "Det", + "DeviceClose", + "DeviceConfigure", + "DeviceExecute", + "DeviceExecuteAsynchronous", + "DeviceObject", + "DeviceOpen", + "DeviceOpenQ", + "DeviceRead", + "DeviceReadBuffer", + "DeviceReadLatest", + "DeviceReadList", + "DeviceReadTimeSeries", + "Devices", + "DeviceStreams", + "DeviceWrite", + "DeviceWriteBuffer", + "DGaussianWavelet", + "DiacriticalPositioning", + "Diagonal", + "DiagonalizableMatrixQ", + "DiagonalMatrix", + "DiagonalMatrixQ", + "Dialog", + "DialogIndent", + "DialogInput", + "DialogLevel", + "DialogNotebook", + "DialogProlog", + "DialogReturn", + "DialogSymbols", + "Diamond", + "DiamondMatrix", + "DiceDissimilarity", + "DictionaryLookup", + "DictionaryWordQ", + "DifferenceDelta", + "DifferenceOrder", + "DifferenceQuotient", + "DifferenceRoot", + "DifferenceRootReduce", + "Differences", + "DifferentialD", + "DifferentialRoot", + "DifferentialRootReduce", + "DifferentiatorFilter", + "DigitalSignature", + "DigitBlock", + "DigitBlockMinimum", + "DigitCharacter", + "DigitCount", + "DigitQ", + "DihedralAngle", + "DihedralGroup", + "Dilation", + "DimensionalCombinations", + "DimensionalMeshComponents", + "DimensionReduce", + "DimensionReducerFunction", + "DimensionReduction", + "Dimensions", + "DiracComb", + "DiracDelta", + "DirectedEdge", + "DirectedEdges", + "DirectedGraph", + "DirectedGraphQ", + "DirectedInfinity", + "Direction", + "Directive", + "Directory", + "DirectoryName", + "DirectoryQ", + "DirectoryStack", + "DirichletBeta", + "DirichletCharacter", + "DirichletCondition", + "DirichletConvolve", + "DirichletDistribution", + "DirichletEta", + "DirichletL", + "DirichletLambda", + "DirichletTransform", + "DirichletWindow", + "DisableConsolePrintPacket", + "DisableFormatting", + "DiscreteAsymptotic", + "DiscreteChirpZTransform", + "DiscreteConvolve", + "DiscreteDelta", + "DiscreteHadamardTransform", + "DiscreteIndicator", + "DiscreteLimit", + "DiscreteLQEstimatorGains", + "DiscreteLQRegulatorGains", + "DiscreteLyapunovSolve", + "DiscreteMarkovProcess", + "DiscreteMaxLimit", + "DiscreteMinLimit", + "DiscretePlot", + "DiscretePlot3D", + "DiscreteRatio", + "DiscreteRiccatiSolve", + "DiscreteShift", + "DiscreteTimeModelQ", + "DiscreteUniformDistribution", + "DiscreteVariables", + "DiscreteWaveletData", + "DiscreteWaveletPacketTransform", + "DiscreteWaveletTransform", + "DiscretizeGraphics", + "DiscretizeRegion", + "Discriminant", + "DisjointQ", + "Disjunction", + "Disk", + "DiskBox", + "DiskMatrix", + "DiskSegment", + "Dispatch", + "DispatchQ", + "DispersionEstimatorFunction", + "Display", + "DisplayAllSteps", + "DisplayEndPacket", + "DisplayFlushImagePacket", + "DisplayForm", + "DisplayFunction", + "DisplayPacket", + "DisplayRules", + "DisplaySetSizePacket", + "DisplayString", + "DisplayTemporary", + "DisplayWith", + "DisplayWithRef", + "DisplayWithVariable", + "DistanceFunction", + "DistanceMatrix", + "DistanceTransform", + "Distribute", + "Distributed", + "DistributedContexts", + "DistributeDefinitions", + "DistributionChart", + "DistributionDomain", + "DistributionFitTest", + "DistributionParameterAssumptions", + "DistributionParameterQ", + "Dithering", + "Div", + "Divergence", + "Divide", + "DivideBy", + "Dividers", + "DivideSides", + "Divisible", + "Divisors", + "DivisorSigma", + "DivisorSum", + "DMSList", + "DMSString", + "Do", + "DockedCells", + "DocumentGenerator", + "DocumentGeneratorInformation", + "DocumentGeneratorInformationData", + "DocumentGenerators", + "DocumentNotebook", + "DocumentWeightingRules", + "Dodecahedron", + "DomainRegistrationInformation", + "DominantColors", + "DOSTextFormat", + "Dot", + "DotDashed", + "DotEqual", + "DotLayer", + "DotPlusLayer", + "Dotted", + "DoubleBracketingBar", + "DoubleContourIntegral", + "DoubleDownArrow", + "DoubleLeftArrow", + "DoubleLeftRightArrow", + "DoubleLeftTee", + "DoubleLongLeftArrow", + "DoubleLongLeftRightArrow", + "DoubleLongRightArrow", + "DoubleRightArrow", + "DoubleRightTee", + "DoubleUpArrow", + "DoubleUpDownArrow", + "DoubleVerticalBar", + "DoublyInfinite", + "Down", + "DownArrow", + "DownArrowBar", + "DownArrowUpArrow", + "DownLeftRightVector", + "DownLeftTeeVector", + "DownLeftVector", + "DownLeftVectorBar", + "DownRightTeeVector", + "DownRightVector", + "DownRightVectorBar", + "Downsample", + "DownTee", + "DownTeeArrow", + "DownValues", + "DragAndDrop", + "DrawEdges", + "DrawFrontFaces", + "DrawHighlighted", + "Drop", + "DropoutLayer", + "DSolve", + "DSolveValue", + "Dt", + "DualLinearProgramming", + "DualPolyhedron", + "DualSystemsModel", + "DumpGet", + "DumpSave", + "DuplicateFreeQ", + "Duration", + "Dynamic", + "DynamicBox", + "DynamicBoxOptions", + "DynamicEvaluationTimeout", + "DynamicGeoGraphics", + "DynamicImage", + "DynamicLocation", + "DynamicModule", + "DynamicModuleBox", + "DynamicModuleBoxOptions", + "DynamicModuleParent", + "DynamicModuleValues", + "DynamicName", + "DynamicNamespace", + "DynamicReference", + "DynamicSetting", + "DynamicUpdating", + "DynamicWrapper", + "DynamicWrapperBox", + "DynamicWrapperBoxOptions", + "E", + "EarthImpactData", + "EarthquakeData", + "EccentricityCentrality", + "Echo", + "EchoFunction", + "EclipseType", + "EdgeAdd", + "EdgeBetweennessCentrality", + "EdgeCapacity", + "EdgeCapForm", + "EdgeColor", + "EdgeConnectivity", + "EdgeContract", + "EdgeCost", + "EdgeCount", + "EdgeCoverQ", + "EdgeCycleMatrix", + "EdgeDashing", + "EdgeDelete", + "EdgeDetect", + "EdgeForm", + "EdgeIndex", + "EdgeJoinForm", + "EdgeLabeling", + "EdgeLabels", + "EdgeLabelStyle", + "EdgeList", + "EdgeOpacity", + "EdgeQ", + "EdgeRenderingFunction", + "EdgeRules", + "EdgeShapeFunction", + "EdgeStyle", + "EdgeTaggedGraph", + "EdgeTaggedGraphQ", + "EdgeTags", + "EdgeThickness", + "EdgeWeight", + "EdgeWeightedGraphQ", + "Editable", + "EditButtonSettings", + "EditCellTagsSettings", + "EditDistance", + "EffectiveInterest", + "Eigensystem", + "Eigenvalues", + "EigenvectorCentrality", + "Eigenvectors", + "Element", + "ElementData", + "ElementwiseLayer", + "ElidedForms", + "Eliminate", + "EliminationOrder", + "Ellipsoid", + "EllipticE", + "EllipticExp", + "EllipticExpPrime", + "EllipticF", + "EllipticFilterModel", + "EllipticK", + "EllipticLog", + "EllipticNomeQ", + "EllipticPi", + "EllipticReducedHalfPeriods", + "EllipticTheta", + "EllipticThetaPrime", + "EmbedCode", + "EmbeddedHTML", + "EmbeddedService", + "EmbeddingLayer", + "EmbeddingObject", + "EmitSound", + "EmphasizeSyntaxErrors", + "EmpiricalDistribution", + "Empty", + "EmptyGraphQ", + "EmptyRegion", + "EnableConsolePrintPacket", + "Enabled", + "Encode", + "Encrypt", + "EncryptedObject", + "EncryptFile", + "End", + "EndAdd", + "EndDialogPacket", + "EndFrontEndInteractionPacket", + "EndOfBuffer", + "EndOfFile", + "EndOfLine", + "EndOfString", + "EndPackage", + "EngineEnvironment", + "EngineeringForm", + "Enter", + "EnterExpressionPacket", + "EnterTextPacket", + "Entity", + "EntityClass", + "EntityClassList", + "EntityCopies", + "EntityFunction", + "EntityGroup", + "EntityInstance", + "EntityList", + "EntityPrefetch", + "EntityProperties", + "EntityProperty", + "EntityPropertyClass", + "EntityRegister", + "EntityStore", + "EntityStores", + "EntityTypeName", + "EntityUnregister", + "EntityValue", + "Entropy", + "EntropyFilter", + "Environment", + "Epilog", + "EpilogFunction", + "Equal", + "EqualColumns", + "EqualRows", + "EqualTilde", + "EqualTo", + "EquatedTo", + "Equilibrium", + "EquirippleFilterKernel", + "Equivalent", + "Erf", + "Erfc", + "Erfi", + "ErlangB", + "ErlangC", + "ErlangDistribution", + "Erosion", + "ErrorBox", + "ErrorBoxOptions", + "ErrorNorm", + "ErrorPacket", + "ErrorsDialogSettings", + "EscapeRadius", + "EstimatedBackground", + "EstimatedDistribution", + "EstimatedProcess", + "EstimatorGains", + "EstimatorRegulator", + "EuclideanDistance", + "EulerAngles", + "EulerCharacteristic", + "EulerE", + "EulerGamma", + "EulerianGraphQ", + "EulerMatrix", + "EulerPhi", + "Evaluatable", + "Evaluate", + "Evaluated", + "EvaluatePacket", + "EvaluateScheduledTask", + "EvaluationBox", + "EvaluationCell", + "EvaluationCompletionAction", + "EvaluationData", + "EvaluationElements", + "EvaluationEnvironment", + "EvaluationMode", + "EvaluationMonitor", + "EvaluationNotebook", + "EvaluationObject", + "EvaluationOrder", + "Evaluator", + "EvaluatorNames", + "EvenQ", + "EventData", + "EventEvaluator", + "EventHandler", + "EventHandlerTag", + "EventLabels", + "EventSeries", + "ExactBlackmanWindow", + "ExactNumberQ", + "ExactRootIsolation", + "ExampleData", + "Except", + "ExcludedForms", + "ExcludedLines", + "ExcludedPhysicalQuantities", + "ExcludePods", + "Exclusions", + "ExclusionsStyle", + "Exists", + "Exit", + "ExitDialog", + "ExoplanetData", + "Exp", + "Expand", + "ExpandAll", + "ExpandDenominator", + "ExpandFileName", + "ExpandNumerator", + "Expectation", + "ExpectationE", + "ExpectedValue", + "ExpGammaDistribution", + "ExpIntegralE", + "ExpIntegralEi", + "ExpirationDate", + "Exponent", + "ExponentFunction", + "ExponentialDistribution", + "ExponentialFamily", + "ExponentialGeneratingFunction", + "ExponentialMovingAverage", + "ExponentialPowerDistribution", + "ExponentPosition", + "ExponentStep", + "Export", + "ExportAutoReplacements", + "ExportByteArray", + "ExportForm", + "ExportPacket", + "ExportString", + "Expression", + "ExpressionCell", + "ExpressionGraph", + "ExpressionPacket", + "ExpressionUUID", + "ExpToTrig", + "ExtendedEntityClass", + "ExtendedGCD", + "Extension", + "ExtentElementFunction", + "ExtentMarkers", + "ExtentSize", + "ExternalBundle", + "ExternalCall", + "ExternalDataCharacterEncoding", + "ExternalEvaluate", + "ExternalFunction", + "ExternalFunctionName", + "ExternalIdentifier", + "ExternalObject", + "ExternalOptions", + "ExternalSessionObject", + "ExternalSessions", + "ExternalStorageBase", + "ExternalStorageDownload", + "ExternalStorageGet", + "ExternalStorageObject", + "ExternalStoragePut", + "ExternalStorageUpload", + "ExternalTypeSignature", + "ExternalValue", + "Extract", + "ExtractArchive", + "ExtractLayer", + "ExtractPacletArchive", + "ExtremeValueDistribution", + "FaceAlign", + "FaceForm", + "FaceGrids", + "FaceGridsStyle", + "FacialFeatures", + "Factor", + "FactorComplete", + "Factorial", + "Factorial2", + "FactorialMoment", + "FactorialMomentGeneratingFunction", + "FactorialPower", + "FactorInteger", + "FactorList", + "FactorSquareFree", + "FactorSquareFreeList", + "FactorTerms", + "FactorTermsList", + "Fail", + "Failure", + "FailureAction", + "FailureDistribution", + "FailureQ", + "False", + "FareySequence", + "FARIMAProcess", + "FeatureDistance", + "FeatureExtract", + "FeatureExtraction", + "FeatureExtractor", + "FeatureExtractorFunction", + "FeatureNames", + "FeatureNearest", + "FeatureSpacePlot", + "FeatureSpacePlot3D", + "FeatureTypes", + "FEDisableConsolePrintPacket", + "FeedbackLinearize", + "FeedbackSector", + "FeedbackSectorStyle", + "FeedbackType", + "FEEnableConsolePrintPacket", + "FetalGrowthData", + "Fibonacci", + "Fibonorial", + "FieldCompletionFunction", + "FieldHint", + "FieldHintStyle", + "FieldMasked", + "FieldSize", + "File", + "FileBaseName", + "FileByteCount", + "FileConvert", + "FileDate", + "FileExistsQ", + "FileExtension", + "FileFormat", + "FileHandler", + "FileHash", + "FileInformation", + "FileName", + "FileNameDepth", + "FileNameDialogSettings", + "FileNameDrop", + "FileNameForms", + "FileNameJoin", + "FileNames", + "FileNameSetter", + "FileNameSplit", + "FileNameTake", + "FilePrint", + "FileSize", + "FileSystemMap", + "FileSystemScan", + "FileTemplate", + "FileTemplateApply", + "FileType", + "FilledCurve", + "FilledCurveBox", + "FilledCurveBoxOptions", + "Filling", + "FillingStyle", + "FillingTransform", + "FilteredEntityClass", + "FilterRules", + "FinancialBond", + "FinancialData", + "FinancialDerivative", + "FinancialIndicator", + "Find", + "FindAnomalies", + "FindArgMax", + "FindArgMin", + "FindChannels", + "FindClique", + "FindClusters", + "FindCookies", + "FindCurvePath", + "FindCycle", + "FindDevices", + "FindDistribution", + "FindDistributionParameters", + "FindDivisions", + "FindEdgeCover", + "FindEdgeCut", + "FindEdgeIndependentPaths", + "FindEquationalProof", + "FindEulerianCycle", + "FindExternalEvaluators", + "FindFaces", + "FindFile", + "FindFit", + "FindFormula", + "FindFundamentalCycles", + "FindGeneratingFunction", + "FindGeoLocation", + "FindGeometricConjectures", + "FindGeometricTransform", + "FindGraphCommunities", + "FindGraphIsomorphism", + "FindGraphPartition", + "FindHamiltonianCycle", + "FindHamiltonianPath", + "FindHiddenMarkovStates", + "FindImageText", + "FindIndependentEdgeSet", + "FindIndependentVertexSet", + "FindInstance", + "FindIntegerNullVector", + "FindKClan", + "FindKClique", + "FindKClub", + "FindKPlex", + "FindLibrary", + "FindLinearRecurrence", + "FindList", + "FindMatchingColor", + "FindMaximum", + "FindMaximumCut", + "FindMaximumFlow", + "FindMaxValue", + "FindMeshDefects", + "FindMinimum", + "FindMinimumCostFlow", + "FindMinimumCut", + "FindMinValue", + "FindMoleculeSubstructure", + "FindPath", + "FindPeaks", + "FindPermutation", + "FindPostmanTour", + "FindProcessParameters", + "FindRepeat", + "FindRoot", + "FindSequenceFunction", + "FindSettings", + "FindShortestPath", + "FindShortestTour", + "FindSpanningTree", + "FindSystemModelEquilibrium", + "FindTextualAnswer", + "FindThreshold", + "FindTransientRepeat", + "FindVertexCover", + "FindVertexCut", + "FindVertexIndependentPaths", + "Fine", + "FinishDynamic", + "FiniteAbelianGroupCount", + "FiniteGroupCount", + "FiniteGroupData", + "First", + "FirstCase", + "FirstPassageTimeDistribution", + "FirstPosition", + "FischerGroupFi22", + "FischerGroupFi23", + "FischerGroupFi24Prime", + "FisherHypergeometricDistribution", + "FisherRatioTest", + "FisherZDistribution", + "Fit", + "FitAll", + "FitRegularization", + "FittedModel", + "FixedOrder", + "FixedPoint", + "FixedPointList", + "FlashSelection", + "Flat", + "Flatten", + "FlattenAt", + "FlattenLayer", + "FlatTopWindow", + "FlipView", + "Floor", + "FlowPolynomial", + "FlushPrintOutputPacket", + "Fold", + "FoldList", + "FoldPair", + "FoldPairList", + "FollowRedirects", + "Font", + "FontColor", + "FontFamily", + "FontForm", + "FontName", + "FontOpacity", + "FontPostScriptName", + "FontProperties", + "FontReencoding", + "FontSize", + "FontSlant", + "FontSubstitutions", + "FontTracking", + "FontVariations", + "FontWeight", + "For", + "ForAll", + "ForceVersionInstall", + "Format", + "FormatRules", + "FormatType", + "FormatTypeAutoConvert", + "FormatValues", + "FormBox", + "FormBoxOptions", + "FormControl", + "FormFunction", + "FormLayoutFunction", + "FormObject", + "FormPage", + "FormTheme", + "FormulaData", + "FormulaLookup", + "FortranForm", + "Forward", + "ForwardBackward", + "Fourier", + "FourierCoefficient", + "FourierCosCoefficient", + "FourierCosSeries", + "FourierCosTransform", + "FourierDCT", + "FourierDCTFilter", + "FourierDCTMatrix", + "FourierDST", + "FourierDSTMatrix", + "FourierMatrix", + "FourierParameters", + "FourierSequenceTransform", + "FourierSeries", + "FourierSinCoefficient", + "FourierSinSeries", + "FourierSinTransform", + "FourierTransform", + "FourierTrigSeries", + "FractionalBrownianMotionProcess", + "FractionalGaussianNoiseProcess", + "FractionalPart", + "FractionBox", + "FractionBoxOptions", + "FractionLine", + "Frame", + "FrameBox", + "FrameBoxOptions", + "Framed", + "FrameInset", + "FrameLabel", + "Frameless", + "FrameMargins", + "FrameRate", + "FrameStyle", + "FrameTicks", + "FrameTicksStyle", + "FRatioDistribution", + "FrechetDistribution", + "FreeQ", + "FrenetSerretSystem", + "FrequencySamplingFilterKernel", + "FresnelC", + "FresnelF", + "FresnelG", + "FresnelS", + "Friday", + "FrobeniusNumber", + "FrobeniusSolve", + "FromAbsoluteTime", + "FromCharacterCode", + "FromCoefficientRules", + "FromContinuedFraction", + "FromDate", + "FromDigits", + "FromDMS", + "FromEntity", + "FromJulianDate", + "FromLetterNumber", + "FromPolarCoordinates", + "FromRomanNumeral", + "FromSphericalCoordinates", + "FromUnixTime", + "Front", + "FrontEndDynamicExpression", + "FrontEndEventActions", + "FrontEndExecute", + "FrontEndObject", + "FrontEndResource", + "FrontEndResourceString", + "FrontEndStackSize", + "FrontEndToken", + "FrontEndTokenExecute", + "FrontEndValueCache", + "FrontEndVersion", + "FrontFaceColor", + "FrontFaceOpacity", + "Full", + "FullAxes", + "FullDefinition", + "FullForm", + "FullGraphics", + "FullInformationOutputRegulator", + "FullOptions", + "FullRegion", + "FullSimplify", + "Function", + "FunctionCompile", + "FunctionCompileExport", + "FunctionCompileExportByteArray", + "FunctionCompileExportLibrary", + "FunctionCompileExportString", + "FunctionDomain", + "FunctionExpand", + "FunctionInterpolation", + "FunctionPeriod", + "FunctionRange", + "FunctionSpace", + "FussellVeselyImportance", + "GaborFilter", + "GaborMatrix", + "GaborWavelet", + "GainMargins", + "GainPhaseMargins", + "GalaxyData", + "GalleryView", + "Gamma", + "GammaDistribution", + "GammaRegularized", + "GapPenalty", + "GARCHProcess", + "GatedRecurrentLayer", + "Gather", + "GatherBy", + "GaugeFaceElementFunction", + "GaugeFaceStyle", + "GaugeFrameElementFunction", + "GaugeFrameSize", + "GaugeFrameStyle", + "GaugeLabels", + "GaugeMarkers", + "GaugeStyle", + "GaussianFilter", + "GaussianIntegers", + "GaussianMatrix", + "GaussianOrthogonalMatrixDistribution", + "GaussianSymplecticMatrixDistribution", + "GaussianUnitaryMatrixDistribution", + "GaussianWindow", + "GCD", + "GegenbauerC", + "General", + "GeneralizedLinearModelFit", + "GenerateAsymmetricKeyPair", + "GenerateConditions", + "GeneratedCell", + "GeneratedDocumentBinding", + "GenerateDerivedKey", + "GenerateDigitalSignature", + "GenerateDocument", + "GeneratedParameters", + "GeneratedQuantityMagnitudes", + "GenerateFileSignature", + "GenerateHTTPResponse", + "GenerateSecuredAuthenticationKey", + "GenerateSymmetricKey", + "GeneratingFunction", + "GeneratorDescription", + "GeneratorHistoryLength", + "GeneratorOutputType", + "Generic", + "GenericCylindricalDecomposition", + "GenomeData", + "GenomeLookup", + "GeoAntipode", + "GeoArea", + "GeoArraySize", + "GeoBackground", + "GeoBoundingBox", + "GeoBounds", + "GeoBoundsRegion", + "GeoBubbleChart", + "GeoCenter", + "GeoCircle", + "GeoContourPlot", + "GeoDensityPlot", + "GeodesicClosing", + "GeodesicDilation", + "GeodesicErosion", + "GeodesicOpening", + "GeoDestination", + "GeodesyData", + "GeoDirection", + "GeoDisk", + "GeoDisplacement", + "GeoDistance", + "GeoDistanceList", + "GeoElevationData", + "GeoEntities", + "GeoGraphics", + "GeogravityModelData", + "GeoGridDirectionDifference", + "GeoGridLines", + "GeoGridLinesStyle", + "GeoGridPosition", + "GeoGridRange", + "GeoGridRangePadding", + "GeoGridUnitArea", + "GeoGridUnitDistance", + "GeoGridVector", + "GeoGroup", + "GeoHemisphere", + "GeoHemisphereBoundary", + "GeoHistogram", + "GeoIdentify", + "GeoImage", + "GeoLabels", + "GeoLength", + "GeoListPlot", + "GeoLocation", + "GeologicalPeriodData", + "GeomagneticModelData", + "GeoMarker", + "GeometricAssertion", + "GeometricBrownianMotionProcess", + "GeometricDistribution", + "GeometricMean", + "GeometricMeanFilter", + "GeometricOptimization", + "GeometricScene", + "GeometricTransformation", + "GeometricTransformation3DBox", + "GeometricTransformation3DBoxOptions", + "GeometricTransformationBox", + "GeometricTransformationBoxOptions", + "GeoModel", + "GeoNearest", + "GeoPath", + "GeoPosition", + "GeoPositionENU", + "GeoPositionXYZ", + "GeoProjection", + "GeoProjectionData", + "GeoRange", + "GeoRangePadding", + "GeoRegionValuePlot", + "GeoResolution", + "GeoScaleBar", + "GeoServer", + "GeoSmoothHistogram", + "GeoStreamPlot", + "GeoStyling", + "GeoStylingImageFunction", + "GeoVariant", + "GeoVector", + "GeoVectorENU", + "GeoVectorPlot", + "GeoVectorXYZ", + "GeoVisibleRegion", + "GeoVisibleRegionBoundary", + "GeoWithinQ", + "GeoZoomLevel", + "GestureHandler", + "GestureHandlerTag", + "Get", + "GetBoundingBoxSizePacket", + "GetContext", + "GetEnvironment", + "GetFileName", + "GetFrontEndOptionsDataPacket", + "GetLinebreakInformationPacket", + "GetMenusPacket", + "GetPageBreakInformationPacket", + "Glaisher", + "GlobalClusteringCoefficient", + "GlobalPreferences", + "GlobalSession", + "Glow", + "GoldenAngle", + "GoldenRatio", + "GompertzMakehamDistribution", + "GoochShading", + "GoodmanKruskalGamma", + "GoodmanKruskalGammaTest", + "Goto", + "Grad", + "Gradient", + "GradientFilter", + "GradientOrientationFilter", + "GrammarApply", + "GrammarRules", + "GrammarToken", + "Graph", + "Graph3D", + "GraphAssortativity", + "GraphAutomorphismGroup", + "GraphCenter", + "GraphComplement", + "GraphData", + "GraphDensity", + "GraphDiameter", + "GraphDifference", + "GraphDisjointUnion", + "GraphDistance", + "GraphDistanceMatrix", + "GraphElementData", + "GraphEmbedding", + "GraphHighlight", + "GraphHighlightStyle", + "GraphHub", + "Graphics", + "Graphics3D", + "Graphics3DBox", + "Graphics3DBoxOptions", + "GraphicsArray", + "GraphicsBaseline", + "GraphicsBox", + "GraphicsBoxOptions", + "GraphicsColor", + "GraphicsColumn", + "GraphicsComplex", + "GraphicsComplex3DBox", + "GraphicsComplex3DBoxOptions", + "GraphicsComplexBox", + "GraphicsComplexBoxOptions", + "GraphicsContents", + "GraphicsData", + "GraphicsGrid", + "GraphicsGridBox", + "GraphicsGroup", + "GraphicsGroup3DBox", + "GraphicsGroup3DBoxOptions", + "GraphicsGroupBox", + "GraphicsGroupBoxOptions", + "GraphicsGrouping", + "GraphicsHighlightColor", + "GraphicsRow", + "GraphicsSpacing", + "GraphicsStyle", + "GraphIntersection", + "GraphLayout", + "GraphLinkEfficiency", + "GraphPeriphery", + "GraphPlot", + "GraphPlot3D", + "GraphPower", + "GraphPropertyDistribution", + "GraphQ", + "GraphRadius", + "GraphReciprocity", + "GraphRoot", + "GraphStyle", + "GraphUnion", + "Gray", + "GrayLevel", + "Greater", + "GreaterEqual", + "GreaterEqualLess", + "GreaterEqualThan", + "GreaterFullEqual", + "GreaterGreater", + "GreaterLess", + "GreaterSlantEqual", + "GreaterThan", + "GreaterTilde", + "Green", + "GreenFunction", + "Grid", + "GridBaseline", + "GridBox", + "GridBoxAlignment", + "GridBoxBackground", + "GridBoxDividers", + "GridBoxFrame", + "GridBoxItemSize", + "GridBoxItemStyle", + "GridBoxOptions", + "GridBoxSpacings", + "GridCreationSettings", + "GridDefaultElement", + "GridElementStyleOptions", + "GridFrame", + "GridFrameMargins", + "GridGraph", + "GridLines", + "GridLinesStyle", + "GroebnerBasis", + "GroupActionBase", + "GroupBy", + "GroupCentralizer", + "GroupElementFromWord", + "GroupElementPosition", + "GroupElementQ", + "GroupElements", + "GroupElementToWord", + "GroupGenerators", + "Groupings", + "GroupMultiplicationTable", + "GroupOrbits", + "GroupOrder", + "GroupPageBreakWithin", + "GroupSetwiseStabilizer", + "GroupStabilizer", + "GroupStabilizerChain", + "GroupTogetherGrouping", + "GroupTogetherNestedGrouping", + "GrowCutComponents", + "Gudermannian", + "GuidedFilter", + "GumbelDistribution", + "HaarWavelet", + "HadamardMatrix", + "HalfLine", + "HalfNormalDistribution", + "HalfPlane", + "HalfSpace", + "HalftoneShading", + "HamiltonianGraphQ", + "HammingDistance", + "HammingWindow", + "HandlerFunctions", + "HandlerFunctionsKeys", + "HankelH1", + "HankelH2", + "HankelMatrix", + "HankelTransform", + "HannPoissonWindow", + "HannWindow", + "HaradaNortonGroupHN", + "HararyGraph", + "HarmonicMean", + "HarmonicMeanFilter", + "HarmonicNumber", + "Hash", + "HatchFilling", + "HatchShading", + "Haversine", + "HazardFunction", + "Head", + "HeadCompose", + "HeaderAlignment", + "HeaderBackground", + "HeaderDisplayFunction", + "HeaderLines", + "HeaderSize", + "HeaderStyle", + "Heads", + "HeavisideLambda", + "HeavisidePi", + "HeavisideTheta", + "HeldGroupHe", + "HeldPart", + "HelpBrowserLookup", + "HelpBrowserNotebook", + "HelpBrowserSettings", + "Here", + "HermiteDecomposition", + "HermiteH", + "HermitianMatrixQ", + "HessenbergDecomposition", + "Hessian", + "HeunB", + "HeunBPrime", + "HeunC", + "HeunCPrime", + "HeunD", + "HeunDPrime", + "HeunG", + "HeunGPrime", + "HeunT", + "HeunTPrime", + "HexadecimalCharacter", + "Hexahedron", + "HexahedronBox", + "HexahedronBoxOptions", + "HiddenItems", + "HiddenMarkovProcess", + "HiddenSurface", + "Highlighted", + "HighlightGraph", + "HighlightImage", + "HighlightMesh", + "HighpassFilter", + "HigmanSimsGroupHS", + "HilbertCurve", + "HilbertFilter", + "HilbertMatrix", + "Histogram", + "Histogram3D", + "HistogramDistribution", + "HistogramList", + "HistogramTransform", + "HistogramTransformInterpolation", + "HistoricalPeriodData", + "HitMissTransform", + "HITSCentrality", + "HjorthDistribution", + "HodgeDual", + "HoeffdingD", + "HoeffdingDTest", + "Hold", + "HoldAll", + "HoldAllComplete", + "HoldComplete", + "HoldFirst", + "HoldForm", + "HoldPattern", + "HoldRest", + "HolidayCalendar", + "HomeDirectory", + "HomePage", + "Horizontal", + "HorizontalForm", + "HorizontalGauge", + "HorizontalScrollPosition", + "HornerForm", + "HostLookup", + "HotellingTSquareDistribution", + "HoytDistribution", + "HTMLSave", + "HTTPErrorResponse", + "HTTPRedirect", + "HTTPRequest", + "HTTPRequestData", + "HTTPResponse", + "Hue", + "HumanGrowthData", + "HumpDownHump", + "HumpEqual", + "HurwitzLerchPhi", + "HurwitzZeta", + "HyperbolicDistribution", + "HypercubeGraph", + "HyperexponentialDistribution", + "Hyperfactorial", + "Hypergeometric0F1", + "Hypergeometric0F1Regularized", + "Hypergeometric1F1", + "Hypergeometric1F1Regularized", + "Hypergeometric2F1", + "Hypergeometric2F1Regularized", + "HypergeometricDistribution", + "HypergeometricPFQ", + "HypergeometricPFQRegularized", + "HypergeometricU", + "Hyperlink", + "HyperlinkAction", + "HyperlinkCreationSettings", + "Hyperplane", + "Hyphenation", + "HyphenationOptions", + "HypoexponentialDistribution", + "HypothesisTestData", + "I", + "IconData", + "Iconize", + "IconizedObject", + "IconRules", + "Icosahedron", + "Identity", + "IdentityMatrix", + "If", + "IgnoreCase", + "IgnoreDiacritics", + "IgnorePunctuation", + "IgnoreSpellCheck", + "IgnoringInactive", + "Im", + "Image", + "Image3D", + "Image3DProjection", + "Image3DSlices", + "ImageAccumulate", + "ImageAdd", + "ImageAdjust", + "ImageAlign", + "ImageApply", + "ImageApplyIndexed", + "ImageAspectRatio", + "ImageAssemble", + "ImageAugmentationLayer", + "ImageBoundingBoxes", + "ImageCache", + "ImageCacheValid", + "ImageCapture", + "ImageCaptureFunction", + "ImageCases", + "ImageChannels", + "ImageClip", + "ImageCollage", + "ImageColorSpace", + "ImageCompose", + "ImageContainsQ", + "ImageContents", + "ImageConvolve", + "ImageCooccurrence", + "ImageCorners", + "ImageCorrelate", + "ImageCorrespondingPoints", + "ImageCrop", + "ImageData", + "ImageDeconvolve", + "ImageDemosaic", + "ImageDifference", + "ImageDimensions", + "ImageDisplacements", + "ImageDistance", + "ImageEffect", + "ImageExposureCombine", + "ImageFeatureTrack", + "ImageFileApply", + "ImageFileFilter", + "ImageFileScan", + "ImageFilter", + "ImageFocusCombine", + "ImageForestingComponents", + "ImageFormattingWidth", + "ImageForwardTransformation", + "ImageGraphics", + "ImageHistogram", + "ImageIdentify", + "ImageInstanceQ", + "ImageKeypoints", + "ImageLabels", + "ImageLegends", + "ImageLevels", + "ImageLines", + "ImageMargins", + "ImageMarker", + "ImageMarkers", + "ImageMeasurements", + "ImageMesh", + "ImageMultiply", + "ImageOffset", + "ImagePad", + "ImagePadding", + "ImagePartition", + "ImagePeriodogram", + "ImagePerspectiveTransformation", + "ImagePosition", + "ImagePreviewFunction", + "ImagePyramid", + "ImagePyramidApply", + "ImageQ", + "ImageRangeCache", + "ImageRecolor", + "ImageReflect", + "ImageRegion", + "ImageResize", + "ImageResolution", + "ImageRestyle", + "ImageRotate", + "ImageRotated", + "ImageSaliencyFilter", + "ImageScaled", + "ImageScan", + "ImageSize", + "ImageSizeAction", + "ImageSizeCache", + "ImageSizeMultipliers", + "ImageSizeRaw", + "ImageSubtract", + "ImageTake", + "ImageTransformation", + "ImageTrim", + "ImageType", + "ImageValue", + "ImageValuePositions", + "ImagingDevice", + "ImplicitRegion", + "Implies", + "Import", + "ImportAutoReplacements", + "ImportByteArray", + "ImportOptions", + "ImportString", + "ImprovementImportance", + "In", + "Inactivate", + "Inactive", + "IncidenceGraph", + "IncidenceList", + "IncidenceMatrix", + "IncludeAromaticBonds", + "IncludeConstantBasis", + "IncludeDefinitions", + "IncludeDirectories", + "IncludeFileExtension", + "IncludeGeneratorTasks", + "IncludeHydrogens", + "IncludeInflections", + "IncludeMetaInformation", + "IncludePods", + "IncludeQuantities", + "IncludeRelatedTables", + "IncludeSingularTerm", + "IncludeWindowTimes", + "Increment", + "IndefiniteMatrixQ", + "Indent", + "IndentingNewlineSpacings", + "IndentMaxFraction", + "IndependenceTest", + "IndependentEdgeSetQ", + "IndependentPhysicalQuantity", + "IndependentUnit", + "IndependentUnitDimension", + "IndependentVertexSetQ", + "Indeterminate", + "IndeterminateThreshold", + "IndexCreationOptions", + "Indexed", + "IndexEdgeTaggedGraph", + "IndexGraph", + "IndexTag", + "Inequality", + "InexactNumberQ", + "InexactNumbers", + "InfiniteFuture", + "InfiniteLine", + "InfinitePast", + "InfinitePlane", + "Infinity", + "Infix", + "InflationAdjust", + "InflationMethod", + "Information", + "InformationData", + "InformationDataGrid", + "Inherited", + "InheritScope", + "InhomogeneousPoissonProcess", + "InitialEvaluationHistory", + "Initialization", + "InitializationCell", + "InitializationCellEvaluation", + "InitializationCellWarning", + "InitializationObjects", + "InitializationValue", + "Initialize", + "InitialSeeding", + "InlineCounterAssignments", + "InlineCounterIncrements", + "InlineRules", + "Inner", + "InnerPolygon", + "InnerPolyhedron", + "Inpaint", + "Input", + "InputAliases", + "InputAssumptions", + "InputAutoReplacements", + "InputField", + "InputFieldBox", + "InputFieldBoxOptions", + "InputForm", + "InputGrouping", + "InputNamePacket", + "InputNotebook", + "InputPacket", + "InputSettings", + "InputStream", + "InputString", + "InputStringPacket", + "InputToBoxFormPacket", + "Insert", + "InsertionFunction", + "InsertionPointObject", + "InsertLinebreaks", + "InsertResults", + "Inset", + "Inset3DBox", + "Inset3DBoxOptions", + "InsetBox", + "InsetBoxOptions", + "Insphere", + "Install", + "InstallService", + "InstanceNormalizationLayer", + "InString", + "Integer", + "IntegerDigits", + "IntegerExponent", + "IntegerLength", + "IntegerName", + "IntegerPart", + "IntegerPartitions", + "IntegerQ", + "IntegerReverse", + "Integers", + "IntegerString", + "Integral", + "Integrate", + "Interactive", + "InteractiveTradingChart", + "Interlaced", + "Interleaving", + "InternallyBalancedDecomposition", + "InterpolatingFunction", + "InterpolatingPolynomial", + "Interpolation", + "InterpolationOrder", + "InterpolationPoints", + "InterpolationPrecision", + "Interpretation", + "InterpretationBox", + "InterpretationBoxOptions", + "InterpretationFunction", + "Interpreter", + "InterpretTemplate", + "InterquartileRange", + "Interrupt", + "InterruptSettings", + "IntersectedEntityClass", + "IntersectingQ", + "Intersection", + "Interval", + "IntervalIntersection", + "IntervalMarkers", + "IntervalMarkersStyle", + "IntervalMemberQ", + "IntervalSlider", + "IntervalUnion", + "Into", + "Inverse", + "InverseBetaRegularized", + "InverseCDF", + "InverseChiSquareDistribution", + "InverseContinuousWaveletTransform", + "InverseDistanceTransform", + "InverseEllipticNomeQ", + "InverseErf", + "InverseErfc", + "InverseFourier", + "InverseFourierCosTransform", + "InverseFourierSequenceTransform", + "InverseFourierSinTransform", + "InverseFourierTransform", + "InverseFunction", + "InverseFunctions", + "InverseGammaDistribution", + "InverseGammaRegularized", + "InverseGaussianDistribution", + "InverseGudermannian", + "InverseHankelTransform", + "InverseHaversine", + "InverseImagePyramid", + "InverseJacobiCD", + "InverseJacobiCN", + "InverseJacobiCS", + "InverseJacobiDC", + "InverseJacobiDN", + "InverseJacobiDS", + "InverseJacobiNC", + "InverseJacobiND", + "InverseJacobiNS", + "InverseJacobiSC", + "InverseJacobiSD", + "InverseJacobiSN", + "InverseLaplaceTransform", + "InverseMellinTransform", + "InversePermutation", + "InverseRadon", + "InverseRadonTransform", + "InverseSeries", + "InverseShortTimeFourier", + "InverseSpectrogram", + "InverseSurvivalFunction", + "InverseTransformedRegion", + "InverseWaveletTransform", + "InverseWeierstrassP", + "InverseWishartMatrixDistribution", + "InverseZTransform", + "Invisible", + "InvisibleApplication", + "InvisibleTimes", + "IPAddress", + "IrreduciblePolynomialQ", + "IslandData", + "IsolatingInterval", + "IsomorphicGraphQ", + "IsotopeData", + "Italic", + "Item", + "ItemAspectRatio", + "ItemBox", + "ItemBoxOptions", + "ItemDisplayFunction", + "ItemSize", + "ItemStyle", + "ItoProcess", + "JaccardDissimilarity", + "JacobiAmplitude", + "Jacobian", + "JacobiCD", + "JacobiCN", + "JacobiCS", + "JacobiDC", + "JacobiDN", + "JacobiDS", + "JacobiNC", + "JacobiND", + "JacobiNS", + "JacobiP", + "JacobiSC", + "JacobiSD", + "JacobiSN", + "JacobiSymbol", + "JacobiZeta", + "JankoGroupJ1", + "JankoGroupJ2", + "JankoGroupJ3", + "JankoGroupJ4", + "JarqueBeraALMTest", + "JohnsonDistribution", + "Join", + "JoinAcross", + "Joined", + "JoinedCurve", + "JoinedCurveBox", + "JoinedCurveBoxOptions", + "JoinForm", + "JordanDecomposition", + "JordanModelDecomposition", + "JulianDate", + "JuliaSetBoettcher", + "JuliaSetIterationCount", + "JuliaSetPlot", + "JuliaSetPoints", + "K", + "KagiChart", + "KaiserBesselWindow", + "KaiserWindow", + "KalmanEstimator", + "KalmanFilter", + "KarhunenLoeveDecomposition", + "KaryTree", + "KatzCentrality", + "KCoreComponents", + "KDistribution", + "KEdgeConnectedComponents", + "KEdgeConnectedGraphQ", + "KeepExistingVersion", + "KelvinBei", + "KelvinBer", + "KelvinKei", + "KelvinKer", + "KendallTau", + "KendallTauTest", + "KernelExecute", + "KernelFunction", + "KernelMixtureDistribution", + "KernelObject", + "Kernels", + "Ket", + "Key", + "KeyCollisionFunction", + "KeyComplement", + "KeyDrop", + "KeyDropFrom", + "KeyExistsQ", + "KeyFreeQ", + "KeyIntersection", + "KeyMap", + "KeyMemberQ", + "KeypointStrength", + "Keys", + "KeySelect", + "KeySort", + "KeySortBy", + "KeyTake", + "KeyUnion", + "KeyValueMap", + "KeyValuePattern", + "Khinchin", + "KillProcess", + "KirchhoffGraph", + "KirchhoffMatrix", + "KleinInvariantJ", + "KnapsackSolve", + "KnightTourGraph", + "KnotData", + "KnownUnitQ", + "KochCurve", + "KolmogorovSmirnovTest", + "KroneckerDelta", + "KroneckerModelDecomposition", + "KroneckerProduct", + "KroneckerSymbol", + "KuiperTest", + "KumaraswamyDistribution", + "Kurtosis", + "KuwaharaFilter", + "KVertexConnectedComponents", + "KVertexConnectedGraphQ", + "LABColor", + "Label", + "Labeled", + "LabeledSlider", + "LabelingFunction", + "LabelingSize", + "LabelStyle", + "LabelVisibility", + "LaguerreL", + "LakeData", + "LambdaComponents", + "LambertW", + "LaminaData", + "LanczosWindow", + "LandauDistribution", + "Language", + "LanguageCategory", + "LanguageData", + "LanguageIdentify", + "LanguageOptions", + "LaplaceDistribution", + "LaplaceTransform", + "Laplacian", + "LaplacianFilter", + "LaplacianGaussianFilter", + "Large", + "Larger", + "Last", + "Latitude", + "LatitudeLongitude", + "LatticeData", + "LatticeReduce", + "Launch", + "LaunchKernels", + "LayeredGraphPlot", + "LayerSizeFunction", + "LayoutInformation", + "LCHColor", + "LCM", + "LeaderSize", + "LeafCount", + "LeapYearQ", + "LearnDistribution", + "LearnedDistribution", + "LearningRate", + "LearningRateMultipliers", + "LeastSquares", + "LeastSquaresFilterKernel", + "Left", + "LeftArrow", + "LeftArrowBar", + "LeftArrowRightArrow", + "LeftDownTeeVector", + "LeftDownVector", + "LeftDownVectorBar", + "LeftRightArrow", + "LeftRightVector", + "LeftTee", + "LeftTeeArrow", + "LeftTeeVector", + "LeftTriangle", + "LeftTriangleBar", + "LeftTriangleEqual", + "LeftUpDownVector", + "LeftUpTeeVector", + "LeftUpVector", + "LeftUpVectorBar", + "LeftVector", + "LeftVectorBar", + "LegendAppearance", + "Legended", + "LegendFunction", + "LegendLabel", + "LegendLayout", + "LegendMargins", + "LegendMarkers", + "LegendMarkerSize", + "LegendreP", + "LegendreQ", + "LegendreType", + "Length", + "LengthWhile", + "LerchPhi", + "Less", + "LessEqual", + "LessEqualGreater", + "LessEqualThan", + "LessFullEqual", + "LessGreater", + "LessLess", + "LessSlantEqual", + "LessThan", + "LessTilde", + "LetterCharacter", + "LetterCounts", + "LetterNumber", + "LetterQ", + "Level", + "LeveneTest", + "LeviCivitaTensor", + "LevyDistribution", + "Lexicographic", + "LibraryDataType", + "LibraryFunction", + "LibraryFunctionError", + "LibraryFunctionInformation", + "LibraryFunctionLoad", + "LibraryFunctionUnload", + "LibraryLoad", + "LibraryUnload", + "LicenseID", + "LiftingFilterData", + "LiftingWaveletTransform", + "LightBlue", + "LightBrown", + "LightCyan", + "Lighter", + "LightGray", + "LightGreen", + "Lighting", + "LightingAngle", + "LightMagenta", + "LightOrange", + "LightPink", + "LightPurple", + "LightRed", + "LightSources", + "LightYellow", + "Likelihood", + "Limit", + "LimitsPositioning", + "LimitsPositioningTokens", + "LindleyDistribution", + "Line", + "Line3DBox", + "Line3DBoxOptions", + "LinearFilter", + "LinearFractionalOptimization", + "LinearFractionalTransform", + "LinearGradientImage", + "LinearizingTransformationData", + "LinearLayer", + "LinearModelFit", + "LinearOffsetFunction", + "LinearOptimization", + "LinearProgramming", + "LinearRecurrence", + "LinearSolve", + "LinearSolveFunction", + "LineBox", + "LineBoxOptions", + "LineBreak", + "LinebreakAdjustments", + "LineBreakChart", + "LinebreakSemicolonWeighting", + "LineBreakWithin", + "LineColor", + "LineGraph", + "LineIndent", + "LineIndentMaxFraction", + "LineIntegralConvolutionPlot", + "LineIntegralConvolutionScale", + "LineLegend", + "LineOpacity", + "LineSpacing", + "LineWrapParts", + "LinkActivate", + "LinkClose", + "LinkConnect", + "LinkConnectedQ", + "LinkCreate", + "LinkError", + "LinkFlush", + "LinkFunction", + "LinkHost", + "LinkInterrupt", + "LinkLaunch", + "LinkMode", + "LinkObject", + "LinkOpen", + "LinkOptions", + "LinkPatterns", + "LinkProtocol", + "LinkRankCentrality", + "LinkRead", + "LinkReadHeld", + "LinkReadyQ", + "Links", + "LinkService", + "LinkWrite", + "LinkWriteHeld", + "LiouvilleLambda", + "List", + "Listable", + "ListAnimate", + "ListContourPlot", + "ListContourPlot3D", + "ListConvolve", + "ListCorrelate", + "ListCurvePathPlot", + "ListDeconvolve", + "ListDensityPlot", + "ListDensityPlot3D", + "Listen", + "ListFormat", + "ListFourierSequenceTransform", + "ListInterpolation", + "ListLineIntegralConvolutionPlot", + "ListLinePlot", + "ListLogLinearPlot", + "ListLogLogPlot", + "ListLogPlot", + "ListPicker", + "ListPickerBox", + "ListPickerBoxBackground", + "ListPickerBoxOptions", + "ListPlay", + "ListPlot", + "ListPlot3D", + "ListPointPlot3D", + "ListPolarPlot", + "ListQ", + "ListSliceContourPlot3D", + "ListSliceDensityPlot3D", + "ListSliceVectorPlot3D", + "ListStepPlot", + "ListStreamDensityPlot", + "ListStreamPlot", + "ListSurfacePlot3D", + "ListVectorDensityPlot", + "ListVectorPlot", + "ListVectorPlot3D", + "ListZTransform", + "Literal", + "LiteralSearch", + "LocalAdaptiveBinarize", + "LocalCache", + "LocalClusteringCoefficient", + "LocalizeDefinitions", + "LocalizeVariables", + "LocalObject", + "LocalObjects", + "LocalResponseNormalizationLayer", + "LocalSubmit", + "LocalSymbol", + "LocalTime", + "LocalTimeZone", + "LocationEquivalenceTest", + "LocationTest", + "Locator", + "LocatorAutoCreate", + "LocatorBox", + "LocatorBoxOptions", + "LocatorCentering", + "LocatorPane", + "LocatorPaneBox", + "LocatorPaneBoxOptions", + "LocatorRegion", + "Locked", + "Log", + "Log10", + "Log2", + "LogBarnesG", + "LogGamma", + "LogGammaDistribution", + "LogicalExpand", + "LogIntegral", + "LogisticDistribution", + "LogisticSigmoid", + "LogitModelFit", + "LogLikelihood", + "LogLinearPlot", + "LogLogisticDistribution", + "LogLogPlot", + "LogMultinormalDistribution", + "LogNormalDistribution", + "LogPlot", + "LogRankTest", + "LogSeriesDistribution", + "LongEqual", + "Longest", + "LongestCommonSequence", + "LongestCommonSequencePositions", + "LongestCommonSubsequence", + "LongestCommonSubsequencePositions", + "LongestMatch", + "LongestOrderedSequence", + "LongForm", + "Longitude", + "LongLeftArrow", + "LongLeftRightArrow", + "LongRightArrow", + "LongShortTermMemoryLayer", + "Lookup", + "Loopback", + "LoopFreeGraphQ", + "Looping", + "LossFunction", + "LowerCaseQ", + "LowerLeftArrow", + "LowerRightArrow", + "LowerTriangularize", + "LowerTriangularMatrixQ", + "LowpassFilter", + "LQEstimatorGains", + "LQGRegulator", + "LQOutputRegulatorGains", + "LQRegulatorGains", + "LUBackSubstitution", + "LucasL", + "LuccioSamiComponents", + "LUDecomposition", + "LunarEclipse", + "LUVColor", + "LyapunovSolve", + "LyonsGroupLy", + "MachineID", + "MachineName", + "MachineNumberQ", + "MachinePrecision", + "MacintoshSystemPageSetup", + "Magenta", + "Magnification", + "Magnify", + "MailAddressValidation", + "MailExecute", + "MailFolder", + "MailItem", + "MailReceiverFunction", + "MailResponseFunction", + "MailSearch", + "MailServerConnect", + "MailServerConnection", + "MailSettings", + "MainSolve", + "MaintainDynamicCaches", + "Majority", + "MakeBoxes", + "MakeExpression", + "MakeRules", + "ManagedLibraryExpressionID", + "ManagedLibraryExpressionQ", + "MandelbrotSetBoettcher", + "MandelbrotSetDistance", + "MandelbrotSetIterationCount", + "MandelbrotSetMemberQ", + "MandelbrotSetPlot", + "MangoldtLambda", + "ManhattanDistance", + "Manipulate", + "Manipulator", + "MannedSpaceMissionData", + "MannWhitneyTest", + "MantissaExponent", + "Manual", + "Map", + "MapAll", + "MapAt", + "MapIndexed", + "MAProcess", + "MapThread", + "MarchenkoPasturDistribution", + "MarcumQ", + "MardiaCombinedTest", + "MardiaKurtosisTest", + "MardiaSkewnessTest", + "MarginalDistribution", + "MarkovProcessProperties", + "Masking", + "MatchingDissimilarity", + "MatchLocalNameQ", + "MatchLocalNames", + "MatchQ", + "Material", + "MathematicalFunctionData", + "MathematicaNotation", + "MathieuC", + "MathieuCharacteristicA", + "MathieuCharacteristicB", + "MathieuCharacteristicExponent", + "MathieuCPrime", + "MathieuGroupM11", + "MathieuGroupM12", + "MathieuGroupM22", + "MathieuGroupM23", + "MathieuGroupM24", + "MathieuS", + "MathieuSPrime", + "MathMLForm", + "MathMLText", + "Matrices", + "MatrixExp", + "MatrixForm", + "MatrixFunction", + "MatrixLog", + "MatrixNormalDistribution", + "MatrixPlot", + "MatrixPower", + "MatrixPropertyDistribution", + "MatrixQ", + "MatrixRank", + "MatrixTDistribution", + "Max", + "MaxBend", + "MaxCellMeasure", + "MaxColorDistance", + "MaxDate", + "MaxDetect", + "MaxDuration", + "MaxExtraBandwidths", + "MaxExtraConditions", + "MaxFeatureDisplacement", + "MaxFeatures", + "MaxFilter", + "MaximalBy", + "Maximize", + "MaxItems", + "MaxIterations", + "MaxLimit", + "MaxMemoryUsed", + "MaxMixtureKernels", + "MaxOverlapFraction", + "MaxPlotPoints", + "MaxPoints", + "MaxRecursion", + "MaxStableDistribution", + "MaxStepFraction", + "MaxSteps", + "MaxStepSize", + "MaxTrainingRounds", + "MaxValue", + "MaxwellDistribution", + "MaxWordGap", + "McLaughlinGroupMcL", + "Mean", + "MeanAbsoluteLossLayer", + "MeanAround", + "MeanClusteringCoefficient", + "MeanDegreeConnectivity", + "MeanDeviation", + "MeanFilter", + "MeanGraphDistance", + "MeanNeighborDegree", + "MeanShift", + "MeanShiftFilter", + "MeanSquaredLossLayer", + "Median", + "MedianDeviation", + "MedianFilter", + "MedicalTestData", + "Medium", + "MeijerG", + "MeijerGReduce", + "MeixnerDistribution", + "MellinConvolve", + "MellinTransform", + "MemberQ", + "MemoryAvailable", + "MemoryConstrained", + "MemoryConstraint", + "MemoryInUse", + "MengerMesh", + "Menu", + "MenuAppearance", + "MenuCommandKey", + "MenuEvaluator", + "MenuItem", + "MenuList", + "MenuPacket", + "MenuSortingValue", + "MenuStyle", + "MenuView", + "Merge", + "MergeDifferences", + "MergingFunction", + "MersennePrimeExponent", + "MersennePrimeExponentQ", + "Mesh", + "MeshCellCentroid", + "MeshCellCount", + "MeshCellHighlight", + "MeshCellIndex", + "MeshCellLabel", + "MeshCellMarker", + "MeshCellMeasure", + "MeshCellQuality", + "MeshCells", + "MeshCellShapeFunction", + "MeshCellStyle", + "MeshConnectivityGraph", + "MeshCoordinates", + "MeshFunctions", + "MeshPrimitives", + "MeshQualityGoal", + "MeshRange", + "MeshRefinementFunction", + "MeshRegion", + "MeshRegionQ", + "MeshShading", + "MeshStyle", + "Message", + "MessageDialog", + "MessageList", + "MessageName", + "MessageObject", + "MessageOptions", + "MessagePacket", + "Messages", + "MessagesNotebook", + "MetaCharacters", + "MetaInformation", + "MeteorShowerData", + "Method", + "MethodOptions", + "MexicanHatWavelet", + "MeyerWavelet", + "Midpoint", + "Min", + "MinColorDistance", + "MinDate", + "MinDetect", + "MineralData", + "MinFilter", + "MinimalBy", + "MinimalPolynomial", + "MinimalStateSpaceModel", + "Minimize", + "MinimumTimeIncrement", + "MinIntervalSize", + "MinkowskiQuestionMark", + "MinLimit", + "MinMax", + "MinorPlanetData", + "Minors", + "MinRecursion", + "MinSize", + "MinStableDistribution", + "Minus", + "MinusPlus", + "MinValue", + "Missing", + "MissingBehavior", + "MissingDataMethod", + "MissingDataRules", + "MissingQ", + "MissingString", + "MissingStyle", + "MissingValuePattern", + "MittagLefflerE", + "MixedFractionParts", + "MixedGraphQ", + "MixedMagnitude", + "MixedRadix", + "MixedRadixQuantity", + "MixedUnit", + "MixtureDistribution", + "Mod", + "Modal", + "Mode", + "Modular", + "ModularInverse", + "ModularLambda", + "Module", + "Modulus", + "MoebiusMu", + "Molecule", + "MoleculeContainsQ", + "MoleculeEquivalentQ", + "MoleculeGraph", + "MoleculeModify", + "MoleculePattern", + "MoleculePlot", + "MoleculePlot3D", + "MoleculeProperty", + "MoleculeQ", + "MoleculeRecognize", + "MoleculeValue", + "Moment", + "Momentary", + "MomentConvert", + "MomentEvaluate", + "MomentGeneratingFunction", + "MomentOfInertia", + "Monday", + "Monitor", + "MonomialList", + "MonomialOrder", + "MonsterGroupM", + "MoonPhase", + "MoonPosition", + "MorletWavelet", + "MorphologicalBinarize", + "MorphologicalBranchPoints", + "MorphologicalComponents", + "MorphologicalEulerNumber", + "MorphologicalGraph", + "MorphologicalPerimeter", + "MorphologicalTransform", + "MortalityData", + "Most", + "MountainData", + "MouseAnnotation", + "MouseAppearance", + "MouseAppearanceTag", + "MouseButtons", + "Mouseover", + "MousePointerNote", + "MousePosition", + "MovieData", + "MovingAverage", + "MovingMap", + "MovingMedian", + "MoyalDistribution", + "Multicolumn", + "MultiedgeStyle", + "MultigraphQ", + "MultilaunchWarning", + "MultiLetterItalics", + "MultiLetterStyle", + "MultilineFunction", + "Multinomial", + "MultinomialDistribution", + "MultinormalDistribution", + "MultiplicativeOrder", + "Multiplicity", + "MultiplySides", + "Multiselection", + "MultivariateHypergeometricDistribution", + "MultivariatePoissonDistribution", + "MultivariateTDistribution", + "N", + "NakagamiDistribution", + "NameQ", + "Names", + "NamespaceBox", + "NamespaceBoxOptions", + "Nand", + "NArgMax", + "NArgMin", + "NBernoulliB", + "NBodySimulation", + "NBodySimulationData", + "NCache", + "NDEigensystem", + "NDEigenvalues", + "NDSolve", + "NDSolveValue", + "Nearest", + "NearestFunction", + "NearestMeshCells", + "NearestNeighborGraph", + "NearestTo", + "NebulaData", + "NeedCurrentFrontEndPackagePacket", + "NeedCurrentFrontEndSymbolsPacket", + "NeedlemanWunschSimilarity", + "Needs", + "Negative", + "NegativeBinomialDistribution", + "NegativeDefiniteMatrixQ", + "NegativeIntegers", + "NegativeMultinomialDistribution", + "NegativeRationals", + "NegativeReals", + "NegativeSemidefiniteMatrixQ", + "NeighborhoodData", + "NeighborhoodGraph", + "Nest", + "NestedGreaterGreater", + "NestedLessLess", + "NestedScriptRules", + "NestGraph", + "NestList", + "NestWhile", + "NestWhileList", + "NetAppend", + "NetBidirectionalOperator", + "NetChain", + "NetDecoder", + "NetDelete", + "NetDrop", + "NetEncoder", + "NetEvaluationMode", + "NetExtract", + "NetFlatten", + "NetFoldOperator", + "NetGANOperator", + "NetGraph", + "NetInformation", + "NetInitialize", + "NetInsert", + "NetInsertSharedArrays", + "NetJoin", + "NetMapOperator", + "NetMapThreadOperator", + "NetMeasurements", + "NetModel", + "NetNestOperator", + "NetPairEmbeddingOperator", + "NetPort", + "NetPortGradient", + "NetPrepend", + "NetRename", + "NetReplace", + "NetReplacePart", + "NetSharedArray", + "NetStateObject", + "NetTake", + "NetTrain", + "NetTrainResultsObject", + "NetworkPacketCapture", + "NetworkPacketRecording", + "NetworkPacketRecordingDuring", + "NetworkPacketTrace", + "NeumannValue", + "NevilleThetaC", + "NevilleThetaD", + "NevilleThetaN", + "NevilleThetaS", + "NewPrimitiveStyle", + "NExpectation", + "Next", + "NextCell", + "NextDate", + "NextPrime", + "NextScheduledTaskTime", + "NHoldAll", + "NHoldFirst", + "NHoldRest", + "NicholsGridLines", + "NicholsPlot", + "NightHemisphere", + "NIntegrate", + "NMaximize", + "NMaxValue", + "NMinimize", + "NMinValue", + "NominalVariables", + "NonAssociative", + "NoncentralBetaDistribution", + "NoncentralChiSquareDistribution", + "NoncentralFRatioDistribution", + "NoncentralStudentTDistribution", + "NonCommutativeMultiply", + "NonConstants", + "NondimensionalizationTransform", + "None", + "NoneTrue", + "NonlinearModelFit", + "NonlinearStateSpaceModel", + "NonlocalMeansFilter", + "NonNegative", + "NonNegativeIntegers", + "NonNegativeRationals", + "NonNegativeReals", + "NonPositive", + "NonPositiveIntegers", + "NonPositiveRationals", + "NonPositiveReals", + "Nor", + "NorlundB", + "Norm", + "Normal", + "NormalDistribution", + "NormalGrouping", + "NormalizationLayer", + "Normalize", + "Normalized", + "NormalizedSquaredEuclideanDistance", + "NormalMatrixQ", + "NormalsFunction", + "NormFunction", + "Not", + "NotCongruent", + "NotCupCap", + "NotDoubleVerticalBar", + "Notebook", + "NotebookApply", + "NotebookAutoSave", + "NotebookClose", + "NotebookConvertSettings", + "NotebookCreate", + "NotebookCreateReturnObject", + "NotebookDefault", + "NotebookDelete", + "NotebookDirectory", + "NotebookDynamicExpression", + "NotebookEvaluate", + "NotebookEventActions", + "NotebookFileName", + "NotebookFind", + "NotebookFindReturnObject", + "NotebookGet", + "NotebookGetLayoutInformationPacket", + "NotebookGetMisspellingsPacket", + "NotebookImport", + "NotebookInformation", + "NotebookInterfaceObject", + "NotebookLocate", + "NotebookObject", + "NotebookOpen", + "NotebookOpenReturnObject", + "NotebookPath", + "NotebookPrint", + "NotebookPut", + "NotebookPutReturnObject", + "NotebookRead", + "NotebookResetGeneratedCells", + "Notebooks", + "NotebookSave", + "NotebookSaveAs", + "NotebookSelection", + "NotebookSetupLayoutInformationPacket", + "NotebooksMenu", + "NotebookTemplate", + "NotebookWrite", + "NotElement", + "NotEqualTilde", + "NotExists", + "NotGreater", + "NotGreaterEqual", + "NotGreaterFullEqual", + "NotGreaterGreater", + "NotGreaterLess", + "NotGreaterSlantEqual", + "NotGreaterTilde", + "Nothing", + "NotHumpDownHump", + "NotHumpEqual", + "NotificationFunction", + "NotLeftTriangle", + "NotLeftTriangleBar", + "NotLeftTriangleEqual", + "NotLess", + "NotLessEqual", + "NotLessFullEqual", + "NotLessGreater", + "NotLessLess", + "NotLessSlantEqual", + "NotLessTilde", + "NotNestedGreaterGreater", + "NotNestedLessLess", + "NotPrecedes", + "NotPrecedesEqual", + "NotPrecedesSlantEqual", + "NotPrecedesTilde", + "NotReverseElement", + "NotRightTriangle", + "NotRightTriangleBar", + "NotRightTriangleEqual", + "NotSquareSubset", + "NotSquareSubsetEqual", + "NotSquareSuperset", + "NotSquareSupersetEqual", + "NotSubset", + "NotSubsetEqual", + "NotSucceeds", + "NotSucceedsEqual", + "NotSucceedsSlantEqual", + "NotSucceedsTilde", + "NotSuperset", + "NotSupersetEqual", + "NotTilde", + "NotTildeEqual", + "NotTildeFullEqual", + "NotTildeTilde", + "NotVerticalBar", + "Now", + "NoWhitespace", + "NProbability", + "NProduct", + "NProductFactors", + "NRoots", + "NSolve", + "NSum", + "NSumTerms", + "NuclearExplosionData", + "NuclearReactorData", + "Null", + "NullRecords", + "NullSpace", + "NullWords", + "Number", + "NumberCompose", + "NumberDecompose", + "NumberExpand", + "NumberFieldClassNumber", + "NumberFieldDiscriminant", + "NumberFieldFundamentalUnits", + "NumberFieldIntegralBasis", + "NumberFieldNormRepresentatives", + "NumberFieldRegulator", + "NumberFieldRootsOfUnity", + "NumberFieldSignature", + "NumberForm", + "NumberFormat", + "NumberLinePlot", + "NumberMarks", + "NumberMultiplier", + "NumberPadding", + "NumberPoint", + "NumberQ", + "NumberSeparator", + "NumberSigns", + "NumberString", + "Numerator", + "NumeratorDenominator", + "NumericalOrder", + "NumericalSort", + "NumericArray", + "NumericArrayQ", + "NumericArrayType", + "NumericFunction", + "NumericQ", + "NuttallWindow", + "NValues", + "NyquistGridLines", + "NyquistPlot", + "O", + "ObservabilityGramian", + "ObservabilityMatrix", + "ObservableDecomposition", + "ObservableModelQ", + "OceanData", + "Octahedron", + "OddQ", + "Off", + "Offset", + "OLEData", + "On", + "ONanGroupON", + "Once", + "OneIdentity", + "Opacity", + "OpacityFunction", + "OpacityFunctionScaling", + "Open", + "OpenAppend", + "Opener", + "OpenerBox", + "OpenerBoxOptions", + "OpenerView", + "OpenFunctionInspectorPacket", + "Opening", + "OpenRead", + "OpenSpecialOptions", + "OpenTemporary", + "OpenWrite", + "Operate", + "OperatingSystem", + "OperatorApplied", + "OptimumFlowData", + "Optional", + "OptionalElement", + "OptionInspectorSettings", + "OptionQ", + "Options", + "OptionsPacket", + "OptionsPattern", + "OptionValue", + "OptionValueBox", + "OptionValueBoxOptions", + "Or", + "Orange", + "Order", + "OrderDistribution", + "OrderedQ", + "Ordering", + "OrderingBy", + "OrderingLayer", + "Orderless", + "OrderlessPatternSequence", + "OrnsteinUhlenbeckProcess", + "Orthogonalize", + "OrthogonalMatrixQ", + "Out", + "Outer", + "OuterPolygon", + "OuterPolyhedron", + "OutputAutoOverwrite", + "OutputControllabilityMatrix", + "OutputControllableModelQ", + "OutputForm", + "OutputFormData", + "OutputGrouping", + "OutputMathEditExpression", + "OutputNamePacket", + "OutputResponse", + "OutputSizeLimit", + "OutputStream", + "Over", + "OverBar", + "OverDot", + "Overflow", + "OverHat", + "Overlaps", + "Overlay", + "OverlayBox", + "OverlayBoxOptions", + "Overscript", + "OverscriptBox", + "OverscriptBoxOptions", + "OverTilde", + "OverVector", + "OverwriteTarget", + "OwenT", + "OwnValues", + "Package", + "PackingMethod", + "PackPaclet", + "PacletDataRebuild", + "PacletDirectoryAdd", + "PacletDirectoryLoad", + "PacletDirectoryRemove", + "PacletDirectoryUnload", + "PacletDisable", + "PacletEnable", + "PacletFind", + "PacletFindRemote", + "PacletInformation", + "PacletInstall", + "PacletInstallSubmit", + "PacletNewerQ", + "PacletObject", + "PacletObjectQ", + "PacletSite", + "PacletSiteObject", + "PacletSiteRegister", + "PacletSites", + "PacletSiteUnregister", + "PacletSiteUpdate", + "PacletUninstall", + "PacletUpdate", + "PaddedForm", + "Padding", + "PaddingLayer", + "PaddingSize", + "PadeApproximant", + "PadLeft", + "PadRight", + "PageBreakAbove", + "PageBreakBelow", + "PageBreakWithin", + "PageFooterLines", + "PageFooters", + "PageHeaderLines", + "PageHeaders", + "PageHeight", + "PageRankCentrality", + "PageTheme", + "PageWidth", + "Pagination", + "PairedBarChart", + "PairedHistogram", + "PairedSmoothHistogram", + "PairedTTest", + "PairedZTest", + "PaletteNotebook", + "PalettePath", + "PalindromeQ", + "Pane", + "PaneBox", + "PaneBoxOptions", + "Panel", + "PanelBox", + "PanelBoxOptions", + "Paneled", + "PaneSelector", + "PaneSelectorBox", + "PaneSelectorBoxOptions", + "PaperWidth", + "ParabolicCylinderD", + "ParagraphIndent", + "ParagraphSpacing", + "ParallelArray", + "ParallelCombine", + "ParallelDo", + "Parallelepiped", + "ParallelEvaluate", + "Parallelization", + "Parallelize", + "ParallelMap", + "ParallelNeeds", + "Parallelogram", + "ParallelProduct", + "ParallelSubmit", + "ParallelSum", + "ParallelTable", + "ParallelTry", + "Parameter", + "ParameterEstimator", + "ParameterMixtureDistribution", + "ParameterVariables", + "ParametricFunction", + "ParametricNDSolve", + "ParametricNDSolveValue", + "ParametricPlot", + "ParametricPlot3D", + "ParametricRampLayer", + "ParametricRegion", + "ParentBox", + "ParentCell", + "ParentConnect", + "ParentDirectory", + "ParentForm", + "Parenthesize", + "ParentList", + "ParentNotebook", + "ParetoDistribution", + "ParetoPickandsDistribution", + "ParkData", + "Part", + "PartBehavior", + "PartialCorrelationFunction", + "PartialD", + "ParticleAcceleratorData", + "ParticleData", + "Partition", + "PartitionGranularity", + "PartitionsP", + "PartitionsQ", + "PartLayer", + "PartOfSpeech", + "PartProtection", + "ParzenWindow", + "PascalDistribution", + "PassEventsDown", + "PassEventsUp", + "Paste", + "PasteAutoQuoteCharacters", + "PasteBoxFormInlineCells", + "PasteButton", + "Path", + "PathGraph", + "PathGraphQ", + "Pattern", + "PatternFilling", + "PatternSequence", + "PatternTest", + "PauliMatrix", + "PaulWavelet", + "Pause", + "PausedTime", + "PDF", + "PeakDetect", + "PeanoCurve", + "PearsonChiSquareTest", + "PearsonCorrelationTest", + "PearsonDistribution", + "PercentForm", + "PerfectNumber", + "PerfectNumberQ", + "PerformanceGoal", + "Perimeter", + "PeriodicBoundaryCondition", + "PeriodicInterpolation", + "Periodogram", + "PeriodogramArray", + "Permanent", + "Permissions", + "PermissionsGroup", + "PermissionsGroupMemberQ", + "PermissionsGroups", + "PermissionsKey", + "PermissionsKeys", + "PermutationCycles", + "PermutationCyclesQ", + "PermutationGroup", + "PermutationLength", + "PermutationList", + "PermutationListQ", + "PermutationMax", + "PermutationMin", + "PermutationOrder", + "PermutationPower", + "PermutationProduct", + "PermutationReplace", + "Permutations", + "PermutationSupport", + "Permute", + "PeronaMalikFilter", + "Perpendicular", + "PerpendicularBisector", + "PersistenceLocation", + "PersistenceTime", + "PersistentObject", + "PersistentObjects", + "PersistentValue", + "PersonData", + "PERTDistribution", + "PetersenGraph", + "PhaseMargins", + "PhaseRange", + "PhysicalSystemData", + "Pi", + "Pick", + "PIDData", + "PIDDerivativeFilter", + "PIDFeedforward", + "PIDTune", + "Piecewise", + "PiecewiseExpand", + "PieChart", + "PieChart3D", + "PillaiTrace", + "PillaiTraceTest", + "PingTime", + "Pink", + "PitchRecognize", + "Pivoting", + "PixelConstrained", + "PixelValue", + "PixelValuePositions", + "Placed", + "Placeholder", + "PlaceholderReplace", + "Plain", + "PlanarAngle", + "PlanarGraph", + "PlanarGraphQ", + "PlanckRadiationLaw", + "PlaneCurveData", + "PlanetaryMoonData", + "PlanetData", + "PlantData", + "Play", + "PlayRange", + "Plot", + "Plot3D", + "Plot3Matrix", + "PlotDivision", + "PlotJoined", + "PlotLabel", + "PlotLabels", + "PlotLayout", + "PlotLegends", + "PlotMarkers", + "PlotPoints", + "PlotRange", + "PlotRangeClipping", + "PlotRangeClipPlanesStyle", + "PlotRangePadding", + "PlotRegion", + "PlotStyle", + "PlotTheme", + "Pluralize", + "Plus", + "PlusMinus", + "Pochhammer", + "PodStates", + "PodWidth", + "Point", + "Point3DBox", + "Point3DBoxOptions", + "PointBox", + "PointBoxOptions", + "PointFigureChart", + "PointLegend", + "PointSize", + "PoissonConsulDistribution", + "PoissonDistribution", + "PoissonProcess", + "PoissonWindow", + "PolarAxes", + "PolarAxesOrigin", + "PolarGridLines", + "PolarPlot", + "PolarTicks", + "PoleZeroMarkers", + "PolyaAeppliDistribution", + "PolyGamma", + "Polygon", + "Polygon3DBox", + "Polygon3DBoxOptions", + "PolygonalNumber", + "PolygonAngle", + "PolygonBox", + "PolygonBoxOptions", + "PolygonCoordinates", + "PolygonDecomposition", + "PolygonHoleScale", + "PolygonIntersections", + "PolygonScale", + "Polyhedron", + "PolyhedronAngle", + "PolyhedronCoordinates", + "PolyhedronData", + "PolyhedronDecomposition", + "PolyhedronGenus", + "PolyLog", + "PolynomialExtendedGCD", + "PolynomialForm", + "PolynomialGCD", + "PolynomialLCM", + "PolynomialMod", + "PolynomialQ", + "PolynomialQuotient", + "PolynomialQuotientRemainder", + "PolynomialReduce", + "PolynomialRemainder", + "Polynomials", + "PoolingLayer", + "PopupMenu", + "PopupMenuBox", + "PopupMenuBoxOptions", + "PopupView", + "PopupWindow", + "Position", + "PositionIndex", + "Positive", + "PositiveDefiniteMatrixQ", + "PositiveIntegers", + "PositiveRationals", + "PositiveReals", + "PositiveSemidefiniteMatrixQ", + "PossibleZeroQ", + "Postfix", + "PostScript", + "Power", + "PowerDistribution", + "PowerExpand", + "PowerMod", + "PowerModList", + "PowerRange", + "PowerSpectralDensity", + "PowersRepresentations", + "PowerSymmetricPolynomial", + "Precedence", + "PrecedenceForm", + "Precedes", + "PrecedesEqual", + "PrecedesSlantEqual", + "PrecedesTilde", + "Precision", + "PrecisionGoal", + "PreDecrement", + "Predict", + "PredictionRoot", + "PredictorFunction", + "PredictorInformation", + "PredictorMeasurements", + "PredictorMeasurementsObject", + "PreemptProtect", + "PreferencesPath", + "Prefix", + "PreIncrement", + "Prepend", + "PrependLayer", + "PrependTo", + "PreprocessingRules", + "PreserveColor", + "PreserveImageOptions", + "Previous", + "PreviousCell", + "PreviousDate", + "PriceGraphDistribution", + "PrimaryPlaceholder", + "Prime", + "PrimeNu", + "PrimeOmega", + "PrimePi", + "PrimePowerQ", + "PrimeQ", + "Primes", + "PrimeZetaP", + "PrimitivePolynomialQ", + "PrimitiveRoot", + "PrimitiveRootList", + "PrincipalComponents", + "PrincipalValue", + "Print", + "PrintableASCIIQ", + "PrintAction", + "PrintForm", + "PrintingCopies", + "PrintingOptions", + "PrintingPageRange", + "PrintingStartingPageNumber", + "PrintingStyleEnvironment", + "Printout3D", + "Printout3DPreviewer", + "PrintPrecision", + "PrintTemporary", + "Prism", + "PrismBox", + "PrismBoxOptions", + "PrivateCellOptions", + "PrivateEvaluationOptions", + "PrivateFontOptions", + "PrivateFrontEndOptions", + "PrivateKey", + "PrivateNotebookOptions", + "PrivatePaths", + "Probability", + "ProbabilityDistribution", + "ProbabilityPlot", + "ProbabilityPr", + "ProbabilityScalePlot", + "ProbitModelFit", + "ProcessConnection", + "ProcessDirectory", + "ProcessEnvironment", + "Processes", + "ProcessEstimator", + "ProcessInformation", + "ProcessObject", + "ProcessParameterAssumptions", + "ProcessParameterQ", + "ProcessStateDomain", + "ProcessStatus", + "ProcessTimeDomain", + "Product", + "ProductDistribution", + "ProductLog", + "ProgressIndicator", + "ProgressIndicatorBox", + "ProgressIndicatorBoxOptions", + "Projection", + "Prolog", + "PromptForm", + "ProofObject", + "Properties", + "Property", + "PropertyList", + "PropertyValue", + "Proportion", + "Proportional", + "Protect", + "Protected", + "ProteinData", + "Pruning", + "PseudoInverse", + "PsychrometricPropertyData", + "PublicKey", + "PublisherID", + "PulsarData", + "PunctuationCharacter", + "Purple", + "Put", + "PutAppend", + "Pyramid", + "PyramidBox", + "PyramidBoxOptions", + "QBinomial", + "QFactorial", + "QGamma", + "QHypergeometricPFQ", + "QnDispersion", + "QPochhammer", + "QPolyGamma", + "QRDecomposition", + "QuadraticIrrationalQ", + "QuadraticOptimization", + "Quantile", + "QuantilePlot", + "Quantity", + "QuantityArray", + "QuantityDistribution", + "QuantityForm", + "QuantityMagnitude", + "QuantityQ", + "QuantityUnit", + "QuantityVariable", + "QuantityVariableCanonicalUnit", + "QuantityVariableDimensions", + "QuantityVariableIdentifier", + "QuantityVariablePhysicalQuantity", + "Quartics", + "QuartileDeviation", + "Quartiles", + "QuartileSkewness", + "Query", + "QueueingNetworkProcess", + "QueueingProcess", + "QueueProperties", + "Quiet", + "Quit", + "Quotient", + "QuotientRemainder", + "RadialGradientImage", + "RadialityCentrality", + "RadicalBox", + "RadicalBoxOptions", + "RadioButton", + "RadioButtonBar", + "RadioButtonBox", + "RadioButtonBoxOptions", + "Radon", + "RadonTransform", + "RamanujanTau", + "RamanujanTauL", + "RamanujanTauTheta", + "RamanujanTauZ", + "Ramp", + "Random", + "RandomChoice", + "RandomColor", + "RandomComplex", + "RandomEntity", + "RandomFunction", + "RandomGeoPosition", + "RandomGraph", + "RandomImage", + "RandomInstance", + "RandomInteger", + "RandomPermutation", + "RandomPoint", + "RandomPolygon", + "RandomPolyhedron", + "RandomPrime", + "RandomReal", + "RandomSample", + "RandomSeed", + "RandomSeeding", + "RandomVariate", + "RandomWalkProcess", + "RandomWord", + "Range", + "RangeFilter", + "RangeSpecification", + "RankedMax", + "RankedMin", + "RarerProbability", + "Raster", + "Raster3D", + "Raster3DBox", + "Raster3DBoxOptions", + "RasterArray", + "RasterBox", + "RasterBoxOptions", + "Rasterize", + "RasterSize", + "Rational", + "RationalFunctions", + "Rationalize", + "Rationals", + "Ratios", + "RawArray", + "RawBoxes", + "RawData", + "RawMedium", + "RayleighDistribution", + "Re", + "Read", + "ReadByteArray", + "ReadLine", + "ReadList", + "ReadProtected", + "ReadString", + "Real", + "RealAbs", + "RealBlockDiagonalForm", + "RealDigits", + "RealExponent", + "Reals", + "RealSign", + "Reap", + "RebuildPacletData", + "RecognitionPrior", + "RecognitionThreshold", + "Record", + "RecordLists", + "RecordSeparators", + "Rectangle", + "RectangleBox", + "RectangleBoxOptions", + "RectangleChart", + "RectangleChart3D", + "RectangularRepeatingElement", + "RecurrenceFilter", + "RecurrenceTable", + "RecurringDigitsForm", + "Red", + "Reduce", + "RefBox", + "ReferenceLineStyle", + "ReferenceMarkers", + "ReferenceMarkerStyle", + "Refine", + "ReflectionMatrix", + "ReflectionTransform", + "Refresh", + "RefreshRate", + "Region", + "RegionBinarize", + "RegionBoundary", + "RegionBoundaryStyle", + "RegionBounds", + "RegionCentroid", + "RegionDifference", + "RegionDimension", + "RegionDisjoint", + "RegionDistance", + "RegionDistanceFunction", + "RegionEmbeddingDimension", + "RegionEqual", + "RegionFillingStyle", + "RegionFunction", + "RegionImage", + "RegionIntersection", + "RegionMeasure", + "RegionMember", + "RegionMemberFunction", + "RegionMoment", + "RegionNearest", + "RegionNearestFunction", + "RegionPlot", + "RegionPlot3D", + "RegionProduct", + "RegionQ", + "RegionResize", + "RegionSize", + "RegionSymmetricDifference", + "RegionUnion", + "RegionWithin", + "RegisterExternalEvaluator", + "RegularExpression", + "Regularization", + "RegularlySampledQ", + "RegularPolygon", + "ReIm", + "ReImLabels", + "ReImPlot", + "ReImStyle", + "Reinstall", + "RelationalDatabase", + "RelationGraph", + "Release", + "ReleaseHold", + "ReliabilityDistribution", + "ReliefImage", + "ReliefPlot", + "RemoteAuthorizationCaching", + "RemoteConnect", + "RemoteConnectionObject", + "RemoteFile", + "RemoteRun", + "RemoteRunProcess", + "Remove", + "RemoveAlphaChannel", + "RemoveAsynchronousTask", + "RemoveAudioStream", + "RemoveBackground", + "RemoveChannelListener", + "RemoveChannelSubscribers", + "Removed", + "RemoveDiacritics", + "RemoveInputStreamMethod", + "RemoveOutputStreamMethod", + "RemoveProperty", + "RemoveScheduledTask", + "RemoveUsers", + "RemoveVideoStream", + "RenameDirectory", + "RenameFile", + "RenderAll", + "RenderingOptions", + "RenewalProcess", + "RenkoChart", + "RepairMesh", + "Repeated", + "RepeatedNull", + "RepeatedString", + "RepeatedTiming", + "RepeatingElement", + "Replace", + "ReplaceAll", + "ReplaceHeldPart", + "ReplaceImageValue", + "ReplaceList", + "ReplacePart", + "ReplacePixelValue", + "ReplaceRepeated", + "ReplicateLayer", + "RequiredPhysicalQuantities", + "Resampling", + "ResamplingAlgorithmData", + "ResamplingMethod", + "Rescale", + "RescalingTransform", + "ResetDirectory", + "ResetMenusPacket", + "ResetScheduledTask", + "ReshapeLayer", + "Residue", + "ResizeLayer", + "Resolve", + "ResourceAcquire", + "ResourceData", + "ResourceFunction", + "ResourceObject", + "ResourceRegister", + "ResourceRemove", + "ResourceSearch", + "ResourceSubmissionObject", + "ResourceSubmit", + "ResourceSystemBase", + "ResourceSystemPath", + "ResourceUpdate", + "ResourceVersion", + "ResponseForm", + "Rest", + "RestartInterval", + "Restricted", + "Resultant", + "ResumePacket", + "Return", + "ReturnEntersInput", + "ReturnExpressionPacket", + "ReturnInputFormPacket", + "ReturnPacket", + "ReturnReceiptFunction", + "ReturnTextPacket", + "Reverse", + "ReverseApplied", + "ReverseBiorthogonalSplineWavelet", + "ReverseElement", + "ReverseEquilibrium", + "ReverseGraph", + "ReverseSort", + "ReverseSortBy", + "ReverseUpEquilibrium", + "RevolutionAxis", + "RevolutionPlot3D", + "RGBColor", + "RiccatiSolve", + "RiceDistribution", + "RidgeFilter", + "RiemannR", + "RiemannSiegelTheta", + "RiemannSiegelZ", + "RiemannXi", + "Riffle", + "Right", + "RightArrow", + "RightArrowBar", + "RightArrowLeftArrow", + "RightComposition", + "RightCosetRepresentative", + "RightDownTeeVector", + "RightDownVector", + "RightDownVectorBar", + "RightTee", + "RightTeeArrow", + "RightTeeVector", + "RightTriangle", + "RightTriangleBar", + "RightTriangleEqual", + "RightUpDownVector", + "RightUpTeeVector", + "RightUpVector", + "RightUpVectorBar", + "RightVector", + "RightVectorBar", + "RiskAchievementImportance", + "RiskReductionImportance", + "RogersTanimotoDissimilarity", + "RollPitchYawAngles", + "RollPitchYawMatrix", + "RomanNumeral", + "Root", + "RootApproximant", + "RootIntervals", + "RootLocusPlot", + "RootMeanSquare", + "RootOfUnityQ", + "RootReduce", + "Roots", + "RootSum", + "Rotate", + "RotateLabel", + "RotateLeft", + "RotateRight", + "RotationAction", + "RotationBox", + "RotationBoxOptions", + "RotationMatrix", + "RotationTransform", + "Round", + "RoundImplies", + "RoundingRadius", + "Row", + "RowAlignments", + "RowBackgrounds", + "RowBox", + "RowHeights", + "RowLines", + "RowMinHeight", + "RowReduce", + "RowsEqual", + "RowSpacings", + "RSolve", + "RSolveValue", + "RudinShapiro", + "RudvalisGroupRu", + "Rule", + "RuleCondition", + "RuleDelayed", + "RuleForm", + "RulePlot", + "RulerUnits", + "Run", + "RunProcess", + "RunScheduledTask", + "RunThrough", + "RuntimeAttributes", + "RuntimeOptions", + "RussellRaoDissimilarity", + "SameQ", + "SameTest", + "SameTestProperties", + "SampledEntityClass", + "SampleDepth", + "SampledSoundFunction", + "SampledSoundList", + "SampleRate", + "SamplingPeriod", + "SARIMAProcess", + "SARMAProcess", + "SASTriangle", + "SatelliteData", + "SatisfiabilityCount", + "SatisfiabilityInstances", + "SatisfiableQ", + "Saturday", + "Save", + "Saveable", + "SaveAutoDelete", + "SaveConnection", + "SaveDefinitions", + "SavitzkyGolayMatrix", + "SawtoothWave", + "Scale", + "Scaled", + "ScaleDivisions", + "ScaledMousePosition", + "ScaleOrigin", + "ScalePadding", + "ScaleRanges", + "ScaleRangeStyle", + "ScalingFunctions", + "ScalingMatrix", + "ScalingTransform", + "Scan", + "ScheduledTask", + "ScheduledTaskActiveQ", + "ScheduledTaskInformation", + "ScheduledTaskInformationData", + "ScheduledTaskObject", + "ScheduledTasks", + "SchurDecomposition", + "ScientificForm", + "ScientificNotationThreshold", + "ScorerGi", + "ScorerGiPrime", + "ScorerHi", + "ScorerHiPrime", + "ScreenRectangle", + "ScreenStyleEnvironment", + "ScriptBaselineShifts", + "ScriptForm", + "ScriptLevel", + "ScriptMinSize", + "ScriptRules", + "ScriptSizeMultipliers", + "Scrollbars", + "ScrollingOptions", + "ScrollPosition", + "SearchAdjustment", + "SearchIndexObject", + "SearchIndices", + "SearchQueryString", + "SearchResultObject", + "Sec", + "Sech", + "SechDistribution", + "SecondOrderConeOptimization", + "SectionGrouping", + "SectorChart", + "SectorChart3D", + "SectorOrigin", + "SectorSpacing", + "SecuredAuthenticationKey", + "SecuredAuthenticationKeys", + "SeedRandom", + "Select", + "Selectable", + "SelectComponents", + "SelectedCells", + "SelectedNotebook", + "SelectFirst", + "Selection", + "SelectionAnimate", + "SelectionCell", + "SelectionCellCreateCell", + "SelectionCellDefaultStyle", + "SelectionCellParentStyle", + "SelectionCreateCell", + "SelectionDebuggerTag", + "SelectionDuplicateCell", + "SelectionEvaluate", + "SelectionEvaluateCreateCell", + "SelectionMove", + "SelectionPlaceholder", + "SelectionSetStyle", + "SelectWithContents", + "SelfLoops", + "SelfLoopStyle", + "SemanticImport", + "SemanticImportString", + "SemanticInterpretation", + "SemialgebraicComponentInstances", + "SemidefiniteOptimization", + "SendMail", + "SendMessage", + "Sequence", + "SequenceAlignment", + "SequenceAttentionLayer", + "SequenceCases", + "SequenceCount", + "SequenceFold", + "SequenceFoldList", + "SequenceForm", + "SequenceHold", + "SequenceLastLayer", + "SequenceMostLayer", + "SequencePosition", + "SequencePredict", + "SequencePredictorFunction", + "SequenceReplace", + "SequenceRestLayer", + "SequenceReverseLayer", + "SequenceSplit", + "Series", + "SeriesCoefficient", + "SeriesData", + "SeriesTermGoal", + "ServiceConnect", + "ServiceDisconnect", + "ServiceExecute", + "ServiceObject", + "ServiceRequest", + "ServiceResponse", + "ServiceSubmit", + "SessionSubmit", + "SessionTime", + "Set", + "SetAccuracy", + "SetAlphaChannel", + "SetAttributes", + "Setbacks", + "SetBoxFormNamesPacket", + "SetCloudDirectory", + "SetCookies", + "SetDelayed", + "SetDirectory", + "SetEnvironment", + "SetEvaluationNotebook", + "SetFileDate", + "SetFileLoadingContext", + "SetNotebookStatusLine", + "SetOptions", + "SetOptionsPacket", + "SetPermissions", + "SetPrecision", + "SetProperty", + "SetSecuredAuthenticationKey", + "SetSelectedNotebook", + "SetSharedFunction", + "SetSharedVariable", + "SetSpeechParametersPacket", + "SetStreamPosition", + "SetSystemModel", + "SetSystemOptions", + "Setter", + "SetterBar", + "SetterBox", + "SetterBoxOptions", + "Setting", + "SetUsers", + "SetValue", + "Shading", + "Shallow", + "ShannonWavelet", + "ShapiroWilkTest", + "Share", + "SharingList", + "Sharpen", + "ShearingMatrix", + "ShearingTransform", + "ShellRegion", + "ShenCastanMatrix", + "ShiftedGompertzDistribution", + "ShiftRegisterSequence", + "Short", + "ShortDownArrow", + "Shortest", + "ShortestMatch", + "ShortestPathFunction", + "ShortLeftArrow", + "ShortRightArrow", + "ShortTimeFourier", + "ShortTimeFourierData", + "ShortUpArrow", + "Show", + "ShowAutoConvert", + "ShowAutoSpellCheck", + "ShowAutoStyles", + "ShowCellBracket", + "ShowCellLabel", + "ShowCellTags", + "ShowClosedCellArea", + "ShowCodeAssist", + "ShowContents", + "ShowControls", + "ShowCursorTracker", + "ShowGroupOpenCloseIcon", + "ShowGroupOpener", + "ShowInvisibleCharacters", + "ShowPageBreaks", + "ShowPredictiveInterface", + "ShowSelection", + "ShowShortBoxForm", + "ShowSpecialCharacters", + "ShowStringCharacters", + "ShowSyntaxStyles", + "ShrinkingDelay", + "ShrinkWrapBoundingBox", + "SiderealTime", + "SiegelTheta", + "SiegelTukeyTest", + "SierpinskiCurve", + "SierpinskiMesh", + "Sign", + "Signature", + "SignedRankTest", + "SignedRegionDistance", + "SignificanceLevel", + "SignPadding", + "SignTest", + "SimilarityRules", + "SimpleGraph", + "SimpleGraphQ", + "SimplePolygonQ", + "SimplePolyhedronQ", + "Simplex", + "Simplify", + "Sin", + "Sinc", + "SinghMaddalaDistribution", + "SingleEvaluation", + "SingleLetterItalics", + "SingleLetterStyle", + "SingularValueDecomposition", + "SingularValueList", + "SingularValuePlot", + "SingularValues", + "Sinh", + "SinhIntegral", + "SinIntegral", + "SixJSymbol", + "Skeleton", + "SkeletonTransform", + "SkellamDistribution", + "Skewness", + "SkewNormalDistribution", + "SkinStyle", + "Skip", + "SliceContourPlot3D", + "SliceDensityPlot3D", + "SliceDistribution", + "SliceVectorPlot3D", + "Slider", + "Slider2D", + "Slider2DBox", + "Slider2DBoxOptions", + "SliderBox", + "SliderBoxOptions", + "SlideView", + "Slot", + "SlotSequence", + "Small", + "SmallCircle", + "Smaller", + "SmithDecomposition", + "SmithDelayCompensator", + "SmithWatermanSimilarity", + "SmoothDensityHistogram", + "SmoothHistogram", + "SmoothHistogram3D", + "SmoothKernelDistribution", + "SnDispersion", + "Snippet", + "SnubPolyhedron", + "SocialMediaData", + "Socket", + "SocketConnect", + "SocketListen", + "SocketListener", + "SocketObject", + "SocketOpen", + "SocketReadMessage", + "SocketReadyQ", + "Sockets", + "SocketWaitAll", + "SocketWaitNext", + "SoftmaxLayer", + "SokalSneathDissimilarity", + "SolarEclipse", + "SolarSystemFeatureData", + "SolidAngle", + "SolidData", + "SolidRegionQ", + "Solve", + "SolveAlways", + "SolveDelayed", + "Sort", + "SortBy", + "SortedBy", + "SortedEntityClass", + "Sound", + "SoundAndGraphics", + "SoundNote", + "SoundVolume", + "SourceLink", + "Sow", + "Space", + "SpaceCurveData", + "SpaceForm", + "Spacer", + "Spacings", + "Span", + "SpanAdjustments", + "SpanCharacterRounding", + "SpanFromAbove", + "SpanFromBoth", + "SpanFromLeft", + "SpanLineThickness", + "SpanMaxSize", + "SpanMinSize", + "SpanningCharacters", + "SpanSymmetric", + "SparseArray", + "SpatialGraphDistribution", + "SpatialMedian", + "SpatialTransformationLayer", + "Speak", + "SpeakerMatchQ", + "SpeakTextPacket", + "SpearmanRankTest", + "SpearmanRho", + "SpeciesData", + "SpecificityGoal", + "SpectralLineData", + "Spectrogram", + "SpectrogramArray", + "Specularity", + "SpeechCases", + "SpeechInterpreter", + "SpeechRecognize", + "SpeechSynthesize", + "SpellingCorrection", + "SpellingCorrectionList", + "SpellingDictionaries", + "SpellingDictionariesPath", + "SpellingOptions", + "SpellingSuggestionsPacket", + "Sphere", + "SphereBox", + "SpherePoints", + "SphericalBesselJ", + "SphericalBesselY", + "SphericalHankelH1", + "SphericalHankelH2", + "SphericalHarmonicY", + "SphericalPlot3D", + "SphericalRegion", + "SphericalShell", + "SpheroidalEigenvalue", + "SpheroidalJoiningFactor", + "SpheroidalPS", + "SpheroidalPSPrime", + "SpheroidalQS", + "SpheroidalQSPrime", + "SpheroidalRadialFactor", + "SpheroidalS1", + "SpheroidalS1Prime", + "SpheroidalS2", + "SpheroidalS2Prime", + "Splice", + "SplicedDistribution", + "SplineClosed", + "SplineDegree", + "SplineKnots", + "SplineWeights", + "Split", + "SplitBy", + "SpokenString", + "Sqrt", + "SqrtBox", + "SqrtBoxOptions", + "Square", + "SquaredEuclideanDistance", + "SquareFreeQ", + "SquareIntersection", + "SquareMatrixQ", + "SquareRepeatingElement", + "SquaresR", + "SquareSubset", + "SquareSubsetEqual", + "SquareSuperset", + "SquareSupersetEqual", + "SquareUnion", + "SquareWave", + "SSSTriangle", + "StabilityMargins", + "StabilityMarginsStyle", + "StableDistribution", + "Stack", + "StackBegin", + "StackComplete", + "StackedDateListPlot", + "StackedListPlot", + "StackInhibit", + "StadiumShape", + "StandardAtmosphereData", + "StandardDeviation", + "StandardDeviationFilter", + "StandardForm", + "Standardize", + "Standardized", + "StandardOceanData", + "StandbyDistribution", + "Star", + "StarClusterData", + "StarData", + "StarGraph", + "StartAsynchronousTask", + "StartExternalSession", + "StartingStepSize", + "StartOfLine", + "StartOfString", + "StartProcess", + "StartScheduledTask", + "StartupSound", + "StartWebSession", + "StateDimensions", + "StateFeedbackGains", + "StateOutputEstimator", + "StateResponse", + "StateSpaceModel", + "StateSpaceRealization", + "StateSpaceTransform", + "StateTransformationLinearize", + "StationaryDistribution", + "StationaryWaveletPacketTransform", + "StationaryWaveletTransform", + "StatusArea", + "StatusCentrality", + "StepMonitor", + "StereochemistryElements", + "StieltjesGamma", + "StippleShading", + "StirlingS1", + "StirlingS2", + "StopAsynchronousTask", + "StoppingPowerData", + "StopScheduledTask", + "StrataVariables", + "StratonovichProcess", + "StreamColorFunction", + "StreamColorFunctionScaling", + "StreamDensityPlot", + "StreamMarkers", + "StreamPlot", + "StreamPoints", + "StreamPosition", + "Streams", + "StreamScale", + "StreamStyle", + "String", + "StringBreak", + "StringByteCount", + "StringCases", + "StringContainsQ", + "StringCount", + "StringDelete", + "StringDrop", + "StringEndsQ", + "StringExpression", + "StringExtract", + "StringForm", + "StringFormat", + "StringFreeQ", + "StringInsert", + "StringJoin", + "StringLength", + "StringMatchQ", + "StringPadLeft", + "StringPadRight", + "StringPart", + "StringPartition", + "StringPosition", + "StringQ", + "StringRepeat", + "StringReplace", + "StringReplaceList", + "StringReplacePart", + "StringReverse", + "StringRiffle", + "StringRotateLeft", + "StringRotateRight", + "StringSkeleton", + "StringSplit", + "StringStartsQ", + "StringTake", + "StringTemplate", + "StringToByteArray", + "StringToStream", + "StringTrim", + "StripBoxes", + "StripOnInput", + "StripWrapperBoxes", + "StrokeForm", + "StructuralImportance", + "StructuredArray", + "StructuredArrayHeadQ", + "StructuredSelection", + "StruveH", + "StruveL", + "Stub", + "StudentTDistribution", + "Style", + "StyleBox", + "StyleBoxAutoDelete", + "StyleData", + "StyleDefinitions", + "StyleForm", + "StyleHints", + "StyleKeyMapping", + "StyleMenuListing", + "StyleNameDialogSettings", + "StyleNames", + "StylePrint", + "StyleSheetPath", + "Subdivide", + "Subfactorial", + "Subgraph", + "SubMinus", + "SubPlus", + "SubresultantPolynomialRemainders", + "SubresultantPolynomials", + "Subresultants", + "Subscript", + "SubscriptBox", + "SubscriptBoxOptions", + "Subscripted", + "Subsequences", + "Subset", + "SubsetCases", + "SubsetCount", + "SubsetEqual", + "SubsetMap", + "SubsetPosition", + "SubsetQ", + "SubsetReplace", + "Subsets", + "SubStar", + "SubstitutionSystem", + "Subsuperscript", + "SubsuperscriptBox", + "SubsuperscriptBoxOptions", + "SubtitleEncoding", + "SubtitleTracks", + "Subtract", + "SubtractFrom", + "SubtractSides", + "SubValues", + "Succeeds", + "SucceedsEqual", + "SucceedsSlantEqual", + "SucceedsTilde", + "Success", + "SuchThat", + "Sum", + "SumConvergence", + "SummationLayer", + "Sunday", + "SunPosition", + "Sunrise", + "Sunset", + "SuperDagger", + "SuperMinus", + "SupernovaData", + "SuperPlus", + "Superscript", + "SuperscriptBox", + "SuperscriptBoxOptions", + "Superset", + "SupersetEqual", + "SuperStar", + "Surd", + "SurdForm", + "SurfaceAppearance", + "SurfaceArea", + "SurfaceColor", + "SurfaceData", + "SurfaceGraphics", + "SurvivalDistribution", + "SurvivalFunction", + "SurvivalModel", + "SurvivalModelFit", + "SuspendPacket", + "SuzukiDistribution", + "SuzukiGroupSuz", + "SwatchLegend", + "Switch", + "Symbol", + "SymbolName", + "SymletWavelet", + "Symmetric", + "SymmetricGroup", + "SymmetricKey", + "SymmetricMatrixQ", + "SymmetricPolynomial", + "SymmetricReduction", + "Symmetrize", + "SymmetrizedArray", + "SymmetrizedArrayRules", + "SymmetrizedDependentComponents", + "SymmetrizedIndependentComponents", + "SymmetrizedReplacePart", + "SynchronousInitialization", + "SynchronousUpdating", + "Synonyms", + "Syntax", + "SyntaxForm", + "SyntaxInformation", + "SyntaxLength", + "SyntaxPacket", + "SyntaxQ", + "SynthesizeMissingValues", + "SystemCredential", + "SystemCredentialData", + "SystemCredentialKey", + "SystemCredentialKeys", + "SystemCredentialStoreObject", + "SystemDialogInput", + "SystemException", + "SystemGet", + "SystemHelpPath", + "SystemInformation", + "SystemInformationData", + "SystemInstall", + "SystemModel", + "SystemModeler", + "SystemModelExamples", + "SystemModelLinearize", + "SystemModelParametricSimulate", + "SystemModelPlot", + "SystemModelProgressReporting", + "SystemModelReliability", + "SystemModels", + "SystemModelSimulate", + "SystemModelSimulateSensitivity", + "SystemModelSimulationData", + "SystemOpen", + "SystemOptions", + "SystemProcessData", + "SystemProcesses", + "SystemsConnectionsModel", + "SystemsModelDelay", + "SystemsModelDelayApproximate", + "SystemsModelDelete", + "SystemsModelDimensions", + "SystemsModelExtract", + "SystemsModelFeedbackConnect", + "SystemsModelLabels", + "SystemsModelLinearity", + "SystemsModelMerge", + "SystemsModelOrder", + "SystemsModelParallelConnect", + "SystemsModelSeriesConnect", + "SystemsModelStateFeedbackConnect", + "SystemsModelVectorRelativeOrders", + "SystemStub", + "SystemTest", + "Tab", + "TabFilling", + "Table", + "TableAlignments", + "TableDepth", + "TableDirections", + "TableForm", + "TableHeadings", + "TableSpacing", + "TableView", + "TableViewBox", + "TableViewBoxBackground", + "TableViewBoxItemSize", + "TableViewBoxOptions", + "TabSpacings", + "TabView", + "TabViewBox", + "TabViewBoxOptions", + "TagBox", + "TagBoxNote", + "TagBoxOptions", + "TaggingRules", + "TagSet", + "TagSetDelayed", + "TagStyle", + "TagUnset", + "Take", + "TakeDrop", + "TakeLargest", + "TakeLargestBy", + "TakeList", + "TakeSmallest", + "TakeSmallestBy", + "TakeWhile", + "Tally", + "Tan", + "Tanh", + "TargetDevice", + "TargetFunctions", + "TargetSystem", + "TargetUnits", + "TaskAbort", + "TaskExecute", + "TaskObject", + "TaskRemove", + "TaskResume", + "Tasks", + "TaskSuspend", + "TaskWait", + "TautologyQ", + "TelegraphProcess", + "TemplateApply", + "TemplateArgBox", + "TemplateBox", + "TemplateBoxOptions", + "TemplateEvaluate", + "TemplateExpression", + "TemplateIf", + "TemplateObject", + "TemplateSequence", + "TemplateSlot", + "TemplateSlotSequence", + "TemplateUnevaluated", + "TemplateVerbatim", + "TemplateWith", + "TemporalData", + "TemporalRegularity", + "Temporary", + "TemporaryVariable", + "TensorContract", + "TensorDimensions", + "TensorExpand", + "TensorProduct", + "TensorQ", + "TensorRank", + "TensorReduce", + "TensorSymmetry", + "TensorTranspose", + "TensorWedge", + "TestID", + "TestReport", + "TestReportObject", + "TestResultObject", + "Tetrahedron", + "TetrahedronBox", + "TetrahedronBoxOptions", + "TeXForm", + "TeXSave", + "Text", + "Text3DBox", + "Text3DBoxOptions", + "TextAlignment", + "TextBand", + "TextBoundingBox", + "TextBox", + "TextCases", + "TextCell", + "TextClipboardType", + "TextContents", + "TextData", + "TextElement", + "TextForm", + "TextGrid", + "TextJustification", + "TextLine", + "TextPacket", + "TextParagraph", + "TextPosition", + "TextRecognize", + "TextSearch", + "TextSearchReport", + "TextSentences", + "TextString", + "TextStructure", + "TextStyle", + "TextTranslation", + "Texture", + "TextureCoordinateFunction", + "TextureCoordinateScaling", + "TextWords", + "Therefore", + "ThermodynamicData", + "ThermometerGauge", + "Thick", + "Thickness", + "Thin", + "Thinning", + "ThisLink", + "ThompsonGroupTh", + "Thread", + "ThreadingLayer", + "ThreeJSymbol", + "Threshold", + "Through", + "Throw", + "ThueMorse", + "Thumbnail", + "Thursday", + "Ticks", + "TicksStyle", + "TideData", + "Tilde", + "TildeEqual", + "TildeFullEqual", + "TildeTilde", + "TimeConstrained", + "TimeConstraint", + "TimeDirection", + "TimeFormat", + "TimeGoal", + "TimelinePlot", + "TimeObject", + "TimeObjectQ", + "TimeRemaining", + "Times", + "TimesBy", + "TimeSeries", + "TimeSeriesAggregate", + "TimeSeriesForecast", + "TimeSeriesInsert", + "TimeSeriesInvertibility", + "TimeSeriesMap", + "TimeSeriesMapThread", + "TimeSeriesModel", + "TimeSeriesModelFit", + "TimeSeriesResample", + "TimeSeriesRescale", + "TimeSeriesShift", + "TimeSeriesThread", + "TimeSeriesWindow", + "TimeUsed", + "TimeValue", + "TimeWarpingCorrespondence", + "TimeWarpingDistance", + "TimeZone", + "TimeZoneConvert", + "TimeZoneOffset", + "Timing", + "Tiny", + "TitleGrouping", + "TitsGroupT", + "ToBoxes", + "ToCharacterCode", + "ToColor", + "ToContinuousTimeModel", + "ToDate", + "Today", + "ToDiscreteTimeModel", + "ToEntity", + "ToeplitzMatrix", + "ToExpression", + "ToFileName", + "Together", + "Toggle", + "ToggleFalse", + "Toggler", + "TogglerBar", + "TogglerBox", + "TogglerBoxOptions", + "ToHeldExpression", + "ToInvertibleTimeSeries", + "TokenWords", + "Tolerance", + "ToLowerCase", + "Tomorrow", + "ToNumberField", + "TooBig", + "Tooltip", + "TooltipBox", + "TooltipBoxOptions", + "TooltipDelay", + "TooltipStyle", + "ToonShading", + "Top", + "TopHatTransform", + "ToPolarCoordinates", + "TopologicalSort", + "ToRadicals", + "ToRules", + "ToSphericalCoordinates", + "ToString", + "Total", + "TotalHeight", + "TotalLayer", + "TotalVariationFilter", + "TotalWidth", + "TouchPosition", + "TouchscreenAutoZoom", + "TouchscreenControlPlacement", + "ToUpperCase", + "Tr", + "Trace", + "TraceAbove", + "TraceAction", + "TraceBackward", + "TraceDepth", + "TraceDialog", + "TraceForward", + "TraceInternal", + "TraceLevel", + "TraceOff", + "TraceOn", + "TraceOriginal", + "TracePrint", + "TraceScan", + "TrackedSymbols", + "TrackingFunction", + "TracyWidomDistribution", + "TradingChart", + "TraditionalForm", + "TraditionalFunctionNotation", + "TraditionalNotation", + "TraditionalOrder", + "TrainingProgressCheckpointing", + "TrainingProgressFunction", + "TrainingProgressMeasurements", + "TrainingProgressReporting", + "TrainingStoppingCriterion", + "TrainingUpdateSchedule", + "TransferFunctionCancel", + "TransferFunctionExpand", + "TransferFunctionFactor", + "TransferFunctionModel", + "TransferFunctionPoles", + "TransferFunctionTransform", + "TransferFunctionZeros", + "TransformationClass", + "TransformationFunction", + "TransformationFunctions", + "TransformationMatrix", + "TransformedDistribution", + "TransformedField", + "TransformedProcess", + "TransformedRegion", + "TransitionDirection", + "TransitionDuration", + "TransitionEffect", + "TransitiveClosureGraph", + "TransitiveReductionGraph", + "Translate", + "TranslationOptions", + "TranslationTransform", + "Transliterate", + "Transparent", + "TransparentColor", + "Transpose", + "TransposeLayer", + "TrapSelection", + "TravelDirections", + "TravelDirectionsData", + "TravelDistance", + "TravelDistanceList", + "TravelMethod", + "TravelTime", + "TreeForm", + "TreeGraph", + "TreeGraphQ", + "TreePlot", + "TrendStyle", + "Triangle", + "TriangleCenter", + "TriangleConstruct", + "TriangleMeasurement", + "TriangleWave", + "TriangularDistribution", + "TriangulateMesh", + "Trig", + "TrigExpand", + "TrigFactor", + "TrigFactorList", + "Trigger", + "TrigReduce", + "TrigToExp", + "TrimmedMean", + "TrimmedVariance", + "TropicalStormData", + "True", + "TrueQ", + "TruncatedDistribution", + "TruncatedPolyhedron", + "TsallisQExponentialDistribution", + "TsallisQGaussianDistribution", + "TTest", + "Tube", + "TubeBezierCurveBox", + "TubeBezierCurveBoxOptions", + "TubeBox", + "TubeBoxOptions", + "TubeBSplineCurveBox", + "TubeBSplineCurveBoxOptions", + "Tuesday", + "TukeyLambdaDistribution", + "TukeyWindow", + "TunnelData", + "Tuples", + "TuranGraph", + "TuringMachine", + "TuttePolynomial", + "TwoWayRule", + "Typed", + "TypeSpecifier", + "UnateQ", + "Uncompress", + "UnconstrainedParameters", + "Undefined", + "UnderBar", + "Underflow", + "Underlined", + "Underoverscript", + "UnderoverscriptBox", + "UnderoverscriptBoxOptions", + "Underscript", + "UnderscriptBox", + "UnderscriptBoxOptions", + "UnderseaFeatureData", + "UndirectedEdge", + "UndirectedGraph", + "UndirectedGraphQ", + "UndoOptions", + "UndoTrackedVariables", + "Unequal", + "UnequalTo", + "Unevaluated", + "UniformDistribution", + "UniformGraphDistribution", + "UniformPolyhedron", + "UniformSumDistribution", + "Uninstall", + "Union", + "UnionedEntityClass", + "UnionPlus", + "Unique", + "UnitaryMatrixQ", + "UnitBox", + "UnitConvert", + "UnitDimensions", + "Unitize", + "UnitRootTest", + "UnitSimplify", + "UnitStep", + "UnitSystem", + "UnitTriangle", + "UnitVector", + "UnitVectorLayer", + "UnityDimensions", + "UniverseModelData", + "UniversityData", + "UnixTime", + "Unprotect", + "UnregisterExternalEvaluator", + "UnsameQ", + "UnsavedVariables", + "Unset", + "UnsetShared", + "UntrackedVariables", + "Up", + "UpArrow", + "UpArrowBar", + "UpArrowDownArrow", + "Update", + "UpdateDynamicObjects", + "UpdateDynamicObjectsSynchronous", + "UpdateInterval", + "UpdatePacletSites", + "UpdateSearchIndex", + "UpDownArrow", + "UpEquilibrium", + "UpperCaseQ", + "UpperLeftArrow", + "UpperRightArrow", + "UpperTriangularize", + "UpperTriangularMatrixQ", + "Upsample", + "UpSet", + "UpSetDelayed", + "UpTee", + "UpTeeArrow", + "UpTo", + "UpValues", + "URL", + "URLBuild", + "URLDecode", + "URLDispatcher", + "URLDownload", + "URLDownloadSubmit", + "URLEncode", + "URLExecute", + "URLExpand", + "URLFetch", + "URLFetchAsynchronous", + "URLParse", + "URLQueryDecode", + "URLQueryEncode", + "URLRead", + "URLResponseTime", + "URLSave", + "URLSaveAsynchronous", + "URLShorten", + "URLSubmit", + "UseGraphicsRange", + "UserDefinedWavelet", + "Using", + "UsingFrontEnd", + "UtilityFunction", + "V2Get", + "ValenceErrorHandling", + "ValidationLength", + "ValidationSet", + "Value", + "ValueBox", + "ValueBoxOptions", + "ValueDimensions", + "ValueForm", + "ValuePreprocessingFunction", + "ValueQ", + "Values", + "ValuesData", + "Variables", + "Variance", + "VarianceEquivalenceTest", + "VarianceEstimatorFunction", + "VarianceGammaDistribution", + "VarianceTest", + "VectorAngle", + "VectorAround", + "VectorAspectRatio", + "VectorColorFunction", + "VectorColorFunctionScaling", + "VectorDensityPlot", + "VectorGlyphData", + "VectorGreater", + "VectorGreaterEqual", + "VectorLess", + "VectorLessEqual", + "VectorMarkers", + "VectorPlot", + "VectorPlot3D", + "VectorPoints", + "VectorQ", + "VectorRange", + "Vectors", + "VectorScale", + "VectorScaling", + "VectorSizes", + "VectorStyle", + "Vee", + "Verbatim", + "Verbose", + "VerboseConvertToPostScriptPacket", + "VerificationTest", + "VerifyConvergence", + "VerifyDerivedKey", + "VerifyDigitalSignature", + "VerifyFileSignature", + "VerifyInterpretation", + "VerifySecurityCertificates", + "VerifySolutions", + "VerifyTestAssumptions", + "Version", + "VersionedPreferences", + "VersionNumber", + "VertexAdd", + "VertexCapacity", + "VertexColors", + "VertexComponent", + "VertexConnectivity", + "VertexContract", + "VertexCoordinateRules", + "VertexCoordinates", + "VertexCorrelationSimilarity", + "VertexCosineSimilarity", + "VertexCount", + "VertexCoverQ", + "VertexDataCoordinates", + "VertexDegree", + "VertexDelete", + "VertexDiceSimilarity", + "VertexEccentricity", + "VertexInComponent", + "VertexInDegree", + "VertexIndex", + "VertexJaccardSimilarity", + "VertexLabeling", + "VertexLabels", + "VertexLabelStyle", + "VertexList", + "VertexNormals", + "VertexOutComponent", + "VertexOutDegree", + "VertexQ", + "VertexRenderingFunction", + "VertexReplace", + "VertexShape", + "VertexShapeFunction", + "VertexSize", + "VertexStyle", + "VertexTextureCoordinates", + "VertexWeight", + "VertexWeightedGraphQ", + "Vertical", + "VerticalBar", + "VerticalForm", + "VerticalGauge", + "VerticalSeparator", + "VerticalSlider", + "VerticalTilde", + "Video", + "VideoEncoding", + "VideoExtractFrames", + "VideoFrameList", + "VideoFrameMap", + "VideoPause", + "VideoPlay", + "VideoQ", + "VideoStop", + "VideoStream", + "VideoStreams", + "VideoTimeSeries", + "VideoTracks", + "VideoTrim", + "ViewAngle", + "ViewCenter", + "ViewMatrix", + "ViewPoint", + "ViewPointSelectorSettings", + "ViewPort", + "ViewProjection", + "ViewRange", + "ViewVector", + "ViewVertical", + "VirtualGroupData", + "Visible", + "VisibleCell", + "VoiceStyleData", + "VoigtDistribution", + "VolcanoData", + "Volume", + "VonMisesDistribution", + "VoronoiMesh", + "WaitAll", + "WaitAsynchronousTask", + "WaitNext", + "WaitUntil", + "WakebyDistribution", + "WalleniusHypergeometricDistribution", + "WaringYuleDistribution", + "WarpingCorrespondence", + "WarpingDistance", + "WatershedComponents", + "WatsonUSquareTest", + "WattsStrogatzGraphDistribution", + "WaveletBestBasis", + "WaveletFilterCoefficients", + "WaveletImagePlot", + "WaveletListPlot", + "WaveletMapIndexed", + "WaveletMatrixPlot", + "WaveletPhi", + "WaveletPsi", + "WaveletScale", + "WaveletScalogram", + "WaveletThreshold", + "WeaklyConnectedComponents", + "WeaklyConnectedGraphComponents", + "WeaklyConnectedGraphQ", + "WeakStationarity", + "WeatherData", + "WeatherForecastData", + "WebAudioSearch", + "WebElementObject", + "WeberE", + "WebExecute", + "WebImage", + "WebImageSearch", + "WebSearch", + "WebSessionObject", + "WebSessions", + "WebWindowObject", + "Wedge", + "Wednesday", + "WeibullDistribution", + "WeierstrassE1", + "WeierstrassE2", + "WeierstrassE3", + "WeierstrassEta1", + "WeierstrassEta2", + "WeierstrassEta3", + "WeierstrassHalfPeriods", + "WeierstrassHalfPeriodW1", + "WeierstrassHalfPeriodW2", + "WeierstrassHalfPeriodW3", + "WeierstrassInvariantG2", + "WeierstrassInvariantG3", + "WeierstrassInvariants", + "WeierstrassP", + "WeierstrassPPrime", + "WeierstrassSigma", + "WeierstrassZeta", + "WeightedAdjacencyGraph", + "WeightedAdjacencyMatrix", + "WeightedData", + "WeightedGraphQ", + "Weights", + "WelchWindow", + "WheelGraph", + "WhenEvent", + "Which", + "While", + "White", + "WhiteNoiseProcess", + "WhitePoint", + "Whitespace", + "WhitespaceCharacter", + "WhittakerM", + "WhittakerW", + "WienerFilter", + "WienerProcess", + "WignerD", + "WignerSemicircleDistribution", + "WikidataData", + "WikidataSearch", + "WikipediaData", + "WikipediaSearch", + "WilksW", + "WilksWTest", + "WindDirectionData", + "WindingCount", + "WindingPolygon", + "WindowClickSelect", + "WindowElements", + "WindowFloating", + "WindowFrame", + "WindowFrameElements", + "WindowMargins", + "WindowMovable", + "WindowOpacity", + "WindowPersistentStyles", + "WindowSelected", + "WindowSize", + "WindowStatusArea", + "WindowTitle", + "WindowToolbars", + "WindowWidth", + "WindSpeedData", + "WindVectorData", + "WinsorizedMean", + "WinsorizedVariance", + "WishartMatrixDistribution", + "With", + "WolframAlpha", + "WolframAlphaDate", + "WolframAlphaQuantity", + "WolframAlphaResult", + "WolframLanguageData", + "Word", + "WordBoundary", + "WordCharacter", + "WordCloud", + "WordCount", + "WordCounts", + "WordData", + "WordDefinition", + "WordFrequency", + "WordFrequencyData", + "WordList", + "WordOrientation", + "WordSearch", + "WordSelectionFunction", + "WordSeparators", + "WordSpacings", + "WordStem", + "WordTranslation", + "WorkingPrecision", + "WrapAround", + "Write", + "WriteLine", + "WriteString", + "Wronskian", + "XMLElement", + "XMLObject", + "XMLTemplate", + "Xnor", + "Xor", + "XYZColor", + "Yellow", + "Yesterday", + "YuleDissimilarity", + "ZernikeR", + "ZeroSymmetric", + "ZeroTest", + "ZeroWidthTimes", + "Zeta", + "ZetaZero", + "ZIPCodeData", + "ZipfDistribution", + "ZoomCenter", + "ZoomFactor", + "ZTest", + "ZTransform", + "$Aborted", + "$ActivationGroupID", + "$ActivationKey", + "$ActivationUserRegistered", + "$AddOnsDirectory", + "$AllowDataUpdates", + "$AllowExternalChannelFunctions", + "$AllowInternet", + "$AssertFunction", + "$Assumptions", + "$AsynchronousTask", + "$AudioDecoders", + "$AudioEncoders", + "$AudioInputDevices", + "$AudioOutputDevices", + "$BaseDirectory", + "$BasePacletsDirectory", + "$BatchInput", + "$BatchOutput", + "$BlockchainBase", + "$BoxForms", + "$ByteOrdering", + "$CacheBaseDirectory", + "$Canceled", + "$ChannelBase", + "$CharacterEncoding", + "$CharacterEncodings", + "$CloudAccountName", + "$CloudBase", + "$CloudConnected", + "$CloudConnection", + "$CloudCreditsAvailable", + "$CloudEvaluation", + "$CloudExpressionBase", + "$CloudObjectNameFormat", + "$CloudObjectURLType", + "$CloudRootDirectory", + "$CloudSymbolBase", + "$CloudUserID", + "$CloudUserUUID", + "$CloudVersion", + "$CloudVersionNumber", + "$CloudWolframEngineVersionNumber", + "$CommandLine", + "$CompilationTarget", + "$ConditionHold", + "$ConfiguredKernels", + "$Context", + "$ContextPath", + "$ControlActiveSetting", + "$Cookies", + "$CookieStore", + "$CreationDate", + "$CurrentLink", + "$CurrentTask", + "$CurrentWebSession", + "$DataStructures", + "$DateStringFormat", + "$DefaultAudioInputDevice", + "$DefaultAudioOutputDevice", + "$DefaultFont", + "$DefaultFrontEnd", + "$DefaultImagingDevice", + "$DefaultLocalBase", + "$DefaultMailbox", + "$DefaultNetworkInterface", + "$DefaultPath", + "$DefaultProxyRules", + "$DefaultSystemCredentialStore", + "$Display", + "$DisplayFunction", + "$DistributedContexts", + "$DynamicEvaluation", + "$Echo", + "$EmbedCodeEnvironments", + "$EmbeddableServices", + "$EntityStores", + "$Epilog", + "$EvaluationCloudBase", + "$EvaluationCloudObject", + "$EvaluationEnvironment", + "$ExportFormats", + "$ExternalIdentifierTypes", + "$ExternalStorageBase", + "$Failed", + "$FinancialDataSource", + "$FontFamilies", + "$FormatType", + "$FrontEnd", + "$FrontEndSession", + "$GeoEntityTypes", + "$GeoLocation", + "$GeoLocationCity", + "$GeoLocationCountry", + "$GeoLocationPrecision", + "$GeoLocationSource", + "$HistoryLength", + "$HomeDirectory", + "$HTMLExportRules", + "$HTTPCookies", + "$HTTPRequest", + "$IgnoreEOF", + "$ImageFormattingWidth", + "$ImageResolution", + "$ImagingDevice", + "$ImagingDevices", + "$ImportFormats", + "$IncomingMailSettings", + "$InitialDirectory", + "$Initialization", + "$InitializationContexts", + "$Input", + "$InputFileName", + "$InputStreamMethods", + "$Inspector", + "$InstallationDate", + "$InstallationDirectory", + "$InterfaceEnvironment", + "$InterpreterTypes", + "$IterationLimit", + "$KernelCount", + "$KernelID", + "$Language", + "$LaunchDirectory", + "$LibraryPath", + "$LicenseExpirationDate", + "$LicenseID", + "$LicenseProcesses", + "$LicenseServer", + "$LicenseSubprocesses", + "$LicenseType", + "$Line", + "$Linked", + "$LinkSupported", + "$LoadedFiles", + "$LocalBase", + "$LocalSymbolBase", + "$MachineAddresses", + "$MachineDomain", + "$MachineDomains", + "$MachineEpsilon", + "$MachineID", + "$MachineName", + "$MachinePrecision", + "$MachineType", + "$MaxExtraPrecision", + "$MaxLicenseProcesses", + "$MaxLicenseSubprocesses", + "$MaxMachineNumber", + "$MaxNumber", + "$MaxPiecewiseCases", + "$MaxPrecision", + "$MaxRootDegree", + "$MessageGroups", + "$MessageList", + "$MessagePrePrint", + "$Messages", + "$MinMachineNumber", + "$MinNumber", + "$MinorReleaseNumber", + "$MinPrecision", + "$MobilePhone", + "$ModuleNumber", + "$NetworkConnected", + "$NetworkInterfaces", + "$NetworkLicense", + "$NewMessage", + "$NewSymbol", + "$NotebookInlineStorageLimit", + "$Notebooks", + "$NoValue", + "$NumberMarks", + "$Off", + "$OperatingSystem", + "$Output", + "$OutputForms", + "$OutputSizeLimit", + "$OutputStreamMethods", + "$Packages", + "$ParentLink", + "$ParentProcessID", + "$PasswordFile", + "$PatchLevelID", + "$Path", + "$PathnameSeparator", + "$PerformanceGoal", + "$Permissions", + "$PermissionsGroupBase", + "$PersistenceBase", + "$PersistencePath", + "$PipeSupported", + "$PlotTheme", + "$Post", + "$Pre", + "$PreferencesDirectory", + "$PreInitialization", + "$PrePrint", + "$PreRead", + "$PrintForms", + "$PrintLiteral", + "$Printout3DPreviewer", + "$ProcessID", + "$ProcessorCount", + "$ProcessorType", + "$ProductInformation", + "$ProgramName", + "$PublisherID", + "$RandomState", + "$RecursionLimit", + "$RegisteredDeviceClasses", + "$RegisteredUserName", + "$ReleaseNumber", + "$RequesterAddress", + "$RequesterWolframID", + "$RequesterWolframUUID", + "$RootDirectory", + "$ScheduledTask", + "$ScriptCommandLine", + "$ScriptInputString", + "$SecuredAuthenticationKeyTokens", + "$ServiceCreditsAvailable", + "$Services", + "$SessionID", + "$SetParentLink", + "$SharedFunctions", + "$SharedVariables", + "$SoundDisplay", + "$SoundDisplayFunction", + "$SourceLink", + "$SSHAuthentication", + "$SubtitleDecoders", + "$SubtitleEncoders", + "$SummaryBoxDataSizeLimit", + "$SuppressInputFormHeads", + "$SynchronousEvaluation", + "$SyntaxHandler", + "$System", + "$SystemCharacterEncoding", + "$SystemCredentialStore", + "$SystemID", + "$SystemMemory", + "$SystemShell", + "$SystemTimeZone", + "$SystemWordLength", + "$TemplatePath", + "$TemporaryDirectory", + "$TemporaryPrefix", + "$TestFileName", + "$TextStyle", + "$TimedOut", + "$TimeUnit", + "$TimeZone", + "$TimeZoneEntity", + "$TopDirectory", + "$TraceOff", + "$TraceOn", + "$TracePattern", + "$TracePostAction", + "$TracePreAction", + "$UnitSystem", + "$Urgent", + "$UserAddOnsDirectory", + "$UserAgentLanguages", + "$UserAgentMachine", + "$UserAgentName", + "$UserAgentOperatingSystem", + "$UserAgentString", + "$UserAgentVersion", + "$UserBaseDirectory", + "$UserBasePacletsDirectory", + "$UserDocumentsDirectory", + "$Username", + "$UserName", + "$UserURLBase", + "$Version", + "$VersionNumber", + "$VideoDecoders", + "$VideoEncoders", + "$VoiceStyles", + "$WolframDocumentsDirectory", + "$WolframID", + "$WolframUUID" +]; + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Wolfram Language +Description: The Wolfram Language is the programming language used in Wolfram Mathematica, a modern technical computing system spanning most areas of technical computing. +Authors: Patrick Scheibe , Robert Jacobson +Website: https://www.wolfram.com/mathematica/ +Category: scientific +*/ + +/** @type LanguageFn */ +function mathematica(hljs) { + /* + This rather scary looking matching of Mathematica numbers is carefully explained by Robert Jacobson here: + https://wltools.github.io/LanguageSpec/Specification/Syntax/Number-representations/ + */ + const BASE_RE = /([2-9]|[1-2]\d|[3][0-5])\^\^/; + const BASE_DIGITS_RE = /(\w*\.\w+|\w+\.\w*|\w+)/; + const NUMBER_RE = /(\d*\.\d+|\d+\.\d*|\d+)/; + const BASE_NUMBER_RE = either(concat(BASE_RE, BASE_DIGITS_RE), NUMBER_RE); + + const ACCURACY_RE = /``[+-]?(\d*\.\d+|\d+\.\d*|\d+)/; + const PRECISION_RE = /`([+-]?(\d*\.\d+|\d+\.\d*|\d+))?/; + const APPROXIMATE_NUMBER_RE = either(ACCURACY_RE, PRECISION_RE); + + const SCIENTIFIC_NOTATION_RE = /\*\^[+-]?\d+/; + + const MATHEMATICA_NUMBER_RE = concat( + BASE_NUMBER_RE, + optional(APPROXIMATE_NUMBER_RE), + optional(SCIENTIFIC_NOTATION_RE) + ); + + const NUMBERS = { + className: 'number', + relevance: 0, + begin: MATHEMATICA_NUMBER_RE + }; + + const SYMBOL_RE = /[a-zA-Z$][a-zA-Z0-9$]*/; + const SYSTEM_SYMBOLS_SET = new Set(SYSTEM_SYMBOLS); + /** @type {Mode} */ + const SYMBOLS = { + variants: [ + { + className: 'builtin-symbol', + begin: SYMBOL_RE, + // for performance out of fear of regex.either(...Mathematica.SYSTEM_SYMBOLS) + "on:begin": (match, response) => { + if (!SYSTEM_SYMBOLS_SET.has(match[0])) response.ignoreMatch(); + } + }, + { + className: 'symbol', + relevance: 0, + begin: SYMBOL_RE + } + ] + }; + + const NAMED_CHARACTER = { + className: 'named-character', + begin: /\\\[[$a-zA-Z][$a-zA-Z0-9]+\]/ + }; + + const OPERATORS = { + className: 'operator', + relevance: 0, + begin: /[+\-*/,;.:@~=><&|_`'^?!%]+/ + }; + const PATTERNS = { + className: 'pattern', + relevance: 0, + begin: /([a-zA-Z$][a-zA-Z0-9$]*)?_+([a-zA-Z$][a-zA-Z0-9$]*)?/ + }; + + const SLOTS = { + className: 'slot', + relevance: 0, + begin: /#[a-zA-Z$][a-zA-Z0-9$]*|#+[0-9]?/ + }; + + const BRACES = { + className: 'brace', + relevance: 0, + begin: /[[\](){}]/ + }; + + const MESSAGES = { + className: 'message-name', + relevance: 0, + begin: concat("::", SYMBOL_RE) + }; + + return { + name: 'Mathematica', + aliases: [ + 'mma', + 'wl' + ], + classNameAliases: { + brace: 'punctuation', + pattern: 'type', + slot: 'type', + symbol: 'variable', + 'named-character': 'variable', + 'builtin-symbol': 'built_in', + 'message-name': 'string' + }, + contains: [ + hljs.COMMENT(/\(\*/, /\*\)/, { + contains: [ 'self' ] + }), + PATTERNS, + SLOTS, + MESSAGES, + SYMBOLS, + NAMED_CHARACTER, + hljs.QUOTE_STRING_MODE, + NUMBERS, + OPERATORS, + BRACES + ] + }; +} + +module.exports = mathematica; + + +/***/ }), + +/***/ 91313: +/***/ ((module) => { + +/* +Language: Matlab +Author: Denis Bardadym +Contributors: Eugene Nizhibitsky , Egor Rogov +Website: https://www.mathworks.com/products/matlab.html +Category: scientific +*/ + +/* + Formal syntax is not published, helpful link: + https://github.com/kornilova-l/matlab-IntelliJ-plugin/blob/master/src/main/grammar/Matlab.bnf +*/ +function matlab(hljs) { + + var TRANSPOSE_RE = '(\'|\\.\')+'; + var TRANSPOSE = { + relevance: 0, + contains: [ + { begin: TRANSPOSE_RE } + ] + }; + + return { + name: 'Matlab', + keywords: { + keyword: + 'arguments break case catch classdef continue else elseif end enumeration events for function ' + + 'global if methods otherwise parfor persistent properties return spmd switch try while', + built_in: + 'sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan ' + + 'atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot ' + + 'cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog ' + + 'realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal ' + + 'cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli ' + + 'besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma ' + + 'gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms ' + + 'nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones ' + + 'eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ' + + 'ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril ' + + 'triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute ' + + 'shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i|0 inf nan ' + + 'isnan isinf isfinite j|0 why compan gallery hadamard hankel hilb invhilb magic pascal ' + + 'rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table ' + + 'readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun ' + + 'legend intersect ismember procrustes hold num2cell ' + }, + illegal: '(//|"|#|/\\*|\\s+/\\w+)', + contains: [ + { + className: 'function', + beginKeywords: 'function', end: '$', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'params', + variants: [ + {begin: '\\(', end: '\\)'}, + {begin: '\\[', end: '\\]'} + ] + } + ] + }, + { + className: 'built_in', + begin: /true|false/, + relevance: 0, + starts: TRANSPOSE + }, + { + begin: '[a-zA-Z][a-zA-Z_0-9]*' + TRANSPOSE_RE, + relevance: 0 + }, + { + className: 'number', + begin: hljs.C_NUMBER_RE, + relevance: 0, + starts: TRANSPOSE + }, + { + className: 'string', + begin: '\'', end: '\'', + contains: [ + hljs.BACKSLASH_ESCAPE, + {begin: '\'\''}] + }, + { + begin: /\]|\}|\)/, + relevance: 0, + starts: TRANSPOSE + }, + { + className: 'string', + begin: '"', end: '"', + contains: [ + hljs.BACKSLASH_ESCAPE, + {begin: '""'} + ], + starts: TRANSPOSE + }, + hljs.COMMENT('^\\s*%\\{\\s*$', '^\\s*%\\}\\s*$'), + hljs.COMMENT('%', '$') + ] + }; +} + +module.exports = matlab; + + +/***/ }), + +/***/ 89887: +/***/ ((module) => { + +/* +Language: Maxima +Author: Robert Dodier +Website: http://maxima.sourceforge.net +Category: scientific +*/ + +function maxima(hljs) { + const KEYWORDS = + 'if then else elseif for thru do while unless step in and or not'; + const LITERALS = + 'true false unknown inf minf ind und %e %i %pi %phi %gamma'; + const BUILTIN_FUNCTIONS = + ' abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate' + + ' addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix' + + ' adjoin adjoint af agd airy airy_ai airy_bi airy_dai airy_dbi algsys alg_type' + + ' alias allroots alphacharp alphanumericp amortization %and annuity_fv' + + ' annuity_pv antid antidiff AntiDifference append appendfile apply apply1 apply2' + + ' applyb1 apropos args arit_amortization arithmetic arithsum array arrayapply' + + ' arrayinfo arraymake arraysetapply ascii asec asech asin asinh askinteger' + + ' asksign assoc assoc_legendre_p assoc_legendre_q assume assume_external_byte_order' + + ' asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method' + + ' av average_degree backtrace bars barsplot barsplot_description base64 base64_decode' + + ' bashindices batch batchload bc2 bdvac belln benefit_cost bern bernpoly bernstein_approx' + + ' bernstein_expand bernstein_poly bessel bessel_i bessel_j bessel_k bessel_simplify' + + ' bessel_y beta beta_incomplete beta_incomplete_generalized beta_incomplete_regularized' + + ' bezout bfallroots bffac bf_find_root bf_fmin_cobyla bfhzeta bfloat bfloatp' + + ' bfpsi bfpsi0 bfzeta biconnected_components bimetric binomial bipartition' + + ' block blockmatrixp bode_gain bode_phase bothcoef box boxplot boxplot_description' + + ' break bug_report build_info|10 buildq build_sample burn cabs canform canten' + + ' cardinality carg cartan cartesian_product catch cauchy_matrix cbffac cdf_bernoulli' + + ' cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform' + + ' cdf_exp cdf_f cdf_gamma cdf_general_finite_discrete cdf_geometric cdf_gumbel' + + ' cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial' + + ' cdf_noncentral_chi2 cdf_noncentral_student_t cdf_normal cdf_pareto cdf_poisson' + + ' cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay' + + ' ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic' + + ' cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2' + + ' charlist charp charpoly chdir chebyshev_t chebyshev_u checkdiv check_overlaps' + + ' chinese cholesky christof chromatic_index chromatic_number cint circulant_graph' + + ' clear_edge_weight clear_rules clear_vertex_label clebsch_gordan clebsch_graph' + + ' clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse' + + ' collectterms columnop columnspace columnswap columnvector combination combine' + + ' comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph' + + ' complete_graph complex_number_p components compose_functions concan concat' + + ' conjugate conmetderiv connected_components connect_vertices cons constant' + + ' constantp constituent constvalue cont2part content continuous_freq contortion' + + ' contour_plot contract contract_edge contragrad contrib_ode convert coord' + + ' copy copy_file copy_graph copylist copymatrix cor cos cosh cot coth cov cov1' + + ' covdiff covect covers crc24sum create_graph create_list csc csch csetup cspline' + + ' ctaylor ct_coordsys ctransform ctranspose cube_graph cuboctahedron_graph' + + ' cunlisp cv cycle_digraph cycle_graph cylindrical days360 dblint deactivate' + + ' declare declare_constvalue declare_dimensions declare_fundamental_dimensions' + + ' declare_fundamental_units declare_qty declare_translated declare_unit_conversion' + + ' declare_units declare_weights decsym defcon define define_alt_display define_variable' + + ' defint defmatch defrule defstruct deftaylor degree_sequence del delete deleten' + + ' delta demo demoivre denom depends derivdegree derivlist describe desolve' + + ' determinant dfloat dgauss_a dgauss_b dgeev dgemm dgeqrf dgesv dgesvd diag' + + ' diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export' + + ' dimacs_import dimension dimensionless dimensions dimensions_as_list direct' + + ' directory discrete_freq disjoin disjointp disolate disp dispcon dispform' + + ' dispfun dispJordan display disprule dispterms distrib divide divisors divsum' + + ' dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart' + + ' draw draw2d draw3d drawdf draw_file draw_graph dscalar echelon edge_coloring' + + ' edge_connectivity edges eigens_by_jacobi eigenvalues eigenvectors eighth' + + ' einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome' + + ' ele2pui elem elementp elevation_grid elim elim_allbut eliminate eliminate_using' + + ' ellipse elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi' + + ' ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp' + + ' equiv_classes erf erfc erf_generalized erfi errcatch error errormsg errors' + + ' euler ev eval_string evenp every evolution evolution2d evundiff example exp' + + ' expand expandwrt expandwrt_factored expint expintegral_chi expintegral_ci' + + ' expintegral_e expintegral_e1 expintegral_ei expintegral_e_simplify expintegral_li' + + ' expintegral_shi expintegral_si explicit explose exponentialize express expt' + + ' exsec extdiff extract_linear_equations extremal_subset ezgcd %f f90 facsum' + + ' factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements' + + ' fast_linsolve fasttimes featurep fernfale fft fib fibtophi fifth filename_merge' + + ' file_search file_type fillarray findde find_root find_root_abs find_root_error' + + ' find_root_rel first fix flatten flength float floatnump floor flower_snark' + + ' flush flush1deriv flushd flushnd flush_output fmin_cobyla forget fortran' + + ' fourcos fourexpand fourier fourier_elim fourint fourintcos fourintsin foursimp' + + ' foursin fourth fposition frame_bracket freeof freshline fresnel_c fresnel_s' + + ' from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp' + + ' fullratsubst fullsetify funcsolve fundamental_dimensions fundamental_units' + + ' fundef funmake funp fv g0 g1 gamma gamma_greek gamma_incomplete gamma_incomplete_generalized' + + ' gamma_incomplete_regularized gauss gauss_a gauss_b gaussprob gcd gcdex gcdivide' + + ' gcfac gcfactor gd generalized_lambert_w genfact gen_laguerre genmatrix gensym' + + ' geo_amortization geo_annuity_fv geo_annuity_pv geomap geometric geometric_mean' + + ' geosum get getcurrentdirectory get_edge_weight getenv get_lu_factors get_output_stream_string' + + ' get_pixel get_plot_option get_tex_environment get_tex_environment_default' + + ' get_vertex_label gfactor gfactorsum ggf girth global_variances gn gnuplot_close' + + ' gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum' + + ' gr2d gr3d gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import' + + ' graph_center graph_charpoly graph_eigenvalues graph_flow graph_order graph_periphery' + + ' graph_product graph_size graph_union great_rhombicosidodecahedron_graph great_rhombicuboctahedron_graph' + + ' grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path' + + ' hankel hankel_1 hankel_2 harmonic harmonic_mean hav heawood_graph hermite' + + ' hessian hgfred hilbertmap hilbert_matrix hipow histogram histogram_description' + + ' hodge horner hypergeometric i0 i1 %ibes ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph' + + ' icosidodecahedron_graph icurvature ident identfor identity idiff idim idummy' + + ' ieqn %if ifactors iframes ifs igcdex igeodesic_coords ilt image imagpart' + + ' imetric implicit implicit_derivative implicit_plot indexed_tensor indices' + + ' induced_subgraph inferencep inference_result infix info_display init_atensor' + + ' init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions' + + ' integrate intersect intersection intervalp intopois intosum invariant1 invariant2' + + ' inverse_fft inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc' + + ' inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns' + + ' inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_adjoint' + + ' invert_by_lu inv_mod irr is is_biconnected is_bipartite is_connected is_digraph' + + ' is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate' + + ' isomorphism is_planar isqrt isreal_p is_sconnected is_tree is_vertex_in_graph' + + ' items_inference %j j0 j1 jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc' + + ' jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd' + + ' jacobi_sn JF jn join jordan julia julia_set julia_sin %k kdels kdelta kill' + + ' killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis' + + ' kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform' + + ' kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_general_finite_discrete' + + ' kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace' + + ' kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_noncentral_chi2' + + ' kurtosis_noncentral_student_t kurtosis_normal kurtosis_pareto kurtosis_poisson' + + ' kurtosis_rayleigh kurtosis_student_t kurtosis_weibull label labels lagrange' + + ' laguerre lambda lambert_w laplace laplacian_matrix last lbfgs lc2kdt lcharp' + + ' lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length' + + ' let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit' + + ' Lindstedt linear linearinterpol linear_program linear_regression line_graph' + + ' linsolve listarray list_correlations listify list_matrix_entries list_nc_monomials' + + ' listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry' + + ' log logcontract log_gamma lopow lorentz_gauge lowercasep lpart lratsubst' + + ' lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact' + + ' lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub' + + ' lucas lu_factor %m macroexpand macroexpand1 make_array makebox makefact makegamma' + + ' make_graph make_level_picture makelist makeOrders make_poly_continent make_poly_country' + + ' make_polygon make_random_state make_rgb_picture makeset make_string_input_stream' + + ' make_string_output_stream make_transform mandelbrot mandelbrot_set map mapatom' + + ' maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mathml_display' + + ' mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker' + + ' max max_clique max_degree max_flow maximize_lp max_independent_set max_matching' + + ' maybe md5sum mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform' + + ' mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_general_finite_discrete' + + ' mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic' + + ' mean_lognormal mean_negative_binomial mean_noncentral_chi2 mean_noncentral_student_t' + + ' mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull' + + ' median median_deviation member mesh metricexpandall mgf1_sha1 min min_degree' + + ' min_edge_cut minfactorial minimalPoly minimize_lp minimum_spanning_tree minor' + + ' minpack_lsquares minpack_solve min_vertex_cover min_vertex_cut mkdir mnewton' + + ' mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions' + + ' multibernstein_poly multi_display_for_texinfo multi_elem multinomial multinomial_coeff' + + ' multi_orbit multiplot_mode multi_pui multsym multthru mycielski_graph nary' + + ' natural_unit nc_degree ncexpt ncharpoly negative_picture neighbors new newcontext' + + ' newdet new_graph newline newton new_variable next_prime nicedummies niceindices' + + ' ninth nofix nonarray noncentral_moment nonmetricity nonnegintegerp nonscalarp' + + ' nonzeroandfreeof notequal nounify nptetrad npv nroots nterms ntermst' + + ' nthroot nullity nullspace num numbered_boundaries numberp number_to_octets' + + ' num_distinct_partitions numerval numfactor num_partitions nusum nzeta nzetai' + + ' nzetar octets_to_number octets_to_oid odd_girth oddp ode2 ode_check odelin' + + ' oid_to_octets op opena opena_binary openr openr_binary openw openw_binary' + + ' operatorp opsubst optimize %or orbit orbits ordergreat ordergreatp orderless' + + ' orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap' + + ' out_neighbors outofpois pade parabolic_cylinder_d parametric parametric_surface' + + ' parg parGosper parse_string parse_timedate part part2cont partfrac partition' + + ' partition_set partpol path_digraph path_graph pathname_directory pathname_name' + + ' pathname_type pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform' + + ' pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_general_finite_discrete' + + ' pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal' + + ' pdf_negative_binomial pdf_noncentral_chi2 pdf_noncentral_student_t pdf_normal' + + ' pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t' + + ' pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph' + + ' petrov pickapart picture_equalp picturep piechart piechart_description planar_embedding' + + ' playback plog plot2d plot3d plotdf ploteq plsquares pochhammer points poisdiff' + + ' poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polar' + + ' polarform polartorect polar_to_xy poly_add poly_buchberger poly_buchberger_criterion' + + ' poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal' + + ' poly_exact_divide poly_expand poly_expt poly_gcd polygon poly_grobner poly_grobner_equal' + + ' poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation' + + ' poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm' + + ' poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form' + + ' poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part' + + ' poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension' + + ' poly_s_polynomial poly_subtract polytocompanion pop postfix potential power_mod' + + ' powerseries powerset prefix prev_prime primep primes principal_components' + + ' print printf printfile print_graph printpois printprops prodrac product properties' + + ' propvars psi psubst ptriangularize pui pui2comp pui2ele pui2polynome pui_direct' + + ' puireduc push put pv qput qrange qty quad_control quad_qag quad_qagi quad_qagp' + + ' quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quadrilateral quantile' + + ' quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2' + + ' quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f' + + ' quantile_gamma quantile_general_finite_discrete quantile_geometric quantile_gumbel' + + ' quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal' + + ' quantile_negative_binomial quantile_noncentral_chi2 quantile_noncentral_student_t' + + ' quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t' + + ' quantile_weibull quartile_skewness quit qunit quotient racah_v racah_w radcan' + + ' radius random random_bernoulli random_beta random_binomial random_bipartite_graph' + + ' random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform' + + ' random_exp random_f random_gamma random_general_finite_discrete random_geometric' + + ' random_graph random_graph1 random_gumbel random_hypergeometric random_laplace' + + ' random_logistic random_lognormal random_negative_binomial random_network' + + ' random_noncentral_chi2 random_noncentral_student_t random_normal random_pareto' + + ' random_permutation random_poisson random_rayleigh random_regular_graph random_student_t' + + ' random_tournament random_tree random_weibull range rank rat ratcoef ratdenom' + + ' ratdiff ratdisrep ratexpand ratinterpol rational rationalize ratnumer ratnump' + + ' ratp ratsimp ratsubst ratvars ratweight read read_array read_binary_array' + + ' read_binary_list read_binary_matrix readbyte readchar read_hashed_array readline' + + ' read_list read_matrix read_nested_list readonly read_xpm real_imagpart_to_conjugate' + + ' realpart realroots rearray rectangle rectform rectform_log_if_constant recttopolar' + + ' rediff reduce_consts reduce_order region region_boundaries region_boundaries_plus' + + ' rem remainder remarray rembox remcomps remcon remcoord remfun remfunction' + + ' remlet remove remove_constvalue remove_dimensions remove_edge remove_fundamental_dimensions' + + ' remove_fundamental_units remove_plot_option remove_vertex rempart remrule' + + ' remsym remvalue rename rename_file reset reset_displays residue resolvante' + + ' resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein' + + ' resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer' + + ' rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann' + + ' rinvariant risch rk rmdir rncombine romberg room rootscontract round row' + + ' rowop rowswap rreduce run_testsuite %s save saving scalarp scaled_bessel_i' + + ' scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot scatterplot_description' + + ' scene schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second' + + ' sequal sequalignore set_alt_display setdifference set_draw_defaults set_edge_weight' + + ' setelmx setequalp setify setp set_partitions set_plot_option set_prompt set_random_state' + + ' set_tex_environment set_tex_environment_default setunits setup_autoload set_up_dot_simplifications' + + ' set_vertex_label seventh sexplode sf sha1sum sha256sum shortest_path shortest_weighted_path' + + ' show showcomps showratvars sierpinskiale sierpinskimap sign signum similaritytransform' + + ' simp_inequality simplify_sum simplode simpmetderiv simtran sin sinh sinsert' + + ' sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial' + + ' skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp' + + ' skewness_f skewness_gamma skewness_general_finite_discrete skewness_geometric' + + ' skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic' + + ' skewness_lognormal skewness_negative_binomial skewness_noncentral_chi2 skewness_noncentral_student_t' + + ' skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t' + + ' skewness_weibull slength smake small_rhombicosidodecahedron_graph small_rhombicuboctahedron_graph' + + ' smax smin smismatch snowmap snub_cube_graph snub_dodecahedron_graph solve' + + ' solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export' + + ' sparse6_import specint spherical spherical_bessel_j spherical_bessel_y spherical_hankel1' + + ' spherical_hankel2 spherical_harmonic spherical_to_xyz splice split sposition' + + ' sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus' + + ' ssubst ssubstfirst staircase standardize standardize_inverse_trig starplot' + + ' starplot_description status std std1 std_bernoulli std_beta std_binomial' + + ' std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma' + + ' std_general_finite_discrete std_geometric std_gumbel std_hypergeometric std_laplace' + + ' std_logistic std_lognormal std_negative_binomial std_noncentral_chi2 std_noncentral_student_t' + + ' std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull' + + ' stemplot stirling stirling1 stirling2 strim striml strimr string stringout' + + ' stringp strong_components struve_h struve_l sublis sublist sublist_indices' + + ' submatrix subsample subset subsetp subst substinpart subst_parallel substpart' + + ' substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext' + + ' symbolp symmdifference symmetricp system take_channel take_inference tan' + + ' tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract' + + ' tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference' + + ' test_normality test_proportion test_proportions_difference test_rank_sum' + + ' test_sign test_signed_rank test_variance test_variance_ratio tex tex1 tex_display' + + ' texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter' + + ' toeplitz tokens to_lisp topological_sort to_poly to_poly_solve totaldisrep' + + ' totalfourier totient tpartpol trace tracematrix trace_options transform_sample' + + ' translate translate_file transpose treefale tree_reduce treillis treinat' + + ' triangle triangularize trigexpand trigrat trigreduce trigsimp trunc truncate' + + ' truncated_cube_graph truncated_dodecahedron_graph truncated_icosahedron_graph' + + ' truncated_tetrahedron_graph tr_warnings_get tube tutte_graph ueivects uforget' + + ' ultraspherical underlying_graph undiff union unique uniteigenvectors unitp' + + ' units unit_step unitvector unorder unsum untellrat untimer' + + ' untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli' + + ' var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform' + + ' var_exp var_f var_gamma var_general_finite_discrete var_geometric var_gumbel' + + ' var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial' + + ' var_noncentral_chi2 var_noncentral_student_t var_normal var_pareto var_poisson' + + ' var_rayleigh var_student_t var_weibull vector vectorpotential vectorsimp' + + ' verbify vers vertex_coloring vertex_connectivity vertex_degree vertex_distance' + + ' vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle' + + ' vertices_to_path %w weyl wheel_graph wiener_index wigner_3j wigner_6j' + + ' wigner_9j with_stdout write_binary_data writebyte write_data writefile wronskian' + + ' xreduce xthru %y Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta' + + ' zgeev zheev zlange zn_add_table zn_carmichael_lambda zn_characteristic_factors' + + ' zn_determinant zn_factor_generators zn_invert_by_lu zn_log zn_mult_table' + + ' absboxchar activecontexts adapt_depth additive adim aform algebraic' + + ' algepsilon algexact aliases allbut all_dotsimp_denoms allocation allsym alphabetic' + + ' animation antisymmetric arrays askexp assume_pos assume_pos_pred assumescalar' + + ' asymbol atomgrad atrig1 axes axis_3d axis_bottom axis_left axis_right axis_top' + + ' azimuth background background_color backsubst berlefact bernstein_explicit' + + ' besselexpand beta_args_sum_to_integer beta_expand bftorat bftrunc bindtest' + + ' border boundaries_array box boxchar breakup %c capping cauchysum cbrange' + + ' cbtics center cflength cframe_flag cnonmet_flag color color_bar color_bar_tics' + + ' colorbox columns commutative complex cone context contexts contour contour_levels' + + ' cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp' + + ' cube current_let_rule_package cylinder data_file_name debugmode decreasing' + + ' default_let_rule_package delay dependencies derivabbrev derivsubst detout' + + ' diagmetric diff dim dimensions dispflag display2d|10 display_format_internal' + + ' distribute_over doallmxops domain domxexpt domxmxops domxnctimes dontfactor' + + ' doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules' + + ' dotdistrib dotexptsimp dotident dotscrules draw_graph_program draw_realpart' + + ' edge_color edge_coloring edge_partition edge_type edge_width %edispflag' + + ' elevation %emode endphi endtheta engineering_format_floats enhanced3d %enumer' + + ' epsilon_lp erfflag erf_representation errormsg error_size error_syms error_type' + + ' %e_to_numlog eval even evenfun evflag evfun ev_point expandwrt_denom expintexpand' + + ' expintrep expon expop exptdispflag exptisolate exptsubst facexpand facsum_combine' + + ' factlim factorflag factorial_expand factors_only fb feature features' + + ' file_name file_output_append file_search_demo file_search_lisp file_search_maxima|10' + + ' file_search_tests file_search_usage file_type_lisp file_type_maxima|10 fill_color' + + ' fill_density filled_func fixed_vertices flipflag float2bf font font_size' + + ' fortindent fortspaces fpprec fpprintprec functions gamma_expand gammalim' + + ' gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gnuplot_command' + + ' gnuplot_curve_styles gnuplot_curve_titles gnuplot_default_term_command gnuplot_dumb_term_command' + + ' gnuplot_file_args gnuplot_file_name gnuplot_out_file gnuplot_pdf_term_command' + + ' gnuplot_pm3d gnuplot_png_term_command gnuplot_postamble gnuplot_preamble' + + ' gnuplot_ps_term_command gnuplot_svg_term_command gnuplot_term gnuplot_view_args' + + ' Gosper_in_Zeilberger gradefs grid grid2d grind halfangles head_angle head_both' + + ' head_length head_type height hypergeometric_representation %iargs ibase' + + ' icc1 icc2 icounter idummyx ieqnprint ifb ifc1 ifc2 ifg ifgi ifr iframe_bracket_form' + + ' ifri igeowedge_flag ikt1 ikt2 imaginary inchar increasing infeval' + + ' infinity inflag infolists inm inmc1 inmc2 intanalysis integer integervalued' + + ' integrate_use_rootsof integration_constant integration_constant_counter interpolate_color' + + ' intfaclim ip_grid ip_grid_in irrational isolate_wrt_times iterations itr' + + ' julia_parameter %k1 %k2 keepfloat key key_pos kinvariant kt label label_alignment' + + ' label_orientation labels lassociative lbfgs_ncorrections lbfgs_nfeval_max' + + ' leftjust legend letrat let_rule_packages lfg lg lhospitallim limsubst linear' + + ' linear_solver linechar linel|10 linenum line_type linewidth line_width linsolve_params' + + ' linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar load_pathname' + + ' loadprint logabs logarc logcb logconcoeffp logexpand lognegint logsimp logx' + + ' logx_secondary logy logy_secondary logz lriem m1pbranch macroexpansion macros' + + ' mainvar manual_demo maperror mapprint matrix_element_add matrix_element_mult' + + ' matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir|10 maxima_userdir|10' + + ' maxnegex MAX_ORD maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint' + + ' maxtayorder mesh_lines_color method mod_big_prime mode_check_errorp' + + ' mode_checkp mode_check_warnp mod_test mod_threshold modular_linear_solver' + + ' modulus multiplicative multiplicities myoptions nary negdistrib negsumdispflag' + + ' newline newtonepsilon newtonmaxiter nextlayerfactor niceindicespref nm nmc' + + ' noeval nolabels nonegative_lp noninteger nonscalar noun noundisp nouns np' + + ' npi nticks ntrig numer numer_pbranch obase odd oddfun opacity opproperties' + + ' opsubst optimprefix optionset orientation origin orthopoly_returns_intervals' + + ' outative outchar packagefile palette partswitch pdf_file pfeformat phiresolution' + + ' %piargs piece pivot_count_sx pivot_max_sx plot_format plot_options plot_realpart' + + ' png_file pochhammer_max_index points pointsize point_size points_joined point_type' + + ' poislim poisson poly_coefficient_ring poly_elimination_order polyfactor poly_grobner_algorithm' + + ' poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list' + + ' poly_secondary_elimination_order poly_top_reduction_only posfun position' + + ' powerdisp pred prederror primep_number_of_tests product_use_gamma program' + + ' programmode promote_float_to_bigfloat prompt proportional_axes props psexpand' + + ' ps_file radexpand radius radsubstflag rassociative ratalgdenom ratchristof' + + ' ratdenomdivide rateinstein ratepsilon ratfac rational ratmx ratprint ratriemann' + + ' ratsimpexpons ratvarswitch ratweights ratweyl ratwtlvl real realonly redraw' + + ' refcheck resolution restart resultant ric riem rmxchar %rnum_list rombergabs' + + ' rombergit rombergmin rombergtol rootsconmode rootsepsilon run_viewer same_xy' + + ' same_xyz savedef savefactors scalar scalarmatrixp scale scale_lp setcheck' + + ' setcheckbreak setval show_edge_color show_edges show_edge_type show_edge_width' + + ' show_id show_label showtime show_vertex_color show_vertex_size show_vertex_type' + + ' show_vertices show_weight simp simplified_output simplify_products simpproduct' + + ' simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solvenullwarn' + + ' solveradcan solvetrigwarn space sparse sphere spring_embedding_depth sqrtdispflag' + + ' stardisp startphi starttheta stats_numer stringdisp structures style sublis_apply_lambda' + + ' subnumsimp sumexpand sumsplitfact surface surface_hide svg_file symmetric' + + ' tab taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials' + + ' tensorkill terminal testsuite_files thetaresolution timer_devalue title tlimswitch' + + ' tr track transcompile transform transform_xy translate_fast_arrays transparent' + + ' transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex' + + ' tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign' + + ' trivial_solutions tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars' + + ' tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode' + + ' tr_warn_undeclared tr_warn_undefined_variable tstep ttyoff tube_extremes' + + ' ufg ug %unitexpand unit_vectors uric uriem use_fast_arrays user_preamble' + + ' usersetunits values vect_cross verbose vertex_color vertex_coloring vertex_partition' + + ' vertex_size vertex_type view warnings weyl width windowname windowtitle wired_surface' + + ' wireframe xaxis xaxis_color xaxis_secondary xaxis_type xaxis_width xlabel' + + ' xlabel_secondary xlength xrange xrange_secondary xtics xtics_axis xtics_rotate' + + ' xtics_rotate_secondary xtics_secondary xtics_secondary_axis xu_grid x_voxel' + + ' xy_file xyplane xy_scale yaxis yaxis_color yaxis_secondary yaxis_type yaxis_width' + + ' ylabel ylabel_secondary ylength yrange yrange_secondary ytics ytics_axis' + + ' ytics_rotate ytics_rotate_secondary ytics_secondary ytics_secondary_axis' + + ' yv_grid y_voxel yx_ratio zaxis zaxis_color zaxis_type zaxis_width zeroa zerob' + + ' zerobern zeta%pi zlabel zlabel_rotate zlength zmin zn_primroot_limit zn_primroot_pretest'; + const SYMBOLS = '_ __ %|0 %%|0'; + + return { + name: 'Maxima', + keywords: { + $pattern: '[A-Za-z_%][0-9A-Za-z_%]*', + keyword: KEYWORDS, + literal: LITERALS, + built_in: BUILTIN_FUNCTIONS, + symbol: SYMBOLS + }, + contains: [ + { + className: 'comment', + begin: '/\\*', + end: '\\*/', + contains: [ 'self' ] + }, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + relevance: 0, + variants: [ + { + // float number w/ exponent + // hmm, I wonder if we ought to include other exponent markers? + begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Ee][-+]?\\d+\\b' + }, + { + // bigfloat number + begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Bb][-+]?\\d+\\b', + relevance: 10 + }, + { + // float number w/out exponent + // Doesn't seem to recognize floats which start with '.' + begin: '\\b(\\.\\d+|\\d+\\.\\d+)\\b' + }, + { + // integer in base up to 36 + // Doesn't seem to recognize integers which end with '.' + begin: '\\b(\\d+|0[0-9A-Za-z]+)\\.?\\b' + } + ] + } + ], + illegal: /@/ + }; +} + +module.exports = maxima; + + +/***/ }), + +/***/ 62872: +/***/ ((module) => { + +/* +Language: MEL +Description: Maya Embedded Language +Author: Shuen-Huei Guan +Website: http://www.autodesk.com/products/autodesk-maya/overview +Category: graphics +*/ + +function mel(hljs) { + return { + name: 'MEL', + keywords: + 'int float string vector matrix if else switch case default while do for in break ' + + 'continue global proc return about abs addAttr addAttributeEditorNodeHelp addDynamic ' + + 'addNewShelfTab addPP addPanelCategory addPrefixToName advanceToNextDrivenKey ' + + 'affectedNet affects aimConstraint air alias aliasAttr align alignCtx alignCurve ' + + 'alignSurface allViewFit ambientLight angle angleBetween animCone animCurveEditor ' + + 'animDisplay animView annotate appendStringArray applicationName applyAttrPreset ' + + 'applyTake arcLenDimContext arcLengthDimension arclen arrayMapper art3dPaintCtx ' + + 'artAttrCtx artAttrPaintVertexCtx artAttrSkinPaintCtx artAttrTool artBuildPaintMenu ' + + 'artFluidAttrCtx artPuttyCtx artSelectCtx artSetPaintCtx artUserPaintCtx assignCommand ' + + 'assignInputDevice assignViewportFactories attachCurve attachDeviceAttr attachSurface ' + + 'attrColorSliderGrp attrCompatibility attrControlGrp attrEnumOptionMenu ' + + 'attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp ' + + 'attrPresetEditWin attributeExists attributeInfo attributeMenu attributeQuery ' + + 'autoKeyframe autoPlace bakeClip bakeFluidShading bakePartialHistory bakeResults ' + + 'bakeSimulation basename basenameEx batchRender bessel bevel bevelPlus binMembership ' + + 'bindSkin blend2 blendShape blendShapeEditor blendShapePanel blendTwoAttr blindDataType ' + + 'boneLattice boundary boxDollyCtx boxZoomCtx bufferCurve buildBookmarkMenu ' + + 'buildKeyframeMenu button buttonManip CBG cacheFile cacheFileCombine cacheFileMerge ' + + 'cacheFileTrack camera cameraView canCreateManip canvas capitalizeString catch ' + + 'catchQuiet ceil changeSubdivComponentDisplayLevel changeSubdivRegion channelBox ' + + 'character characterMap characterOutlineEditor characterize chdir checkBox checkBoxGrp ' + + 'checkDefaultRenderGlobals choice circle circularFillet clamp clear clearCache clip ' + + 'clipEditor clipEditorCurrentTimeCtx clipSchedule clipSchedulerOutliner clipTrimBefore ' + + 'closeCurve closeSurface cluster cmdFileOutput cmdScrollFieldExecuter ' + + 'cmdScrollFieldReporter cmdShell coarsenSubdivSelectionList collision color ' + + 'colorAtPoint colorEditor colorIndex colorIndexSliderGrp colorSliderButtonGrp ' + + 'colorSliderGrp columnLayout commandEcho commandLine commandPort compactHairSystem ' + + 'componentEditor compositingInterop computePolysetVolume condition cone confirmDialog ' + + 'connectAttr connectControl connectDynamic connectJoint connectionInfo constrain ' + + 'constrainValue constructionHistory container containsMultibyte contextInfo control ' + + 'convertFromOldLayers convertIffToPsd convertLightmap convertSolidTx convertTessellation ' + + 'convertUnit copyArray copyFlexor copyKey copySkinWeights cos cpButton cpCache ' + + 'cpClothSet cpCollision cpConstraint cpConvClothToMesh cpForces cpGetSolverAttr cpPanel ' + + 'cpProperty cpRigidCollisionFilter cpSeam cpSetEdit cpSetSolverAttr cpSolver ' + + 'cpSolverTypes cpTool cpUpdateClothUVs createDisplayLayer createDrawCtx createEditor ' + + 'createLayeredPsdFile createMotionField createNewShelf createNode createRenderLayer ' + + 'createSubdivRegion cross crossProduct ctxAbort ctxCompletion ctxEditMode ctxTraverse ' + + 'currentCtx currentTime currentTimeCtx currentUnit curve curveAddPtCtx ' + + 'curveCVCtx curveEPCtx curveEditorCtx curveIntersect curveMoveEPCtx curveOnSurface ' + + 'curveSketchCtx cutKey cycleCheck cylinder dagPose date defaultLightListCheckBox ' + + 'defaultNavigation defineDataServer defineVirtualDevice deformer deg_to_rad delete ' + + 'deleteAttr deleteShadingGroupsAndMaterials deleteShelfTab deleteUI deleteUnusedBrushes ' + + 'delrandstr detachCurve detachDeviceAttr detachSurface deviceEditor devicePanel dgInfo ' + + 'dgdirty dgeval dgtimer dimWhen directKeyCtx directionalLight dirmap dirname disable ' + + 'disconnectAttr disconnectJoint diskCache displacementToPoly displayAffected ' + + 'displayColor displayCull displayLevelOfDetail displayPref displayRGBColor ' + + 'displaySmoothness displayStats displayString displaySurface distanceDimContext ' + + 'distanceDimension doBlur dolly dollyCtx dopeSheetEditor dot dotProduct ' + + 'doubleProfileBirailSurface drag dragAttrContext draggerContext dropoffLocator ' + + 'duplicate duplicateCurve duplicateSurface dynCache dynControl dynExport dynExpression ' + + 'dynGlobals dynPaintEditor dynParticleCtx dynPref dynRelEdPanel dynRelEditor ' + + 'dynamicLoad editAttrLimits editDisplayLayerGlobals editDisplayLayerMembers ' + + 'editRenderLayerAdjustment editRenderLayerGlobals editRenderLayerMembers editor ' + + 'editorTemplate effector emit emitter enableDevice encodeString endString endsWith env ' + + 'equivalent equivalentTol erf error eval evalDeferred evalEcho event ' + + 'exactWorldBoundingBox exclusiveLightCheckBox exec executeForEachObject exists exp ' + + 'expression expressionEditorListen extendCurve extendSurface extrude fcheck fclose feof ' + + 'fflush fgetline fgetword file fileBrowserDialog fileDialog fileExtension fileInfo ' + + 'filetest filletCurve filter filterCurve filterExpand filterStudioImport ' + + 'findAllIntersections findAnimCurves findKeyframe findMenuItem findRelatedSkinCluster ' + + 'finder firstParentOf fitBspline flexor floatEq floatField floatFieldGrp floatScrollBar ' + + 'floatSlider floatSlider2 floatSliderButtonGrp floatSliderGrp floor flow fluidCacheInfo ' + + 'fluidEmitter fluidVoxelInfo flushUndo fmod fontDialog fopen formLayout format fprint ' + + 'frameLayout fread freeFormFillet frewind fromNativePath fwrite gamma gauss ' + + 'geometryConstraint getApplicationVersionAsFloat getAttr getClassification ' + + 'getDefaultBrush getFileList getFluidAttr getInputDeviceRange getMayaPanelTypes ' + + 'getModifiers getPanel getParticleAttr getPluginResource getenv getpid glRender ' + + 'glRenderEditor globalStitch gmatch goal gotoBindPose grabColor gradientControl ' + + 'gradientControlNoAttr graphDollyCtx graphSelectContext graphTrackCtx gravity grid ' + + 'gridLayout group groupObjectsByName HfAddAttractorToAS HfAssignAS HfBuildEqualMap ' + + 'HfBuildFurFiles HfBuildFurImages HfCancelAFR HfConnectASToHF HfCreateAttractor ' + + 'HfDeleteAS HfEditAS HfPerformCreateAS HfRemoveAttractorFromAS HfSelectAttached ' + + 'HfSelectAttractors HfUnAssignAS hardenPointCurve hardware hardwareRenderPanel ' + + 'headsUpDisplay headsUpMessage help helpLine hermite hide hilite hitTest hotBox hotkey ' + + 'hotkeyCheck hsv_to_rgb hudButton hudSlider hudSliderButton hwReflectionMap hwRender ' + + 'hwRenderLoad hyperGraph hyperPanel hyperShade hypot iconTextButton iconTextCheckBox ' + + 'iconTextRadioButton iconTextRadioCollection iconTextScrollList iconTextStaticLabel ' + + 'ikHandle ikHandleCtx ikHandleDisplayScale ikSolver ikSplineHandleCtx ikSystem ' + + 'ikSystemInfo ikfkDisplayMethod illustratorCurves image imfPlugins inheritTransform ' + + 'insertJoint insertJointCtx insertKeyCtx insertKnotCurve insertKnotSurface instance ' + + 'instanceable instancer intField intFieldGrp intScrollBar intSlider intSliderGrp ' + + 'interToUI internalVar intersect iprEngine isAnimCurve isConnected isDirty isParentOf ' + + 'isSameObject isTrue isValidObjectName isValidString isValidUiName isolateSelect ' + + 'itemFilter itemFilterAttr itemFilterRender itemFilterType joint jointCluster jointCtx ' + + 'jointDisplayScale jointLattice keyTangent keyframe keyframeOutliner ' + + 'keyframeRegionCurrentTimeCtx keyframeRegionDirectKeyCtx keyframeRegionDollyCtx ' + + 'keyframeRegionInsertKeyCtx keyframeRegionMoveKeyCtx keyframeRegionScaleKeyCtx ' + + 'keyframeRegionSelectKeyCtx keyframeRegionSetKeyCtx keyframeRegionTrackCtx ' + + 'keyframeStats lassoContext lattice latticeDeformKeyCtx launch launchImageEditor ' + + 'layerButton layeredShaderPort layeredTexturePort layout layoutDialog lightList ' + + 'lightListEditor lightListPanel lightlink lineIntersection linearPrecision linstep ' + + 'listAnimatable listAttr listCameras listConnections listDeviceAttachments listHistory ' + + 'listInputDeviceAxes listInputDeviceButtons listInputDevices listMenuAnnotation ' + + 'listNodeTypes listPanelCategories listRelatives listSets listTransforms ' + + 'listUnselected listerEditor loadFluid loadNewShelf loadPlugin ' + + 'loadPluginLanguageResources loadPrefObjects localizedPanelLabel lockNode loft log ' + + 'longNameOf lookThru ls lsThroughFilter lsType lsUI Mayatomr mag makeIdentity makeLive ' + + 'makePaintable makeRoll makeSingleSurface makeTubeOn makebot manipMoveContext ' + + 'manipMoveLimitsCtx manipOptions manipRotateContext manipRotateLimitsCtx ' + + 'manipScaleContext manipScaleLimitsCtx marker match max memory menu menuBarLayout ' + + 'menuEditor menuItem menuItemToShelf menuSet menuSetPref messageLine min minimizeApp ' + + 'mirrorJoint modelCurrentTimeCtx modelEditor modelPanel mouse movIn movOut move ' + + 'moveIKtoFK moveKeyCtx moveVertexAlongDirection multiProfileBirailSurface mute ' + + 'nParticle nameCommand nameField namespace namespaceInfo newPanelItems newton nodeCast ' + + 'nodeIconButton nodeOutliner nodePreset nodeType noise nonLinear normalConstraint ' + + 'normalize nurbsBoolean nurbsCopyUVSet nurbsCube nurbsEditUV nurbsPlane nurbsSelect ' + + 'nurbsSquare nurbsToPoly nurbsToPolygonsPref nurbsToSubdiv nurbsToSubdivPref ' + + 'nurbsUVSet nurbsViewDirectionVector objExists objectCenter objectLayer objectType ' + + 'objectTypeUI obsoleteProc oceanNurbsPreviewPlane offsetCurve offsetCurveOnSurface ' + + 'offsetSurface openGLExtension openMayaPref optionMenu optionMenuGrp optionVar orbit ' + + 'orbitCtx orientConstraint outlinerEditor outlinerPanel overrideModifier ' + + 'paintEffectsDisplay pairBlend palettePort paneLayout panel panelConfiguration ' + + 'panelHistory paramDimContext paramDimension paramLocator parent parentConstraint ' + + 'particle particleExists particleInstancer particleRenderInfo partition pasteKey ' + + 'pathAnimation pause pclose percent performanceOptions pfxstrokes pickWalk picture ' + + 'pixelMove planarSrf plane play playbackOptions playblast plugAttr plugNode pluginInfo ' + + 'pluginResourceUtil pointConstraint pointCurveConstraint pointLight pointMatrixMult ' + + 'pointOnCurve pointOnSurface pointPosition poleVectorConstraint polyAppend ' + + 'polyAppendFacetCtx polyAppendVertex polyAutoProjection polyAverageNormal ' + + 'polyAverageVertex polyBevel polyBlendColor polyBlindData polyBoolOp polyBridgeEdge ' + + 'polyCacheMonitor polyCheck polyChipOff polyClipboard polyCloseBorder polyCollapseEdge ' + + 'polyCollapseFacet polyColorBlindData polyColorDel polyColorPerVertex polyColorSet ' + + 'polyCompare polyCone polyCopyUV polyCrease polyCreaseCtx polyCreateFacet ' + + 'polyCreateFacetCtx polyCube polyCut polyCutCtx polyCylinder polyCylindricalProjection ' + + 'polyDelEdge polyDelFacet polyDelVertex polyDuplicateAndConnect polyDuplicateEdge ' + + 'polyEditUV polyEditUVShell polyEvaluate polyExtrudeEdge polyExtrudeFacet ' + + 'polyExtrudeVertex polyFlipEdge polyFlipUV polyForceUV polyGeoSampler polyHelix ' + + 'polyInfo polyInstallAction polyLayoutUV polyListComponentConversion polyMapCut ' + + 'polyMapDel polyMapSew polyMapSewMove polyMergeEdge polyMergeEdgeCtx polyMergeFacet ' + + 'polyMergeFacetCtx polyMergeUV polyMergeVertex polyMirrorFace polyMoveEdge ' + + 'polyMoveFacet polyMoveFacetUV polyMoveUV polyMoveVertex polyNormal polyNormalPerVertex ' + + 'polyNormalizeUV polyOptUvs polyOptions polyOutput polyPipe polyPlanarProjection ' + + 'polyPlane polyPlatonicSolid polyPoke polyPrimitive polyPrism polyProjection ' + + 'polyPyramid polyQuad polyQueryBlindData polyReduce polySelect polySelectConstraint ' + + 'polySelectConstraintMonitor polySelectCtx polySelectEditCtx polySeparate ' + + 'polySetToFaceNormal polySewEdge polyShortestPathCtx polySmooth polySoftEdge ' + + 'polySphere polySphericalProjection polySplit polySplitCtx polySplitEdge polySplitRing ' + + 'polySplitVertex polyStraightenUVBorder polySubdivideEdge polySubdivideFacet ' + + 'polyToSubdiv polyTorus polyTransfer polyTriangulate polyUVSet polyUnite polyWedgeFace ' + + 'popen popupMenu pose pow preloadRefEd print progressBar progressWindow projFileViewer ' + + 'projectCurve projectTangent projectionContext projectionManip promptDialog propModCtx ' + + 'propMove psdChannelOutliner psdEditTextureFile psdExport psdTextureFile putenv pwd ' + + 'python querySubdiv quit rad_to_deg radial radioButton radioButtonGrp radioCollection ' + + 'radioMenuItemCollection rampColorPort rand randomizeFollicles randstate rangeControl ' + + 'readTake rebuildCurve rebuildSurface recordAttr recordDevice redo reference ' + + 'referenceEdit referenceQuery refineSubdivSelectionList refresh refreshAE ' + + 'registerPluginResource rehash reloadImage removeJoint removeMultiInstance ' + + 'removePanelCategory rename renameAttr renameSelectionList renameUI render ' + + 'renderGlobalsNode renderInfo renderLayerButton renderLayerParent ' + + 'renderLayerPostProcess renderLayerUnparent renderManip renderPartition ' + + 'renderQualityNode renderSettings renderThumbnailUpdate renderWindowEditor ' + + 'renderWindowSelectContext renderer reorder reorderDeformers requires reroot ' + + 'resampleFluid resetAE resetPfxToPolyCamera resetTool resolutionNode retarget ' + + 'reverseCurve reverseSurface revolve rgb_to_hsv rigidBody rigidSolver roll rollCtx ' + + 'rootOf rot rotate rotationInterpolation roundConstantRadius rowColumnLayout rowLayout ' + + 'runTimeCommand runup sampleImage saveAllShelves saveAttrPreset saveFluid saveImage ' + + 'saveInitialState saveMenu savePrefObjects savePrefs saveShelf saveToolSettings scale ' + + 'scaleBrushBrightness scaleComponents scaleConstraint scaleKey scaleKeyCtx sceneEditor ' + + 'sceneUIReplacement scmh scriptCtx scriptEditorInfo scriptJob scriptNode scriptTable ' + + 'scriptToShelf scriptedPanel scriptedPanelType scrollField scrollLayout sculpt ' + + 'searchPathArray seed selLoadSettings select selectContext selectCurveCV selectKey ' + + 'selectKeyCtx selectKeyframeRegionCtx selectMode selectPref selectPriority selectType ' + + 'selectedNodes selectionConnection separator setAttr setAttrEnumResource ' + + 'setAttrMapping setAttrNiceNameResource setConstraintRestPosition ' + + 'setDefaultShadingGroup setDrivenKeyframe setDynamic setEditCtx setEditor setFluidAttr ' + + 'setFocus setInfinity setInputDeviceMapping setKeyCtx setKeyPath setKeyframe ' + + 'setKeyframeBlendshapeTargetWts setMenuMode setNodeNiceNameResource setNodeTypeFlag ' + + 'setParent setParticleAttr setPfxToPolyCamera setPluginResource setProject ' + + 'setStampDensity setStartupMessage setState setToolTo setUITemplate setXformManip sets ' + + 'shadingConnection shadingGeometryRelCtx shadingLightRelCtx shadingNetworkCompare ' + + 'shadingNode shapeCompare shelfButton shelfLayout shelfTabLayout shellField ' + + 'shortNameOf showHelp showHidden showManipCtx showSelectionInTitle ' + + 'showShadingGroupAttrEditor showWindow sign simplify sin singleProfileBirailSurface ' + + 'size sizeBytes skinCluster skinPercent smoothCurve smoothTangentSurface smoothstep ' + + 'snap2to2 snapKey snapMode snapTogetherCtx snapshot soft softMod softModCtx sort sound ' + + 'soundControl source spaceLocator sphere sphrand spotLight spotLightPreviewPort ' + + 'spreadSheetEditor spring sqrt squareSurface srtContext stackTrace startString ' + + 'startsWith stitchAndExplodeShell stitchSurface stitchSurfacePoints strcmp ' + + 'stringArrayCatenate stringArrayContains stringArrayCount stringArrayInsertAtIndex ' + + 'stringArrayIntersector stringArrayRemove stringArrayRemoveAtIndex ' + + 'stringArrayRemoveDuplicates stringArrayRemoveExact stringArrayToString ' + + 'stringToStringArray strip stripPrefixFromName stroke subdAutoProjection ' + + 'subdCleanTopology subdCollapse subdDuplicateAndConnect subdEditUV ' + + 'subdListComponentConversion subdMapCut subdMapSewMove subdMatchTopology subdMirror ' + + 'subdToBlind subdToPoly subdTransferUVsToCache subdiv subdivCrease ' + + 'subdivDisplaySmoothness substitute substituteAllString substituteGeometry substring ' + + 'surface surfaceSampler surfaceShaderList swatchDisplayPort switchTable symbolButton ' + + 'symbolCheckBox sysFile system tabLayout tan tangentConstraint texLatticeDeformContext ' + + 'texManipContext texMoveContext texMoveUVShellContext texRotateContext texScaleContext ' + + 'texSelectContext texSelectShortestPathCtx texSmudgeUVContext texWinToolCtx text ' + + 'textCurves textField textFieldButtonGrp textFieldGrp textManip textScrollList ' + + 'textToShelf textureDisplacePlane textureHairColor texturePlacementContext ' + + 'textureWindow threadCount threePointArcCtx timeControl timePort timerX toNativePath ' + + 'toggle toggleAxis toggleWindowVisibility tokenize tokenizeList tolerance tolower ' + + 'toolButton toolCollection toolDropped toolHasOptions toolPropertyWindow torus toupper ' + + 'trace track trackCtx transferAttributes transformCompare transformLimits translator ' + + 'trim trunc truncateFluidCache truncateHairCache tumble tumbleCtx turbulence ' + + 'twoPointArcCtx uiRes uiTemplate unassignInputDevice undo undoInfo ungroup uniform unit ' + + 'unloadPlugin untangleUV untitledFileName untrim upAxis updateAE userCtx uvLink ' + + 'uvSnapshot validateShelfName vectorize view2dToolCtx viewCamera viewClipPlane ' + + 'viewFit viewHeadOn viewLookAt viewManip viewPlace viewSet visor volumeAxis vortex ' + + 'waitCursor warning webBrowser webBrowserPrefs whatIs window windowPref wire ' + + 'wireContext workspace wrinkle wrinkleContext writeTake xbmLangPathList xform', + illegal: ' { + +/* +Language: Mercury +Author: mucaho +Description: Mercury is a logic/functional programming language which combines the clarity and expressiveness of declarative programming with advanced static analysis and error detection features. +Website: https://www.mercurylang.org +*/ + +function mercury(hljs) { + const KEYWORDS = { + keyword: + 'module use_module import_module include_module end_module initialise ' + + 'mutable initialize finalize finalise interface implementation pred ' + + 'mode func type inst solver any_pred any_func is semidet det nondet ' + + 'multi erroneous failure cc_nondet cc_multi typeclass instance where ' + + 'pragma promise external trace atomic or_else require_complete_switch ' + + 'require_det require_semidet require_multi require_nondet ' + + 'require_cc_multi require_cc_nondet require_erroneous require_failure', + meta: + // pragma + 'inline no_inline type_spec source_file fact_table obsolete memo ' + + 'loop_check minimal_model terminates does_not_terminate ' + + 'check_termination promise_equivalent_clauses ' + + // preprocessor + 'foreign_proc foreign_decl foreign_code foreign_type ' + + 'foreign_import_module foreign_export_enum foreign_export ' + + 'foreign_enum may_call_mercury will_not_call_mercury thread_safe ' + + 'not_thread_safe maybe_thread_safe promise_pure promise_semipure ' + + 'tabled_for_io local untrailed trailed attach_to_io_state ' + + 'can_pass_as_mercury_type stable will_not_throw_exception ' + + 'may_modify_trail will_not_modify_trail may_duplicate ' + + 'may_not_duplicate affects_liveness does_not_affect_liveness ' + + 'doesnt_affect_liveness no_sharing unknown_sharing sharing', + built_in: + 'some all not if then else true fail false try catch catch_any ' + + 'semidet_true semidet_false semidet_fail impure_true impure semipure' + }; + + const COMMENT = hljs.COMMENT('%', '$'); + + const NUMCODE = { + className: 'number', + begin: "0'.\\|0[box][0-9a-fA-F]*" + }; + + const ATOM = hljs.inherit(hljs.APOS_STRING_MODE, { + relevance: 0 + }); + const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { + relevance: 0 + }); + const STRING_FMT = { + className: 'subst', + begin: '\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]', + relevance: 0 + }; + STRING.contains = STRING.contains.slice(); // we need our own copy of contains + STRING.contains.push(STRING_FMT); + + const IMPLICATION = { + className: 'built_in', + variants: [ + { + begin: '<=>' + }, + { + begin: '<=', + relevance: 0 + }, + { + begin: '=>', + relevance: 0 + }, + { + begin: '/\\\\' + }, + { + begin: '\\\\/' + } + ] + }; + + const HEAD_BODY_CONJUNCTION = { + className: 'built_in', + variants: [ + { + begin: ':-\\|-->' + }, + { + begin: '=', + relevance: 0 + } + ] + }; + + return { + name: 'Mercury', + aliases: [ + 'm', + 'moo' + ], + keywords: KEYWORDS, + contains: [ + IMPLICATION, + HEAD_BODY_CONJUNCTION, + COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + NUMCODE, + hljs.NUMBER_MODE, + ATOM, + STRING, + { // relevance booster + begin: /:-/ + }, + { // relevance booster + begin: /\.$/ + } + ] + }; +} + +module.exports = mercury; + + +/***/ }), + +/***/ 52340: +/***/ ((module) => { + +/* +Language: MIPS Assembly +Author: Nebuleon Fumika +Description: MIPS Assembly (up to MIPS32R2) +Website: https://en.wikipedia.org/wiki/MIPS_architecture +Category: assembler +*/ + +function mipsasm(hljs) { + // local labels: %?[FB]?[AT]?\d{1,2}\w+ + return { + name: 'MIPS Assembly', + case_insensitive: true, + aliases: [ 'mips' ], + keywords: { + $pattern: '\\.?' + hljs.IDENT_RE, + meta: + // GNU preprocs + '.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .ltorg ', + built_in: + '$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 ' + // integer registers + '$16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 ' + // integer registers + 'zero at v0 v1 a0 a1 a2 a3 a4 a5 a6 a7 ' + // integer register aliases + 't0 t1 t2 t3 t4 t5 t6 t7 t8 t9 s0 s1 s2 s3 s4 s5 s6 s7 s8 ' + // integer register aliases + 'k0 k1 gp sp fp ra ' + // integer register aliases + '$f0 $f1 $f2 $f2 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 ' + // floating-point registers + '$f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31 ' + // floating-point registers + 'Context Random EntryLo0 EntryLo1 Context PageMask Wired EntryHi ' + // Coprocessor 0 registers + 'HWREna BadVAddr Count Compare SR IntCtl SRSCtl SRSMap Cause EPC PRId ' + // Coprocessor 0 registers + 'EBase Config Config1 Config2 Config3 LLAddr Debug DEPC DESAVE CacheErr ' + // Coprocessor 0 registers + 'ECC ErrorEPC TagLo DataLo TagHi DataHi WatchLo WatchHi PerfCtl PerfCnt ' // Coprocessor 0 registers + }, + contains: [ + { + className: 'keyword', + begin: '\\b(' + // mnemonics + // 32-bit integer instructions + 'addi?u?|andi?|b(al)?|beql?|bgez(al)?l?|bgtzl?|blezl?|bltz(al)?l?|' + + 'bnel?|cl[oz]|divu?|ext|ins|j(al)?|jalr(\\.hb)?|jr(\\.hb)?|lbu?|lhu?|' + + 'll|lui|lw[lr]?|maddu?|mfhi|mflo|movn|movz|move|msubu?|mthi|mtlo|mul|' + + 'multu?|nop|nor|ori?|rotrv?|sb|sc|se[bh]|sh|sllv?|slti?u?|srav?|' + + 'srlv?|subu?|sw[lr]?|xori?|wsbh|' + + // floating-point instructions + 'abs\\.[sd]|add\\.[sd]|alnv.ps|bc1[ft]l?|' + + 'c\\.(s?f|un|u?eq|[ou]lt|[ou]le|ngle?|seq|l[et]|ng[et])\\.[sd]|' + + '(ceil|floor|round|trunc)\\.[lw]\\.[sd]|cfc1|cvt\\.d\\.[lsw]|' + + 'cvt\\.l\\.[dsw]|cvt\\.ps\\.s|cvt\\.s\\.[dlw]|cvt\\.s\\.p[lu]|cvt\\.w\\.[dls]|' + + 'div\\.[ds]|ldx?c1|luxc1|lwx?c1|madd\\.[sd]|mfc1|mov[fntz]?\\.[ds]|' + + 'msub\\.[sd]|mth?c1|mul\\.[ds]|neg\\.[ds]|nmadd\\.[ds]|nmsub\\.[ds]|' + + 'p[lu][lu]\\.ps|recip\\.fmt|r?sqrt\\.[ds]|sdx?c1|sub\\.[ds]|suxc1|' + + 'swx?c1|' + + // system control instructions + 'break|cache|d?eret|[de]i|ehb|mfc0|mtc0|pause|prefx?|rdhwr|' + + 'rdpgpr|sdbbp|ssnop|synci?|syscall|teqi?|tgei?u?|tlb(p|r|w[ir])|' + + 'tlti?u?|tnei?|wait|wrpgpr' + + ')', + end: '\\s' + }, + // lines ending with ; or # aren't really comments, probably auto-detect fail + hljs.COMMENT('[;#](?!\\s*$)', '$'), + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '[^\\\\]\'', + relevance: 0 + }, + { + className: 'title', + begin: '\\|', + end: '\\|', + illegal: '\\n', + relevance: 0 + }, + { + className: 'number', + variants: [ + { // hex + begin: '0x[0-9a-f]+' + }, + { // bare number + begin: '\\b-?\\d+' + } + ], + relevance: 0 + }, + { + className: 'symbol', + variants: [ + { // GNU MIPS syntax + begin: '^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:' + }, + { // numbered local labels + begin: '^\\s*[0-9]+:' + }, + { // number local label reference (backwards, forwards) + begin: '[0-9]+[bf]' + } + ], + relevance: 0 + } + ], + // forward slashes are not allowed + illegal: /\// + }; +} + +module.exports = mipsasm; + + +/***/ }), + +/***/ 14825: +/***/ ((module) => { + +/* +Language: Mizar +Description: The Mizar Language is a formal language derived from the mathematical vernacular. +Author: Kelley van Evert +Website: http://mizar.org/language/ +Category: scientific +*/ + +function mizar(hljs) { + return { + name: 'Mizar', + keywords: + 'environ vocabularies notations constructors definitions ' + + 'registrations theorems schemes requirements begin end definition ' + + 'registration cluster existence pred func defpred deffunc theorem ' + + 'proof let take assume then thus hence ex for st holds consider ' + + 'reconsider such that and in provided of as from be being by means ' + + 'equals implies iff redefine define now not or attr is mode ' + + 'suppose per cases set thesis contradiction scheme reserve struct ' + + 'correctness compatibility coherence symmetry assymetry ' + + 'reflexivity irreflexivity connectedness uniqueness commutativity ' + + 'idempotence involutiveness projectivity', + contains: [ + hljs.COMMENT('::', '$') + ] + }; +} + +module.exports = mizar; + + +/***/ }), + +/***/ 29027: +/***/ ((module) => { + +/* +Language: Mojolicious +Requires: xml.js, perl.js +Author: Dotan Dimet +Description: Mojolicious .ep (Embedded Perl) templates +Website: https://mojolicious.org +Category: template +*/ +function mojolicious(hljs) { + return { + name: 'Mojolicious', + subLanguage: 'xml', + contains: [ + { + className: 'meta', + begin: '^__(END|DATA)__$' + }, + // mojolicious line + { + begin: "^\\s*%{1,2}={0,2}", + end: '$', + subLanguage: 'perl' + }, + // mojolicious block + { + begin: "<%{1,2}={0,2}", + end: "={0,1}%>", + subLanguage: 'perl', + excludeBegin: true, + excludeEnd: true + } + ] + }; +} + +module.exports = mojolicious; + + +/***/ }), + +/***/ 9853: +/***/ ((module) => { + +/* +Language: Monkey +Description: Monkey2 is an easy to use, cross platform, games oriented programming language from Blitz Research. +Author: Arthur Bikmullin +Website: https://blitzresearch.itch.io/monkey2 +*/ + +function monkey(hljs) { + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + { + begin: '[$][a-fA-F0-9]+' + }, + hljs.NUMBER_MODE + ] + }; + + return { + name: 'Monkey', + case_insensitive: true, + keywords: { + keyword: 'public private property continue exit extern new try catch ' + + 'eachin not abstract final select case default const local global field ' + + 'end if then else elseif endif while wend repeat until forever for ' + + 'to step next return module inline throw import', + + built_in: 'DebugLog DebugStop Error Print ACos ACosr ASin ASinr ATan ATan2 ATan2r ATanr Abs Abs Ceil ' + + 'Clamp Clamp Cos Cosr Exp Floor Log Max Max Min Min Pow Sgn Sgn Sin Sinr Sqrt Tan Tanr Seed PI HALFPI TWOPI', + + literal: 'true false null and or shl shr mod' + }, + illegal: /\/\*/, + contains: [ + hljs.COMMENT('#rem', '#end'), + hljs.COMMENT( + "'", + '$', + { + relevance: 0 + } + ), + { + className: 'function', + beginKeywords: 'function method', + end: '[(=:]|$', + illegal: /\n/, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + className: 'class', + beginKeywords: 'class interface', + end: '$', + contains: [ + { + beginKeywords: 'extends implements' + }, + hljs.UNDERSCORE_TITLE_MODE + ] + }, + { + className: 'built_in', + begin: '\\b(self|super)\\b' + }, + { + className: 'meta', + begin: '\\s*#', + end: '$', + keywords: { + 'meta-keyword': 'if else elseif endif end then' + } + }, + { + className: 'meta', + begin: '^\\s*strict\\b' + }, + { + beginKeywords: 'alias', + end: '=', + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + hljs.QUOTE_STRING_MODE, + NUMBER + ] + }; +} + +module.exports = monkey; + + +/***/ }), + +/***/ 15250: +/***/ ((module) => { + +/* +Language: MoonScript +Author: Billy Quith +Description: MoonScript is a programming language that transcompiles to Lua. +Origin: coffeescript.js +Website: http://moonscript.org/ +Category: scripting +*/ + +function moonscript(hljs) { + const KEYWORDS = { + keyword: + // Moonscript keywords + 'if then not for in while do return else elseif break continue switch and or ' + + 'unless when class extends super local import export from using', + literal: + 'true false nil', + built_in: + '_G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load ' + + 'loadfile loadstring module next pairs pcall print rawequal rawget rawset require ' + + 'select setfenv setmetatable tonumber tostring type unpack xpcall coroutine debug ' + + 'io math os package string table' + }; + const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'; + const SUBST = { + className: 'subst', + begin: /#\{/, + end: /\}/, + keywords: KEYWORDS + }; + const EXPRESSIONS = [ + hljs.inherit(hljs.C_NUMBER_MODE, + { + starts: { + end: '(\\s*/)?', + relevance: 0 + } + }), // a number tries to eat the following slash to prevent treating it as a regexp + { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/, + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + SUBST + ] + } + ] + }, + { + className: 'built_in', + begin: '@__' + hljs.IDENT_RE + }, + { + begin: '@' + hljs.IDENT_RE // relevance booster on par with CoffeeScript + }, + { + begin: hljs.IDENT_RE + '\\\\' + hljs.IDENT_RE // inst\method + } + ]; + SUBST.contains = EXPRESSIONS; + + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: JS_IDENT_RE + }); + const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>'; + const PARAMS = { + className: 'params', + begin: '\\([^\\(]', + returnBegin: true, + /* We need another contained nameless mode to not have every nested + pair of parens to be called "params" */ + contains: [ + { + begin: /\(/, + end: /\)/, + keywords: KEYWORDS, + contains: [ 'self' ].concat(EXPRESSIONS) + } + ] + }; + + return { + name: 'MoonScript', + aliases: [ 'moon' ], + keywords: KEYWORDS, + illegal: /\/\*/, + contains: EXPRESSIONS.concat([ + hljs.COMMENT('--', '$'), + { + className: 'function', // function: -> => + begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [ + TITLE, + PARAMS + ] + }, + { + begin: /[\(,:=]\s*/, // anonymous function start + relevance: 0, + contains: [ + { + className: 'function', + begin: POSSIBLE_PARAMS_RE, + end: '[-=]>', + returnBegin: true, + contains: [ PARAMS ] + } + ] + }, + { + className: 'class', + beginKeywords: 'class', + end: '$', + illegal: /[:="\[\]]/, + contains: [ + { + beginKeywords: 'extends', + endsWithParent: true, + illegal: /[:="\[\]]/, + contains: [ TITLE ] + }, + TITLE + ] + }, + { + className: 'name', // table + begin: JS_IDENT_RE + ':', + end: ':', + returnBegin: true, + returnEnd: true, + relevance: 0 + } + ]) + }; +} + +module.exports = moonscript; + + +/***/ }), + +/***/ 74620: +/***/ ((module) => { + +/* + Language: N1QL + Author: Andres Täht + Contributors: Rene Saarsoo + Description: Couchbase query language + Website: https://www.couchbase.com/products/n1ql + */ + +function n1ql(hljs) { + return { + name: 'N1QL', + case_insensitive: true, + contains: [ + { + beginKeywords: + 'build create index delete drop explain infer|10 insert merge prepare select update upsert|10', + end: /;/, endsWithParent: true, + keywords: { + // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html + keyword: + 'all alter analyze and any array as asc begin between binary boolean break bucket build by call ' + + 'case cast cluster collate collection commit connect continue correlate cover create database ' + + 'dataset datastore declare decrement delete derived desc describe distinct do drop each element ' + + 'else end every except exclude execute exists explain fetch first flatten for force from ' + + 'function grant group gsi having if ignore ilike in include increment index infer inline inner ' + + 'insert intersect into is join key keys keyspace known last left let letting like limit lsm map ' + + 'mapping matched materialized merge minus namespace nest not number object offset on ' + + 'option or order outer over parse partition password path pool prepare primary private privilege ' + + 'procedure public raw realm reduce rename return returning revoke right role rollback satisfies ' + + 'schema select self semi set show some start statistics string system then to transaction trigger ' + + 'truncate under union unique unknown unnest unset update upsert use user using validate value ' + + 'valued values via view when where while with within work xor', + // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html + literal: + 'true false null missing|5', + // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html + built_in: + 'array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length ' + + 'array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace ' + + 'array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull ' + + 'missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis ' + + 'date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str ' + + 'duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str ' + + 'str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode ' + + 'base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random ' + + 'round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values ' + + 'object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position ' + + 'regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper ' + + 'isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring' + }, + contains: [ + { + className: 'string', + begin: '\'', end: '\'', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + className: 'string', + begin: '"', end: '"', + contains: [hljs.BACKSLASH_ESCAPE] + }, + { + className: 'symbol', + begin: '`', end: '`', + contains: [hljs.BACKSLASH_ESCAPE], + relevance: 2 + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = n1ql; + + +/***/ }), + +/***/ 27158: +/***/ ((module) => { + +/* +Language: Nginx config +Author: Peter Leonov +Contributors: Ivan Sagalaev +Category: common, config +Website: https://www.nginx.com +*/ + +function nginx(hljs) { + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$\d+/ + }, + { + begin: /\$\{/, + end: /\}/ + }, + { + begin: /[$@]/ + hljs.UNDERSCORE_IDENT_RE + } + ] + }; + const DEFAULT = { + endsWithParent: true, + keywords: { + $pattern: '[a-z/_]+', + literal: + 'on off yes no true false none blocked debug info notice warn error crit ' + + 'select break last permanent redirect kqueue rtsig epoll poll /dev/poll' + }, + relevance: 0, + illegal: '=>', + contains: [ + hljs.HASH_COMMENT_MODE, + { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR + ], + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /'/, + end: /'/ + } + ] + }, + // this swallows entire URLs to avoid detecting numbers within + { + begin: '([a-z]+):/', + end: '\\s', + endsWithParent: true, + excludeEnd: true, + contains: [ VAR ] + }, + { + className: 'regexp', + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR + ], + variants: [ + { + begin: "\\s\\^", + end: "\\s|\\{|;", + returnEnd: true + }, + // regexp locations (~, ~*) + { + begin: "~\\*?\\s+", + end: "\\s|\\{|;", + returnEnd: true + }, + // *.example.com + { + begin: "\\*(\\.[a-z\\-]+)+" + }, + // sub.example.* + { + begin: "([a-z\\-]+\\.)+\\*" + } + ] + }, + // IP + { + className: 'number', + begin: '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b' + }, + // units + { + className: 'number', + begin: '\\b\\d+[kKmMgGdshdwy]*\\b', + relevance: 0 + }, + VAR + ] + }; + + return { + name: 'Nginx config', + aliases: [ 'nginxconf' ], + contains: [ + hljs.HASH_COMMENT_MODE, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s+\\{', + returnBegin: true, + end: /\{/, + contains: [ + { + className: 'section', + begin: hljs.UNDERSCORE_IDENT_RE + } + ], + relevance: 0 + }, + { + begin: hljs.UNDERSCORE_IDENT_RE + '\\s', + end: ';|\\{', + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: hljs.UNDERSCORE_IDENT_RE, + starts: DEFAULT + } + ], + relevance: 0 + } + ], + illegal: '[^\\s\\}]' + }; +} + +module.exports = nginx; + + +/***/ }), + +/***/ 52478: +/***/ ((module) => { + +/* +Language: Nim +Description: Nim is a statically typed compiled systems programming language. +Website: https://nim-lang.org +Category: system +*/ + +function nim(hljs) { + return { + name: 'Nim', + keywords: { + keyword: + 'addr and as asm bind block break case cast const continue converter ' + + 'discard distinct div do elif else end enum except export finally ' + + 'for from func generic if import in include interface is isnot iterator ' + + 'let macro method mixin mod nil not notin object of or out proc ptr ' + + 'raise ref return shl shr static template try tuple type using var ' + + 'when while with without xor yield', + literal: + 'shared guarded stdin stdout stderr result true false', + built_in: + 'int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float ' + + 'float32 float64 bool char string cstring pointer expr stmt void ' + + 'auto any range array openarray varargs seq set clong culong cchar ' + + 'cschar cshort cint csize clonglong cfloat cdouble clongdouble ' + + 'cuchar cushort cuint culonglong cstringarray semistatic' + }, + contains: [ + { + className: 'meta', // Actually pragma + begin: /\{\./, + end: /\.\}/, + relevance: 10 + }, + { + className: 'string', + begin: /[a-zA-Z]\w*"/, + end: /"/, + contains: [ + { + begin: /""/ + } + ] + }, + { + className: 'string', + begin: /([a-zA-Z]\w*)?"""/, + end: /"""/ + }, + hljs.QUOTE_STRING_MODE, + { + className: 'type', + begin: /\b[A-Z]\w+\b/, + relevance: 0 + }, + { + className: 'number', + relevance: 0, + variants: [ + { + begin: /\b(0[xX][0-9a-fA-F][_0-9a-fA-F]*)('?[iIuU](8|16|32|64))?/ + }, + { + begin: /\b(0o[0-7][_0-7]*)('?[iIuUfF](8|16|32|64))?/ + }, + { + begin: /\b(0(b|B)[01][_01]*)('?[iIuUfF](8|16|32|64))?/ + }, + { + begin: /\b(\d[_\d]*)('?[iIuUfF](8|16|32|64))?/ + } + ] + }, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = nim; + + +/***/ }), + +/***/ 14608: +/***/ ((module) => { + +/* +Language: Node REPL +Requires: javascript.js +Author: Marat Nagayev +Category: scripting +*/ + +/** @type LanguageFn */ +function nodeRepl(hljs) { + return { + name: 'Node REPL', + contains: [ + { + className: 'meta', + starts: { + // a space separates the REPL prefix from the actual code + // this is purely for cleaner HTML output + end: / |$/, + starts: { + end: '$', + subLanguage: 'javascript' + } + }, + variants: [ + { + begin: /^>(?=[ ]|$)/ + }, + { + begin: /^\.\.\.(?=[ ]|$)/ + } + ] + } + ] + }; +} + +module.exports = nodeRepl; + + +/***/ }), + +/***/ 76035: +/***/ ((module) => { + +/* +Language: NSIS +Description: Nullsoft Scriptable Install System +Author: Jan T. Sott +Website: https://nsis.sourceforge.io/Main_Page +*/ + +function nsis(hljs) { + const CONSTANTS = { + className: 'variable', + begin: /\$(ADMINTOOLS|APPDATA|CDBURN_AREA|CMDLINE|COMMONFILES32|COMMONFILES64|COMMONFILES|COOKIES|DESKTOP|DOCUMENTS|EXEDIR|EXEFILE|EXEPATH|FAVORITES|FONTS|HISTORY|HWNDPARENT|INSTDIR|INTERNET_CACHE|LANGUAGE|LOCALAPPDATA|MUSIC|NETHOOD|OUTDIR|PICTURES|PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES32|PROGRAMFILES64|PROGRAMFILES|QUICKLAUNCH|RECENT|RESOURCES_LOCALIZED|RESOURCES|SENDTO|SMPROGRAMS|SMSTARTUP|STARTMENU|SYSDIR|TEMP|TEMPLATES|VIDEOS|WINDIR)/ + }; + + const DEFINES = { + // ${defines} + className: 'variable', + begin: /\$+\{[\w.:-]+\}/ + }; + + const VARIABLES = { + // $variables + className: 'variable', + begin: /\$+\w+/, + illegal: /\(\)\{\}/ + }; + + const LANGUAGES = { + // $(language_strings) + className: 'variable', + begin: /\$+\([\w^.:-]+\)/ + }; + + const PARAMETERS = { + // command parameters + className: 'params', + begin: '(ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SYSTEM|TEMPORARY)' + }; + + const COMPILER = { + // !compiler_flags + className: 'keyword', + begin: /!(addincludedir|addplugindir|appendfile|cd|define|delfile|echo|else|endif|error|execute|finalize|getdllversion|gettlbversion|if|ifdef|ifmacrodef|ifmacrondef|ifndef|include|insertmacro|macro|macroend|makensis|packhdr|searchparse|searchreplace|system|tempfile|undef|verbose|warning)/ + }; + + const METACHARS = { + // $\n, $\r, $\t, $$ + className: 'meta', + begin: /\$(\\[nrt]|\$)/ + }; + + const PLUGINS = { + // plug::ins + className: 'class', + begin: /\w+::\w+/ + }; + + const STRING = { + className: 'string', + variants: [ + { + begin: '"', + end: '"' + }, + { + begin: '\'', + end: '\'' + }, + { + begin: '`', + end: '`' + } + ], + illegal: /\n/, + contains: [ + METACHARS, + CONSTANTS, + DEFINES, + VARIABLES, + LANGUAGES + ] + }; + + return { + name: 'NSIS', + case_insensitive: false, + keywords: { + keyword: + 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ChangeUI CheckBitmap ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exch Exec ExecShell ExecShellWait ExecWait ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileReadUTF16LE FileReadWord FileWriteUTF16LE FileSeek FileWrite FileWriteByte FileWriteWord FindClose FindFirst FindNext FindWindow FlushINI GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetKnownFolderPath GetLabelAddress GetTempFileName Goto HideWindow Icon IfAbort IfErrors IfFileExists IfRebootFlag IfRtlLanguage IfShellVarContextAll IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText Int64Cmp Int64CmpU Int64Fmt IntCmp IntCmpU IntFmt IntOp IntPtrCmp IntPtrCmpU IntPtrOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadAndSetImage LoadLanguageFile LockWindow LogSet LogText ManifestDPIAware ManifestLongPathAware ManifestMaxVersionTested ManifestSupportedOS MessageBox MiscButtonText Name Nop OutFile Page PageCallbacks PEAddResource PEDllCharacteristics PERemoveResource PESubsysVer Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename RequestExecutionLevel ReserveFile Return RMDir SearchPath SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetRebootFlag SetRegView SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCmpS StrCpy StrLen SubCaption Unicode UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIFileVersion VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegMultiStr WriteRegNone WriteRegStr WriteUninstaller XPStyle', + literal: + 'admin all auto both bottom bzip2 colored components current custom directory false force hide highest ifdiff ifnewer instfiles lastused leave left license listonly lzma nevershow none normal notset off on open print right show silent silentlog smooth textonly top true try un.components un.custom un.directory un.instfiles un.license uninstConfirm user Win10 Win7 Win8 WinVista zlib' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + { + className: 'function', + beginKeywords: 'Function PageEx Section SectionGroup', + end: '$' + }, + STRING, + COMPILER, + DEFINES, + VARIABLES, + LANGUAGES, + PARAMETERS, + PLUGINS, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = nsis; + + +/***/ }), + +/***/ 92748: +/***/ ((module) => { + +/* +Language: Objective-C +Author: Valerii Hiora +Contributors: Angel G. Olloqui , Matt Diephouse , Andrew Farmer , Minh Nguyễn +Website: https://developer.apple.com/documentation/objectivec +Category: common +*/ + +function objectivec(hljs) { + const API_CLASS = { + className: 'built_in', + begin: '\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+' + }; + const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/; + const OBJC_KEYWORDS = { + $pattern: IDENTIFIER_RE, + keyword: + 'int float while char export sizeof typedef const struct for union ' + + 'unsigned long volatile static bool mutable if do return goto void ' + + 'enum else break extern asm case short default double register explicit ' + + 'signed typename this switch continue wchar_t inline readonly assign ' + + 'readwrite self @synchronized id typeof ' + + 'nonatomic super unichar IBOutlet IBAction strong weak copy ' + + 'in out inout bycopy byref oneway __strong __weak __block __autoreleasing ' + + '@private @protected @public @try @property @end @throw @catch @finally ' + + '@autoreleasepool @synthesize @dynamic @selector @optional @required ' + + '@encode @package @import @defs @compatibility_alias ' + + '__bridge __bridge_transfer __bridge_retained __bridge_retain ' + + '__covariant __contravariant __kindof ' + + '_Nonnull _Nullable _Null_unspecified ' + + '__FUNCTION__ __PRETTY_FUNCTION__ __attribute__ ' + + 'getter setter retain unsafe_unretained ' + + 'nonnull nullable null_unspecified null_resettable class instancetype ' + + 'NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER ' + + 'NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED ' + + 'NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE ' + + 'NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END ' + + 'NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW ' + + 'NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN', + literal: + 'false true FALSE TRUE nil YES NO NULL', + built_in: + 'BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once' + }; + const CLASS_KEYWORDS = { + $pattern: IDENTIFIER_RE, + keyword: '@interface @class @protocol @implementation' + }; + return { + name: 'Objective-C', + aliases: [ + 'mm', + 'objc', + 'obj-c', + 'obj-c++', + 'objective-c++' + ], + keywords: OBJC_KEYWORDS, + illegal: '/, + end: /$/, + illegal: '\\n' + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }, + { + className: 'class', + begin: '(' + CLASS_KEYWORDS.keyword.split(' ').join('|') + ')\\b', + end: /(\{|$)/, + excludeEnd: true, + keywords: CLASS_KEYWORDS, + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + { + begin: '\\.' + hljs.UNDERSCORE_IDENT_RE, + relevance: 0 + } + ] + }; +} + +module.exports = objectivec; + + +/***/ }), + +/***/ 8590: +/***/ ((module) => { + +/* +Language: OCaml +Author: Mehdi Dogguy +Contributors: Nicolas Braud-Santoni , Mickael Delahaye +Description: OCaml language definition. +Website: https://ocaml.org +Category: functional +*/ + +function ocaml(hljs) { + /* missing support for heredoc-like string (OCaml 4.0.2+) */ + return { + name: 'OCaml', + aliases: ['ml'], + keywords: { + $pattern: '[a-z_]\\w*!?', + keyword: + 'and as assert asr begin class constraint do done downto else end ' + + 'exception external for fun function functor if in include ' + + 'inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method ' + + 'mod module mutable new object of open! open or private rec sig struct ' + + 'then to try type val! val virtual when while with ' + + /* camlp4 */ + 'parser value', + built_in: + /* built-in types */ + 'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit ' + + /* (some) types in Pervasives */ + 'in_channel out_channel ref', + literal: + 'true false' + }, + illegal: /\/\/|>>/, + contains: [ + { + className: 'literal', + begin: '\\[(\\|\\|)?\\]|\\(\\)', + relevance: 0 + }, + hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + contains: ['self'] + } + ), + { /* type variable */ + className: 'symbol', + begin: '\'[A-Za-z_](?!\')[\\w\']*' + /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */ + }, + { /* polymorphic variant */ + className: 'type', + begin: '`[A-Z][\\w\']*' + }, + { /* module or constructor */ + className: 'type', + begin: '\\b[A-Z][\\w\']*', + relevance: 0 + }, + { /* don't color identifiers, but safely catch all identifiers with '*/ + begin: '[a-z_]\\w*\'[\\w\']*', relevance: 0 + }, + hljs.inherit(hljs.APOS_STRING_MODE, {className: 'string', relevance: 0}), + hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}), + { + className: 'number', + begin: + '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)', + relevance: 0 + }, + { + begin: /->/ // relevance booster + } + ] + } +} + +module.exports = ocaml; + + +/***/ }), + +/***/ 76055: +/***/ ((module) => { + +/* +Language: OpenSCAD +Author: Dan Panzarella +Description: OpenSCAD is a language for the 3D CAD modeling software of the same name. +Website: https://www.openscad.org +Category: scientific +*/ + +function openscad(hljs) { + const SPECIAL_VARS = { + className: 'keyword', + begin: '\\$(f[asn]|t|vp[rtd]|children)' + }; + const LITERALS = { + className: 'literal', + begin: 'false|true|PI|undef' + }; + const NUMBERS = { + className: 'number', + begin: '\\b\\d+(\\.\\d+)?(e-?\\d+)?', // adds 1e5, 1e-10 + relevance: 0 + }; + const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }); + const PREPRO = { + className: 'meta', + keywords: { + 'meta-keyword': 'include use' + }, + begin: 'include|use <', + end: '>' + }; + const PARAMS = { + className: 'params', + begin: '\\(', + end: '\\)', + contains: [ + 'self', + NUMBERS, + STRING, + SPECIAL_VARS, + LITERALS + ] + }; + const MODIFIERS = { + begin: '[*!#%]', + relevance: 0 + }; + const FUNCTIONS = { + className: 'function', + beginKeywords: 'module function', + end: /=|\{/, + contains: [ + PARAMS, + hljs.UNDERSCORE_TITLE_MODE + ] + }; + + return { + name: 'OpenSCAD', + aliases: [ 'scad' ], + keywords: { + keyword: 'function module include use for intersection_for if else \\%', + literal: 'false true PI undef', + built_in: 'circle square polygon text sphere cube cylinder polyhedron translate rotate scale resize mirror multmatrix color offset hull minkowski union difference intersection abs sign sin cos tan acos asin atan atan2 floor round ceil ln log pow sqrt exp rands min max concat lookup str chr search version version_num norm cross parent_module echo import import_dxf dxf_linear_extrude linear_extrude rotate_extrude surface projection render children dxf_cross dxf_dim let assign' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + NUMBERS, + PREPRO, + STRING, + SPECIAL_VARS, + MODIFIERS, + FUNCTIONS + ] + }; +} + +module.exports = openscad; + + +/***/ }), + +/***/ 51333: +/***/ ((module) => { + +/* +Language: Oxygene +Author: Carlo Kok +Description: Oxygene is built on the foundation of Object Pascal, revamped and extended to be a modern language for the twenty-first century. +Website: https://www.elementscompiler.com/elements/default.aspx +*/ + +function oxygene(hljs) { + const OXYGENE_KEYWORDS = { + $pattern: /\.?\w+/, + keyword: + 'abstract add and array as asc aspect assembly async begin break block by case class concat const copy constructor continue ' + + 'create default delegate desc distinct div do downto dynamic each else empty end ensure enum equals event except exit extension external false ' + + 'final finalize finalizer finally flags for forward from function future global group has if implementation implements implies in index inherited ' + + 'inline interface into invariants is iterator join locked locking loop matching method mod module namespace nested new nil not notify nullable of ' + + 'old on operator or order out override parallel params partial pinned private procedure property protected public queryable raise read readonly ' + + 'record reintroduce remove repeat require result reverse sealed select self sequence set shl shr skip static step soft take then to true try tuple ' + + 'type union unit unsafe until uses using var virtual raises volatile where while with write xor yield await mapped deprecated stdcall cdecl pascal ' + + 'register safecall overload library platform reference packed strict published autoreleasepool selector strong weak unretained' + }; + const CURLY_COMMENT = hljs.COMMENT( + /\{/, + /\}/, + { + relevance: 0 + } + ); + const PAREN_COMMENT = hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + relevance: 10 + } + ); + const STRING = { + className: 'string', + begin: '\'', + end: '\'', + contains: [ + { + begin: '\'\'' + } + ] + }; + const CHAR_STRING = { + className: 'string', + begin: '(#\\d+)+' + }; + const FUNCTION = { + className: 'function', + beginKeywords: 'function constructor destructor procedure method', + end: '[:;]', + keywords: 'function constructor|10 destructor|10 procedure|10 method|10', + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)', + keywords: OXYGENE_KEYWORDS, + contains: [ + STRING, + CHAR_STRING + ] + }, + CURLY_COMMENT, + PAREN_COMMENT + ] + }; + return { + name: 'Oxygene', + case_insensitive: true, + keywords: OXYGENE_KEYWORDS, + illegal: '("|\\$[G-Zg-z]|\\/\\*||->)', + contains: [ + CURLY_COMMENT, + PAREN_COMMENT, + hljs.C_LINE_COMMENT_MODE, + STRING, + CHAR_STRING, + hljs.NUMBER_MODE, + FUNCTION, + { + className: 'class', + begin: '=\\bclass\\b', + end: 'end;', + keywords: OXYGENE_KEYWORDS, + contains: [ + STRING, + CHAR_STRING, + CURLY_COMMENT, + PAREN_COMMENT, + hljs.C_LINE_COMMENT_MODE, + FUNCTION + ] + } + ] + }; +} + +module.exports = oxygene; + + +/***/ }), + +/***/ 70990: +/***/ ((module) => { + +/* +Language: Parser3 +Requires: xml.js +Author: Oleg Volchkov +Website: https://www.parser.ru/en/ +Category: template +*/ + +function parser3(hljs) { + const CURLY_SUBCOMMENT = hljs.COMMENT( + /\{/, + /\}/, + { + contains: [ 'self' ] + } + ); + return { + name: 'Parser3', + subLanguage: 'xml', + relevance: 0, + contains: [ + hljs.COMMENT('^#', '$'), + hljs.COMMENT( + /\^rem\{/, + /\}/, + { + relevance: 10, + contains: [ CURLY_SUBCOMMENT ] + } + ), + { + className: 'meta', + begin: '^@(?:BASE|USE|CLASS|OPTIONS)$', + relevance: 10 + }, + { + className: 'title', + begin: '@[\\w\\-]+\\[[\\w^;\\-]*\\](?:\\[[\\w^;\\-]*\\])?(?:.*)$' + }, + { + className: 'variable', + begin: /\$\{?[\w\-.:]+\}?/ + }, + { + className: 'keyword', + begin: /\^[\w\-.:]+/ + }, + { + className: 'number', + begin: '\\^#[0-9a-fA-F]+' + }, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = parser3; + + +/***/ }), + +/***/ 93238: +/***/ ((module) => { + +/* +Language: Packet Filter config +Description: pf.conf — packet filter configuration file (OpenBSD) +Author: Peter Piwowarski +Website: http://man.openbsd.org/pf.conf +Category: config +*/ + +function pf(hljs) { + const MACRO = { + className: 'variable', + begin: /\$[\w\d#@][\w\d_]*/ + }; + const TABLE = { + className: 'variable', + begin: /<(?!\/)/, + end: />/ + }; + + return { + name: 'Packet Filter config', + aliases: [ 'pf.conf' ], + keywords: { + $pattern: /[a-z0-9_<>-]+/, + built_in: /* block match pass are "actions" in pf.conf(5), the rest are + * lexically similar top-level commands. + */ + 'block match pass load anchor|5 antispoof|10 set table', + keyword: + 'in out log quick on rdomain inet inet6 proto from port os to route ' + + 'allow-opts divert-packet divert-reply divert-to flags group icmp-type ' + + 'icmp6-type label once probability recieved-on rtable prio queue ' + + 'tos tag tagged user keep fragment for os drop ' + + 'af-to|10 binat-to|10 nat-to|10 rdr-to|10 bitmask least-stats random round-robin ' + + 'source-hash static-port ' + + 'dup-to reply-to route-to ' + + 'parent bandwidth default min max qlimit ' + + 'block-policy debug fingerprints hostid limit loginterface optimization ' + + 'reassemble ruleset-optimization basic none profile skip state-defaults ' + + 'state-policy timeout ' + + 'const counters persist ' + + 'no modulate synproxy state|5 floating if-bound no-sync pflow|10 sloppy ' + + 'source-track global rule max-src-nodes max-src-states max-src-conn ' + + 'max-src-conn-rate overload flush ' + + 'scrub|5 max-mss min-ttl no-df|10 random-id', + literal: + 'all any no-route self urpf-failed egress|5 unknown' + }, + contains: [ + hljs.HASH_COMMENT_MODE, + hljs.NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + MACRO, + TABLE + ] + }; +} + +module.exports = pf; + + +/***/ }), + +/***/ 21257: +/***/ ((module) => { + +/* +Language: PostgreSQL and PL/pgSQL +Author: Egor Rogov (e.rogov@postgrespro.ru) +Website: https://www.postgresql.org/docs/11/sql.html +Description: + This language incorporates both PostgreSQL SQL dialect and PL/pgSQL language. + It is based on PostgreSQL version 11. Some notes: + - Text in double-dollar-strings is _always_ interpreted as some programming code. Text + in ordinary quotes is _never_ interpreted that way and highlighted just as a string. + - There are quite a bit "special cases". That's because many keywords are not strictly + they are keywords in some contexts and ordinary identifiers in others. Only some + of such cases are handled; you still can get some of your identifiers highlighted + wrong way. + - Function names deliberately are not highlighted. There is no way to tell function + call from other constructs, hence we can't highlight _all_ function names. And + some names highlighted while others not looks ugly. +*/ + +function pgsql(hljs) { + const COMMENT_MODE = hljs.COMMENT('--', '$'); + const UNQUOTED_IDENT = '[a-zA-Z_][a-zA-Z_0-9$]*'; + const DOLLAR_STRING = '\\$([a-zA-Z_]?|[a-zA-Z_][a-zA-Z_0-9]*)\\$'; + const LABEL = '<<\\s*' + UNQUOTED_IDENT + '\\s*>>'; + + const SQL_KW = + // https://www.postgresql.org/docs/11/static/sql-keywords-appendix.html + // https://www.postgresql.org/docs/11/static/sql-commands.html + // SQL commands (starting words) + 'ABORT ALTER ANALYZE BEGIN CALL CHECKPOINT|10 CLOSE CLUSTER COMMENT COMMIT COPY CREATE DEALLOCATE DECLARE ' + + 'DELETE DISCARD DO DROP END EXECUTE EXPLAIN FETCH GRANT IMPORT INSERT LISTEN LOAD LOCK MOVE NOTIFY ' + + 'PREPARE REASSIGN|10 REFRESH REINDEX RELEASE RESET REVOKE ROLLBACK SAVEPOINT SECURITY SELECT SET SHOW ' + + 'START TRUNCATE UNLISTEN|10 UPDATE VACUUM|10 VALUES ' + + // SQL commands (others) + 'AGGREGATE COLLATION CONVERSION|10 DATABASE DEFAULT PRIVILEGES DOMAIN TRIGGER EXTENSION FOREIGN ' + + 'WRAPPER|10 TABLE FUNCTION GROUP LANGUAGE LARGE OBJECT MATERIALIZED VIEW OPERATOR CLASS ' + + 'FAMILY POLICY PUBLICATION|10 ROLE RULE SCHEMA SEQUENCE SERVER STATISTICS SUBSCRIPTION SYSTEM ' + + 'TABLESPACE CONFIGURATION DICTIONARY PARSER TEMPLATE TYPE USER MAPPING PREPARED ACCESS ' + + 'METHOD CAST AS TRANSFORM TRANSACTION OWNED TO INTO SESSION AUTHORIZATION ' + + 'INDEX PROCEDURE ASSERTION ' + + // additional reserved key words + 'ALL ANALYSE AND ANY ARRAY ASC ASYMMETRIC|10 BOTH CASE CHECK ' + + 'COLLATE COLUMN CONCURRENTLY|10 CONSTRAINT CROSS ' + + 'DEFERRABLE RANGE ' + + 'DESC DISTINCT ELSE EXCEPT FOR FREEZE|10 FROM FULL HAVING ' + + 'ILIKE IN INITIALLY INNER INTERSECT IS ISNULL JOIN LATERAL LEADING LIKE LIMIT ' + + 'NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY ' + + 'REFERENCES RETURNING SIMILAR SOME SYMMETRIC TABLESAMPLE THEN ' + + 'TRAILING UNION UNIQUE USING VARIADIC|10 VERBOSE WHEN WHERE WINDOW WITH ' + + // some of non-reserved (which are used in clauses or as PL/pgSQL keyword) + 'BY RETURNS INOUT OUT SETOF|10 IF STRICT CURRENT CONTINUE OWNER LOCATION OVER PARTITION WITHIN ' + + 'BETWEEN ESCAPE EXTERNAL INVOKER DEFINER WORK RENAME VERSION CONNECTION CONNECT ' + + 'TABLES TEMP TEMPORARY FUNCTIONS SEQUENCES TYPES SCHEMAS OPTION CASCADE RESTRICT ADD ADMIN ' + + 'EXISTS VALID VALIDATE ENABLE DISABLE REPLICA|10 ALWAYS PASSING COLUMNS PATH ' + + 'REF VALUE OVERRIDING IMMUTABLE STABLE VOLATILE BEFORE AFTER EACH ROW PROCEDURAL ' + + 'ROUTINE NO HANDLER VALIDATOR OPTIONS STORAGE OIDS|10 WITHOUT INHERIT DEPENDS CALLED ' + + 'INPUT LEAKPROOF|10 COST ROWS NOWAIT SEARCH UNTIL ENCRYPTED|10 PASSWORD CONFLICT|10 ' + + 'INSTEAD INHERITS CHARACTERISTICS WRITE CURSOR ALSO STATEMENT SHARE EXCLUSIVE INLINE ' + + 'ISOLATION REPEATABLE READ COMMITTED SERIALIZABLE UNCOMMITTED LOCAL GLOBAL SQL PROCEDURES ' + + 'RECURSIVE SNAPSHOT ROLLUP CUBE TRUSTED|10 INCLUDE FOLLOWING PRECEDING UNBOUNDED RANGE GROUPS ' + + 'UNENCRYPTED|10 SYSID FORMAT DELIMITER HEADER QUOTE ENCODING FILTER OFF ' + + // some parameters of VACUUM/ANALYZE/EXPLAIN + 'FORCE_QUOTE FORCE_NOT_NULL FORCE_NULL COSTS BUFFERS TIMING SUMMARY DISABLE_PAGE_SKIPPING ' + + // + 'RESTART CYCLE GENERATED IDENTITY DEFERRED IMMEDIATE LEVEL LOGGED UNLOGGED ' + + 'OF NOTHING NONE EXCLUDE ATTRIBUTE ' + + // from GRANT (not keywords actually) + 'USAGE ROUTINES ' + + // actually literals, but look better this way (due to IS TRUE, IS FALSE, ISNULL etc) + 'TRUE FALSE NAN INFINITY '; + + const ROLE_ATTRS = // only those not in keywrods already + 'SUPERUSER NOSUPERUSER CREATEDB NOCREATEDB CREATEROLE NOCREATEROLE INHERIT NOINHERIT ' + + 'LOGIN NOLOGIN REPLICATION NOREPLICATION BYPASSRLS NOBYPASSRLS '; + + const PLPGSQL_KW = + 'ALIAS BEGIN CONSTANT DECLARE END EXCEPTION RETURN PERFORM|10 RAISE GET DIAGNOSTICS ' + + 'STACKED|10 FOREACH LOOP ELSIF EXIT WHILE REVERSE SLICE DEBUG LOG INFO NOTICE WARNING ASSERT ' + + 'OPEN '; + + const TYPES = + // https://www.postgresql.org/docs/11/static/datatype.html + 'BIGINT INT8 BIGSERIAL SERIAL8 BIT VARYING VARBIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR VARCHAR ' + + 'CIDR CIRCLE DATE DOUBLE PRECISION FLOAT8 FLOAT INET INTEGER INT INT4 INTERVAL JSON JSONB LINE LSEG|10 ' + + 'MACADDR MACADDR8 MONEY NUMERIC DEC DECIMAL PATH POINT POLYGON REAL FLOAT4 SMALLINT INT2 ' + + 'SMALLSERIAL|10 SERIAL2|10 SERIAL|10 SERIAL4|10 TEXT TIME ZONE TIMETZ|10 TIMESTAMP TIMESTAMPTZ|10 TSQUERY|10 TSVECTOR|10 ' + + 'TXID_SNAPSHOT|10 UUID XML NATIONAL NCHAR ' + + 'INT4RANGE|10 INT8RANGE|10 NUMRANGE|10 TSRANGE|10 TSTZRANGE|10 DATERANGE|10 ' + + // pseudotypes + 'ANYELEMENT ANYARRAY ANYNONARRAY ANYENUM ANYRANGE CSTRING INTERNAL ' + + 'RECORD PG_DDL_COMMAND VOID UNKNOWN OPAQUE REFCURSOR ' + + // spec. type + 'NAME ' + + // OID-types + 'OID REGPROC|10 REGPROCEDURE|10 REGOPER|10 REGOPERATOR|10 REGCLASS|10 REGTYPE|10 REGROLE|10 ' + + 'REGNAMESPACE|10 REGCONFIG|10 REGDICTIONARY|10 ';// + + + const TYPES_RE = + TYPES.trim() + .split(' ') + .map(function(val) { return val.split('|')[0]; }) + .join('|'); + + const SQL_BI = + 'CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_CATALOG|10 CURRENT_DATE LOCALTIME LOCALTIMESTAMP ' + + 'CURRENT_ROLE|10 CURRENT_SCHEMA|10 SESSION_USER PUBLIC '; + + const PLPGSQL_BI = + 'FOUND NEW OLD TG_NAME|10 TG_WHEN|10 TG_LEVEL|10 TG_OP|10 TG_RELID|10 TG_RELNAME|10 ' + + 'TG_TABLE_NAME|10 TG_TABLE_SCHEMA|10 TG_NARGS|10 TG_ARGV|10 TG_EVENT|10 TG_TAG|10 ' + + // get diagnostics + 'ROW_COUNT RESULT_OID|10 PG_CONTEXT|10 RETURNED_SQLSTATE COLUMN_NAME CONSTRAINT_NAME ' + + 'PG_DATATYPE_NAME|10 MESSAGE_TEXT TABLE_NAME SCHEMA_NAME PG_EXCEPTION_DETAIL|10 ' + + 'PG_EXCEPTION_HINT|10 PG_EXCEPTION_CONTEXT|10 '; + + const PLPGSQL_EXCEPTIONS = + // exceptions https://www.postgresql.org/docs/current/static/errcodes-appendix.html + 'SQLSTATE SQLERRM|10 ' + + 'SUCCESSFUL_COMPLETION WARNING DYNAMIC_RESULT_SETS_RETURNED IMPLICIT_ZERO_BIT_PADDING ' + + 'NULL_VALUE_ELIMINATED_IN_SET_FUNCTION PRIVILEGE_NOT_GRANTED PRIVILEGE_NOT_REVOKED ' + + 'STRING_DATA_RIGHT_TRUNCATION DEPRECATED_FEATURE NO_DATA NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED ' + + 'SQL_STATEMENT_NOT_YET_COMPLETE CONNECTION_EXCEPTION CONNECTION_DOES_NOT_EXIST CONNECTION_FAILURE ' + + 'SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION ' + + 'TRANSACTION_RESOLUTION_UNKNOWN PROTOCOL_VIOLATION TRIGGERED_ACTION_EXCEPTION FEATURE_NOT_SUPPORTED ' + + 'INVALID_TRANSACTION_INITIATION LOCATOR_EXCEPTION INVALID_LOCATOR_SPECIFICATION INVALID_GRANTOR ' + + 'INVALID_GRANT_OPERATION INVALID_ROLE_SPECIFICATION DIAGNOSTICS_EXCEPTION ' + + 'STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER CASE_NOT_FOUND CARDINALITY_VIOLATION ' + + 'DATA_EXCEPTION ARRAY_SUBSCRIPT_ERROR CHARACTER_NOT_IN_REPERTOIRE DATETIME_FIELD_OVERFLOW ' + + 'DIVISION_BY_ZERO ERROR_IN_ASSIGNMENT ESCAPE_CHARACTER_CONFLICT INDICATOR_OVERFLOW ' + + 'INTERVAL_FIELD_OVERFLOW INVALID_ARGUMENT_FOR_LOGARITHM INVALID_ARGUMENT_FOR_NTILE_FUNCTION ' + + 'INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION INVALID_ARGUMENT_FOR_POWER_FUNCTION ' + + 'INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION INVALID_CHARACTER_VALUE_FOR_CAST ' + + 'INVALID_DATETIME_FORMAT INVALID_ESCAPE_CHARACTER INVALID_ESCAPE_OCTET INVALID_ESCAPE_SEQUENCE ' + + 'NONSTANDARD_USE_OF_ESCAPE_CHARACTER INVALID_INDICATOR_PARAMETER_VALUE INVALID_PARAMETER_VALUE ' + + 'INVALID_REGULAR_EXPRESSION INVALID_ROW_COUNT_IN_LIMIT_CLAUSE ' + + 'INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE INVALID_TABLESAMPLE_ARGUMENT INVALID_TABLESAMPLE_REPEAT ' + + 'INVALID_TIME_ZONE_DISPLACEMENT_VALUE INVALID_USE_OF_ESCAPE_CHARACTER MOST_SPECIFIC_TYPE_MISMATCH ' + + 'NULL_VALUE_NOT_ALLOWED NULL_VALUE_NO_INDICATOR_PARAMETER NUMERIC_VALUE_OUT_OF_RANGE ' + + 'SEQUENCE_GENERATOR_LIMIT_EXCEEDED STRING_DATA_LENGTH_MISMATCH STRING_DATA_RIGHT_TRUNCATION ' + + 'SUBSTRING_ERROR TRIM_ERROR UNTERMINATED_C_STRING ZERO_LENGTH_CHARACTER_STRING ' + + 'FLOATING_POINT_EXCEPTION INVALID_TEXT_REPRESENTATION INVALID_BINARY_REPRESENTATION ' + + 'BAD_COPY_FILE_FORMAT UNTRANSLATABLE_CHARACTER NOT_AN_XML_DOCUMENT INVALID_XML_DOCUMENT ' + + 'INVALID_XML_CONTENT INVALID_XML_COMMENT INVALID_XML_PROCESSING_INSTRUCTION ' + + 'INTEGRITY_CONSTRAINT_VIOLATION RESTRICT_VIOLATION NOT_NULL_VIOLATION FOREIGN_KEY_VIOLATION ' + + 'UNIQUE_VIOLATION CHECK_VIOLATION EXCLUSION_VIOLATION INVALID_CURSOR_STATE ' + + 'INVALID_TRANSACTION_STATE ACTIVE_SQL_TRANSACTION BRANCH_TRANSACTION_ALREADY_ACTIVE ' + + 'HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION ' + + 'INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION ' + + 'NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION READ_ONLY_SQL_TRANSACTION ' + + 'SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED NO_ACTIVE_SQL_TRANSACTION ' + + 'IN_FAILED_SQL_TRANSACTION IDLE_IN_TRANSACTION_SESSION_TIMEOUT INVALID_SQL_STATEMENT_NAME ' + + 'TRIGGERED_DATA_CHANGE_VIOLATION INVALID_AUTHORIZATION_SPECIFICATION INVALID_PASSWORD ' + + 'DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST DEPENDENT_OBJECTS_STILL_EXIST ' + + 'INVALID_TRANSACTION_TERMINATION SQL_ROUTINE_EXCEPTION FUNCTION_EXECUTED_NO_RETURN_STATEMENT ' + + 'MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED ' + + 'READING_SQL_DATA_NOT_PERMITTED INVALID_CURSOR_NAME EXTERNAL_ROUTINE_EXCEPTION ' + + 'CONTAINING_SQL_NOT_PERMITTED MODIFYING_SQL_DATA_NOT_PERMITTED ' + + 'PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED ' + + 'EXTERNAL_ROUTINE_INVOCATION_EXCEPTION INVALID_SQLSTATE_RETURNED NULL_VALUE_NOT_ALLOWED ' + + 'TRIGGER_PROTOCOL_VIOLATED SRF_PROTOCOL_VIOLATED EVENT_TRIGGER_PROTOCOL_VIOLATED ' + + 'SAVEPOINT_EXCEPTION INVALID_SAVEPOINT_SPECIFICATION INVALID_CATALOG_NAME ' + + 'INVALID_SCHEMA_NAME TRANSACTION_ROLLBACK TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION ' + + 'SERIALIZATION_FAILURE STATEMENT_COMPLETION_UNKNOWN DEADLOCK_DETECTED ' + + 'SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION SYNTAX_ERROR INSUFFICIENT_PRIVILEGE CANNOT_COERCE ' + + 'GROUPING_ERROR WINDOWING_ERROR INVALID_RECURSION INVALID_FOREIGN_KEY INVALID_NAME ' + + 'NAME_TOO_LONG RESERVED_NAME DATATYPE_MISMATCH INDETERMINATE_DATATYPE COLLATION_MISMATCH ' + + 'INDETERMINATE_COLLATION WRONG_OBJECT_TYPE GENERATED_ALWAYS UNDEFINED_COLUMN ' + + 'UNDEFINED_FUNCTION UNDEFINED_TABLE UNDEFINED_PARAMETER UNDEFINED_OBJECT ' + + 'DUPLICATE_COLUMN DUPLICATE_CURSOR DUPLICATE_DATABASE DUPLICATE_FUNCTION ' + + 'DUPLICATE_PREPARED_STATEMENT DUPLICATE_SCHEMA DUPLICATE_TABLE DUPLICATE_ALIAS ' + + 'DUPLICATE_OBJECT AMBIGUOUS_COLUMN AMBIGUOUS_FUNCTION AMBIGUOUS_PARAMETER AMBIGUOUS_ALIAS ' + + 'INVALID_COLUMN_REFERENCE INVALID_COLUMN_DEFINITION INVALID_CURSOR_DEFINITION ' + + 'INVALID_DATABASE_DEFINITION INVALID_FUNCTION_DEFINITION ' + + 'INVALID_PREPARED_STATEMENT_DEFINITION INVALID_SCHEMA_DEFINITION INVALID_TABLE_DEFINITION ' + + 'INVALID_OBJECT_DEFINITION WITH_CHECK_OPTION_VIOLATION INSUFFICIENT_RESOURCES DISK_FULL ' + + 'OUT_OF_MEMORY TOO_MANY_CONNECTIONS CONFIGURATION_LIMIT_EXCEEDED PROGRAM_LIMIT_EXCEEDED ' + + 'STATEMENT_TOO_COMPLEX TOO_MANY_COLUMNS TOO_MANY_ARGUMENTS OBJECT_NOT_IN_PREREQUISITE_STATE ' + + 'OBJECT_IN_USE CANT_CHANGE_RUNTIME_PARAM LOCK_NOT_AVAILABLE OPERATOR_INTERVENTION ' + + 'QUERY_CANCELED ADMIN_SHUTDOWN CRASH_SHUTDOWN CANNOT_CONNECT_NOW DATABASE_DROPPED ' + + 'SYSTEM_ERROR IO_ERROR UNDEFINED_FILE DUPLICATE_FILE SNAPSHOT_TOO_OLD CONFIG_FILE_ERROR ' + + 'LOCK_FILE_EXISTS FDW_ERROR FDW_COLUMN_NAME_NOT_FOUND FDW_DYNAMIC_PARAMETER_VALUE_NEEDED ' + + 'FDW_FUNCTION_SEQUENCE_ERROR FDW_INCONSISTENT_DESCRIPTOR_INFORMATION ' + + 'FDW_INVALID_ATTRIBUTE_VALUE FDW_INVALID_COLUMN_NAME FDW_INVALID_COLUMN_NUMBER ' + + 'FDW_INVALID_DATA_TYPE FDW_INVALID_DATA_TYPE_DESCRIPTORS ' + + 'FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER FDW_INVALID_HANDLE FDW_INVALID_OPTION_INDEX ' + + 'FDW_INVALID_OPTION_NAME FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH ' + + 'FDW_INVALID_STRING_FORMAT FDW_INVALID_USE_OF_NULL_POINTER FDW_TOO_MANY_HANDLES ' + + 'FDW_OUT_OF_MEMORY FDW_NO_SCHEMAS FDW_OPTION_NAME_NOT_FOUND FDW_REPLY_HANDLE ' + + 'FDW_SCHEMA_NOT_FOUND FDW_TABLE_NOT_FOUND FDW_UNABLE_TO_CREATE_EXECUTION ' + + 'FDW_UNABLE_TO_CREATE_REPLY FDW_UNABLE_TO_ESTABLISH_CONNECTION PLPGSQL_ERROR ' + + 'RAISE_EXCEPTION NO_DATA_FOUND TOO_MANY_ROWS ASSERT_FAILURE INTERNAL_ERROR DATA_CORRUPTED ' + + 'INDEX_CORRUPTED '; + + const FUNCTIONS = + // https://www.postgresql.org/docs/11/static/functions-aggregate.html + 'ARRAY_AGG AVG BIT_AND BIT_OR BOOL_AND BOOL_OR COUNT EVERY JSON_AGG JSONB_AGG JSON_OBJECT_AGG ' + + 'JSONB_OBJECT_AGG MAX MIN MODE STRING_AGG SUM XMLAGG ' + + 'CORR COVAR_POP COVAR_SAMP REGR_AVGX REGR_AVGY REGR_COUNT REGR_INTERCEPT REGR_R2 REGR_SLOPE ' + + 'REGR_SXX REGR_SXY REGR_SYY STDDEV STDDEV_POP STDDEV_SAMP VARIANCE VAR_POP VAR_SAMP ' + + 'PERCENTILE_CONT PERCENTILE_DISC ' + + // https://www.postgresql.org/docs/11/static/functions-window.html + 'ROW_NUMBER RANK DENSE_RANK PERCENT_RANK CUME_DIST NTILE LAG LEAD FIRST_VALUE LAST_VALUE NTH_VALUE ' + + // https://www.postgresql.org/docs/11/static/functions-comparison.html + 'NUM_NONNULLS NUM_NULLS ' + + // https://www.postgresql.org/docs/11/static/functions-math.html + 'ABS CBRT CEIL CEILING DEGREES DIV EXP FLOOR LN LOG MOD PI POWER RADIANS ROUND SCALE SIGN SQRT ' + + 'TRUNC WIDTH_BUCKET ' + + 'RANDOM SETSEED ' + + 'ACOS ACOSD ASIN ASIND ATAN ATAND ATAN2 ATAN2D COS COSD COT COTD SIN SIND TAN TAND ' + + // https://www.postgresql.org/docs/11/static/functions-string.html + 'BIT_LENGTH CHAR_LENGTH CHARACTER_LENGTH LOWER OCTET_LENGTH OVERLAY POSITION SUBSTRING TREAT TRIM UPPER ' + + 'ASCII BTRIM CHR CONCAT CONCAT_WS CONVERT CONVERT_FROM CONVERT_TO DECODE ENCODE INITCAP ' + + 'LEFT LENGTH LPAD LTRIM MD5 PARSE_IDENT PG_CLIENT_ENCODING QUOTE_IDENT|10 QUOTE_LITERAL|10 ' + + 'QUOTE_NULLABLE|10 REGEXP_MATCH REGEXP_MATCHES REGEXP_REPLACE REGEXP_SPLIT_TO_ARRAY ' + + 'REGEXP_SPLIT_TO_TABLE REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPLIT_PART STRPOS SUBSTR ' + + 'TO_ASCII TO_HEX TRANSLATE ' + + // https://www.postgresql.org/docs/11/static/functions-binarystring.html + 'OCTET_LENGTH GET_BIT GET_BYTE SET_BIT SET_BYTE ' + + // https://www.postgresql.org/docs/11/static/functions-formatting.html + 'TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP ' + + // https://www.postgresql.org/docs/11/static/functions-datetime.html + 'AGE CLOCK_TIMESTAMP|10 DATE_PART DATE_TRUNC ISFINITE JUSTIFY_DAYS JUSTIFY_HOURS JUSTIFY_INTERVAL ' + + 'MAKE_DATE MAKE_INTERVAL|10 MAKE_TIME MAKE_TIMESTAMP|10 MAKE_TIMESTAMPTZ|10 NOW STATEMENT_TIMESTAMP|10 ' + + 'TIMEOFDAY TRANSACTION_TIMESTAMP|10 ' + + // https://www.postgresql.org/docs/11/static/functions-enum.html + 'ENUM_FIRST ENUM_LAST ENUM_RANGE ' + + // https://www.postgresql.org/docs/11/static/functions-geometry.html + 'AREA CENTER DIAMETER HEIGHT ISCLOSED ISOPEN NPOINTS PCLOSE POPEN RADIUS WIDTH ' + + 'BOX BOUND_BOX CIRCLE LINE LSEG PATH POLYGON ' + + // https://www.postgresql.org/docs/11/static/functions-net.html + 'ABBREV BROADCAST HOST HOSTMASK MASKLEN NETMASK NETWORK SET_MASKLEN TEXT INET_SAME_FAMILY ' + + 'INET_MERGE MACADDR8_SET7BIT ' + + // https://www.postgresql.org/docs/11/static/functions-textsearch.html + 'ARRAY_TO_TSVECTOR GET_CURRENT_TS_CONFIG NUMNODE PLAINTO_TSQUERY PHRASETO_TSQUERY WEBSEARCH_TO_TSQUERY ' + + 'QUERYTREE SETWEIGHT STRIP TO_TSQUERY TO_TSVECTOR JSON_TO_TSVECTOR JSONB_TO_TSVECTOR TS_DELETE ' + + 'TS_FILTER TS_HEADLINE TS_RANK TS_RANK_CD TS_REWRITE TSQUERY_PHRASE TSVECTOR_TO_ARRAY ' + + 'TSVECTOR_UPDATE_TRIGGER TSVECTOR_UPDATE_TRIGGER_COLUMN ' + + // https://www.postgresql.org/docs/11/static/functions-xml.html + 'XMLCOMMENT XMLCONCAT XMLELEMENT XMLFOREST XMLPI XMLROOT ' + + 'XMLEXISTS XML_IS_WELL_FORMED XML_IS_WELL_FORMED_DOCUMENT XML_IS_WELL_FORMED_CONTENT ' + + 'XPATH XPATH_EXISTS XMLTABLE XMLNAMESPACES ' + + 'TABLE_TO_XML TABLE_TO_XMLSCHEMA TABLE_TO_XML_AND_XMLSCHEMA ' + + 'QUERY_TO_XML QUERY_TO_XMLSCHEMA QUERY_TO_XML_AND_XMLSCHEMA ' + + 'CURSOR_TO_XML CURSOR_TO_XMLSCHEMA ' + + 'SCHEMA_TO_XML SCHEMA_TO_XMLSCHEMA SCHEMA_TO_XML_AND_XMLSCHEMA ' + + 'DATABASE_TO_XML DATABASE_TO_XMLSCHEMA DATABASE_TO_XML_AND_XMLSCHEMA ' + + 'XMLATTRIBUTES ' + + // https://www.postgresql.org/docs/11/static/functions-json.html + 'TO_JSON TO_JSONB ARRAY_TO_JSON ROW_TO_JSON JSON_BUILD_ARRAY JSONB_BUILD_ARRAY JSON_BUILD_OBJECT ' + + 'JSONB_BUILD_OBJECT JSON_OBJECT JSONB_OBJECT JSON_ARRAY_LENGTH JSONB_ARRAY_LENGTH JSON_EACH ' + + 'JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_EXTRACT_PATH JSONB_EXTRACT_PATH ' + + 'JSON_OBJECT_KEYS JSONB_OBJECT_KEYS JSON_POPULATE_RECORD JSONB_POPULATE_RECORD JSON_POPULATE_RECORDSET ' + + 'JSONB_POPULATE_RECORDSET JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT ' + + 'JSONB_ARRAY_ELEMENTS_TEXT JSON_TYPEOF JSONB_TYPEOF JSON_TO_RECORD JSONB_TO_RECORD JSON_TO_RECORDSET ' + + 'JSONB_TO_RECORDSET JSON_STRIP_NULLS JSONB_STRIP_NULLS JSONB_SET JSONB_INSERT JSONB_PRETTY ' + + // https://www.postgresql.org/docs/11/static/functions-sequence.html + 'CURRVAL LASTVAL NEXTVAL SETVAL ' + + // https://www.postgresql.org/docs/11/static/functions-conditional.html + 'COALESCE NULLIF GREATEST LEAST ' + + // https://www.postgresql.org/docs/11/static/functions-array.html + 'ARRAY_APPEND ARRAY_CAT ARRAY_NDIMS ARRAY_DIMS ARRAY_FILL ARRAY_LENGTH ARRAY_LOWER ARRAY_POSITION ' + + 'ARRAY_POSITIONS ARRAY_PREPEND ARRAY_REMOVE ARRAY_REPLACE ARRAY_TO_STRING ARRAY_UPPER CARDINALITY ' + + 'STRING_TO_ARRAY UNNEST ' + + // https://www.postgresql.org/docs/11/static/functions-range.html + 'ISEMPTY LOWER_INC UPPER_INC LOWER_INF UPPER_INF RANGE_MERGE ' + + // https://www.postgresql.org/docs/11/static/functions-srf.html + 'GENERATE_SERIES GENERATE_SUBSCRIPTS ' + + // https://www.postgresql.org/docs/11/static/functions-info.html + 'CURRENT_DATABASE CURRENT_QUERY CURRENT_SCHEMA|10 CURRENT_SCHEMAS|10 INET_CLIENT_ADDR INET_CLIENT_PORT ' + + 'INET_SERVER_ADDR INET_SERVER_PORT ROW_SECURITY_ACTIVE FORMAT_TYPE ' + + 'TO_REGCLASS TO_REGPROC TO_REGPROCEDURE TO_REGOPER TO_REGOPERATOR TO_REGTYPE TO_REGNAMESPACE TO_REGROLE ' + + 'COL_DESCRIPTION OBJ_DESCRIPTION SHOBJ_DESCRIPTION ' + + 'TXID_CURRENT TXID_CURRENT_IF_ASSIGNED TXID_CURRENT_SNAPSHOT TXID_SNAPSHOT_XIP TXID_SNAPSHOT_XMAX ' + + 'TXID_SNAPSHOT_XMIN TXID_VISIBLE_IN_SNAPSHOT TXID_STATUS ' + + // https://www.postgresql.org/docs/11/static/functions-admin.html + 'CURRENT_SETTING SET_CONFIG BRIN_SUMMARIZE_NEW_VALUES BRIN_SUMMARIZE_RANGE BRIN_DESUMMARIZE_RANGE ' + + 'GIN_CLEAN_PENDING_LIST ' + + // https://www.postgresql.org/docs/11/static/functions-trigger.html + 'SUPPRESS_REDUNDANT_UPDATES_TRIGGER ' + + // ihttps://www.postgresql.org/docs/devel/static/lo-funcs.html + 'LO_FROM_BYTEA LO_PUT LO_GET LO_CREAT LO_CREATE LO_UNLINK LO_IMPORT LO_EXPORT LOREAD LOWRITE ' + + // + 'GROUPING CAST '; + + const FUNCTIONS_RE = + FUNCTIONS.trim() + .split(' ') + .map(function(val) { return val.split('|')[0]; }) + .join('|'); + + return { + name: 'PostgreSQL', + aliases: [ + 'postgres', + 'postgresql' + ], + case_insensitive: true, + keywords: { + keyword: + SQL_KW + PLPGSQL_KW + ROLE_ATTRS, + built_in: + SQL_BI + PLPGSQL_BI + PLPGSQL_EXCEPTIONS + }, + // Forbid some cunstructs from other languages to improve autodetect. In fact + // "[a-z]:" is legal (as part of array slice), but improbabal. + illegal: /:==|\W\s*\(\*|(^|\s)\$[a-z]|\{\{|[a-z]:\s*$|\.\.\.|TO:|DO:/, + contains: [ + // special handling of some words, which are reserved only in some contexts + { + className: 'keyword', + variants: [ + { + begin: /\bTEXT\s*SEARCH\b/ + }, + { + begin: /\b(PRIMARY|FOREIGN|FOR(\s+NO)?)\s+KEY\b/ + }, + { + begin: /\bPARALLEL\s+(UNSAFE|RESTRICTED|SAFE)\b/ + }, + { + begin: /\bSTORAGE\s+(PLAIN|EXTERNAL|EXTENDED|MAIN)\b/ + }, + { + begin: /\bMATCH\s+(FULL|PARTIAL|SIMPLE)\b/ + }, + { + begin: /\bNULLS\s+(FIRST|LAST)\b/ + }, + { + begin: /\bEVENT\s+TRIGGER\b/ + }, + { + begin: /\b(MAPPING|OR)\s+REPLACE\b/ + }, + { + begin: /\b(FROM|TO)\s+(PROGRAM|STDIN|STDOUT)\b/ + }, + { + begin: /\b(SHARE|EXCLUSIVE)\s+MODE\b/ + }, + { + begin: /\b(LEFT|RIGHT)\s+(OUTER\s+)?JOIN\b/ + }, + { + begin: /\b(FETCH|MOVE)\s+(NEXT|PRIOR|FIRST|LAST|ABSOLUTE|RELATIVE|FORWARD|BACKWARD)\b/ + }, + { + begin: /\bPRESERVE\s+ROWS\b/ + }, + { + begin: /\bDISCARD\s+PLANS\b/ + }, + { + begin: /\bREFERENCING\s+(OLD|NEW)\b/ + }, + { + begin: /\bSKIP\s+LOCKED\b/ + }, + { + begin: /\bGROUPING\s+SETS\b/ + }, + { + begin: /\b(BINARY|INSENSITIVE|SCROLL|NO\s+SCROLL)\s+(CURSOR|FOR)\b/ + }, + { + begin: /\b(WITH|WITHOUT)\s+HOLD\b/ + }, + { + begin: /\bWITH\s+(CASCADED|LOCAL)\s+CHECK\s+OPTION\b/ + }, + { + begin: /\bEXCLUDE\s+(TIES|NO\s+OTHERS)\b/ + }, + { + begin: /\bFORMAT\s+(TEXT|XML|JSON|YAML)\b/ + }, + { + begin: /\bSET\s+((SESSION|LOCAL)\s+)?NAMES\b/ + }, + { + begin: /\bIS\s+(NOT\s+)?UNKNOWN\b/ + }, + { + begin: /\bSECURITY\s+LABEL\b/ + }, + { + begin: /\bSTANDALONE\s+(YES|NO|NO\s+VALUE)\b/ + }, + { + begin: /\bWITH\s+(NO\s+)?DATA\b/ + }, + { + begin: /\b(FOREIGN|SET)\s+DATA\b/ + }, + { + begin: /\bSET\s+(CATALOG|CONSTRAINTS)\b/ + }, + { + begin: /\b(WITH|FOR)\s+ORDINALITY\b/ + }, + { + begin: /\bIS\s+(NOT\s+)?DOCUMENT\b/ + }, + { + begin: /\bXML\s+OPTION\s+(DOCUMENT|CONTENT)\b/ + }, + { + begin: /\b(STRIP|PRESERVE)\s+WHITESPACE\b/ + }, + { + begin: /\bNO\s+(ACTION|MAXVALUE|MINVALUE)\b/ + }, + { + begin: /\bPARTITION\s+BY\s+(RANGE|LIST|HASH)\b/ + }, + { + begin: /\bAT\s+TIME\s+ZONE\b/ + }, + { + begin: /\bGRANTED\s+BY\b/ + }, + { + begin: /\bRETURN\s+(QUERY|NEXT)\b/ + }, + { + begin: /\b(ATTACH|DETACH)\s+PARTITION\b/ + }, + { + begin: /\bFORCE\s+ROW\s+LEVEL\s+SECURITY\b/ + }, + { + begin: /\b(INCLUDING|EXCLUDING)\s+(COMMENTS|CONSTRAINTS|DEFAULTS|IDENTITY|INDEXES|STATISTICS|STORAGE|ALL)\b/ + }, + { + begin: /\bAS\s+(ASSIGNMENT|IMPLICIT|PERMISSIVE|RESTRICTIVE|ENUM|RANGE)\b/ + } + ] + }, + // functions named as keywords, followed by '(' + { + begin: /\b(FORMAT|FAMILY|VERSION)\s*\(/ + // keywords: { built_in: 'FORMAT FAMILY VERSION' } + }, + // INCLUDE ( ... ) in index_parameters in CREATE TABLE + { + begin: /\bINCLUDE\s*\(/, + keywords: 'INCLUDE' + }, + // not highlight RANGE if not in frame_clause (not 100% correct, but seems satisfactory) + { + begin: /\bRANGE(?!\s*(BETWEEN|UNBOUNDED|CURRENT|[-0-9]+))/ + }, + // disable highlighting in commands CREATE AGGREGATE/COLLATION/DATABASE/OPERTOR/TEXT SEARCH .../TYPE + // and in PL/pgSQL RAISE ... USING + { + begin: /\b(VERSION|OWNER|TEMPLATE|TABLESPACE|CONNECTION\s+LIMIT|PROCEDURE|RESTRICT|JOIN|PARSER|COPY|START|END|COLLATION|INPUT|ANALYZE|STORAGE|LIKE|DEFAULT|DELIMITER|ENCODING|COLUMN|CONSTRAINT|TABLE|SCHEMA)\s*=/ + }, + // PG_smth; HAS_some_PRIVILEGE + { + // className: 'built_in', + begin: /\b(PG_\w+?|HAS_[A-Z_]+_PRIVILEGE)\b/, + relevance: 10 + }, + // extract + { + begin: /\bEXTRACT\s*\(/, + end: /\bFROM\b/, + returnEnd: true, + keywords: { + // built_in: 'EXTRACT', + type: 'CENTURY DAY DECADE DOW DOY EPOCH HOUR ISODOW ISOYEAR MICROSECONDS ' + + 'MILLENNIUM MILLISECONDS MINUTE MONTH QUARTER SECOND TIMEZONE TIMEZONE_HOUR ' + + 'TIMEZONE_MINUTE WEEK YEAR' + } + }, + // xmlelement, xmlpi - special NAME + { + begin: /\b(XMLELEMENT|XMLPI)\s*\(\s*NAME/, + keywords: { + // built_in: 'XMLELEMENT XMLPI', + keyword: 'NAME' + } + }, + // xmlparse, xmlserialize + { + begin: /\b(XMLPARSE|XMLSERIALIZE)\s*\(\s*(DOCUMENT|CONTENT)/, + keywords: { + // built_in: 'XMLPARSE XMLSERIALIZE', + keyword: 'DOCUMENT CONTENT' + } + }, + // Sequences. We actually skip everything between CACHE|INCREMENT|MAXVALUE|MINVALUE and + // nearest following numeric constant. Without with trick we find a lot of "keywords" + // in 'avrasm' autodetection test... + { + beginKeywords: 'CACHE INCREMENT MAXVALUE MINVALUE', + end: hljs.C_NUMBER_RE, + returnEnd: true, + keywords: 'BY CACHE INCREMENT MAXVALUE MINVALUE' + }, + // WITH|WITHOUT TIME ZONE as part of datatype + { + className: 'type', + begin: /\b(WITH|WITHOUT)\s+TIME\s+ZONE\b/ + }, + // INTERVAL optional fields + { + className: 'type', + begin: /\bINTERVAL\s+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)(\s+TO\s+(MONTH|HOUR|MINUTE|SECOND))?\b/ + }, + // Pseudo-types which allowed only as return type + { + begin: /\bRETURNS\s+(LANGUAGE_HANDLER|TRIGGER|EVENT_TRIGGER|FDW_HANDLER|INDEX_AM_HANDLER|TSM_HANDLER)\b/, + keywords: { + keyword: 'RETURNS', + type: 'LANGUAGE_HANDLER TRIGGER EVENT_TRIGGER FDW_HANDLER INDEX_AM_HANDLER TSM_HANDLER' + } + }, + // Known functions - only when followed by '(' + { + begin: '\\b(' + FUNCTIONS_RE + ')\\s*\\(' + // keywords: { built_in: FUNCTIONS } + }, + // Types + { + begin: '\\.(' + TYPES_RE + ')\\b' // prevent highlight as type, say, 'oid' in 'pgclass.oid' + }, + { + begin: '\\b(' + TYPES_RE + ')\\s+PATH\\b', // in XMLTABLE + keywords: { + keyword: 'PATH', // hopefully no one would use PATH type in XMLTABLE... + type: TYPES.replace('PATH ', '') + } + }, + { + className: 'type', + begin: '\\b(' + TYPES_RE + ')\\b' + }, + // Strings, see https://www.postgresql.org/docs/11/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS + { + className: 'string', + begin: '\'', + end: '\'', + contains: [ + { + begin: '\'\'' + } + ] + }, + { + className: 'string', + begin: '(e|E|u&|U&)\'', + end: '\'', + contains: [ + { + begin: '\\\\.' + } + ], + relevance: 10 + }, + hljs.END_SAME_AS_BEGIN({ + begin: DOLLAR_STRING, + end: DOLLAR_STRING, + contains: [ + { + // actually we want them all except SQL; listed are those with known implementations + // and XML + JSON just in case + subLanguage: [ + 'pgsql', + 'perl', + 'python', + 'tcl', + 'r', + 'lua', + 'java', + 'php', + 'ruby', + 'bash', + 'scheme', + 'xml', + 'json' + ], + endsWithParent: true + } + ] + }), + // identifiers in quotes + { + begin: '"', + end: '"', + contains: [ + { + begin: '""' + } + ] + }, + // numbers + hljs.C_NUMBER_MODE, + // comments + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + // PL/pgSQL staff + // %ROWTYPE, %TYPE, $n + { + className: 'meta', + variants: [ + { // %TYPE, %ROWTYPE + begin: '%(ROW)?TYPE', + relevance: 10 + }, + { // $n + begin: '\\$\\d+' + }, + { // #compiler option + begin: '^#\\w', + end: '$' + } + ] + }, + // <> + { + className: 'symbol', + begin: LABEL, + relevance: 10 + } + ] + }; +} + +module.exports = pgsql; + + +/***/ }), + +/***/ 16425: +/***/ ((module) => { + +/* +Language: PHP Template +Requires: xml.js, php.js +Author: Josh Goebel +Website: https://www.php.net +Category: common +*/ + +function phpTemplate(hljs) { + return { + name: "PHP template", + subLanguage: 'xml', + contains: [ + { + begin: /<\?(php|=)?/, + end: /\?>/, + subLanguage: 'php', + contains: [ + // We don't want the php closing tag ?> to close the PHP block when + // inside any of the following blocks: + { + begin: '/\\*', + end: '\\*/', + skip: true + }, + { + begin: 'b"', + end: '"', + skip: true + }, + { + begin: 'b\'', + end: '\'', + skip: true + }, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null, + className: null, + contains: null, + skip: true + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null, + className: null, + contains: null, + skip: true + }) + ] + } + ] + }; +} + +module.exports = phpTemplate; + + +/***/ }), + +/***/ 87241: +/***/ ((module) => { + +/* +Language: Plain text +Author: Egor Rogov (e.rogov@postgrespro.ru) +Description: Plain text without any highlighting. +Category: common +*/ + +function plaintext(hljs) { + return { + name: 'Plain text', + aliases: [ + 'text', + 'txt' + ], + disableAutodetect: true + }; +} + +module.exports = plaintext; + + +/***/ }), + +/***/ 35412: +/***/ ((module) => { + +/* +Language: Pony +Author: Joe Eli McIlvain +Description: Pony is an open-source, object-oriented, actor-model, + capabilities-secure, high performance programming language. +Website: https://www.ponylang.io +*/ + +function pony(hljs) { + const KEYWORDS = { + keyword: + 'actor addressof and as be break class compile_error compile_intrinsic ' + + 'consume continue delegate digestof do else elseif embed end error ' + + 'for fun if ifdef in interface is isnt lambda let match new not object ' + + 'or primitive recover repeat return struct then trait try type until ' + + 'use var where while with xor', + meta: + 'iso val tag trn box ref', + literal: + 'this false true' + }; + + const TRIPLE_QUOTE_STRING_MODE = { + className: 'string', + begin: '"""', + end: '"""', + relevance: 10 + }; + + const QUOTE_STRING_MODE = { + className: 'string', + begin: '"', + end: '"', + contains: [ hljs.BACKSLASH_ESCAPE ] + }; + + const SINGLE_QUOTE_CHAR_MODE = { + className: 'string', + begin: '\'', + end: '\'', + contains: [ hljs.BACKSLASH_ESCAPE ], + relevance: 0 + }; + + const TYPE_NAME = { + className: 'type', + begin: '\\b_?[A-Z][\\w]*', + relevance: 0 + }; + + const PRIMED_NAME = { + begin: hljs.IDENT_RE + '\'', + relevance: 0 + }; + + const NUMBER_MODE = { + className: 'number', + begin: '(-?)(\\b0[xX][a-fA-F0-9]+|\\b0[bB][01]+|(\\b\\d+(_\\d+)?(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)', + relevance: 0 + }; + + /** + * The `FUNCTION` and `CLASS` modes were intentionally removed to simplify + * highlighting and fix cases like + * ``` + * interface Iterator[A: A] + * fun has_next(): Bool + * fun next(): A? + * ``` + * where it is valid to have a function head without a body + */ + + return { + name: 'Pony', + keywords: KEYWORDS, + contains: [ + TYPE_NAME, + TRIPLE_QUOTE_STRING_MODE, + QUOTE_STRING_MODE, + SINGLE_QUOTE_CHAR_MODE, + PRIMED_NAME, + NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = pony; + + +/***/ }), + +/***/ 47521: +/***/ ((module) => { + +/* +Language: PowerShell +Description: PowerShell is a task-based command-line shell and scripting language built on .NET. +Author: David Mohundro +Contributors: Nicholas Blumhardt , Victor Zhou , Nicolas Le Gall +Website: https://docs.microsoft.com/en-us/powershell/ +*/ + +function powershell(hljs) { + const TYPES = [ + "string", + "char", + "byte", + "int", + "long", + "bool", + "decimal", + "single", + "double", + "DateTime", + "xml", + "array", + "hashtable", + "void" + ]; + + // https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands + const VALID_VERBS = + 'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|' + + 'Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|' + + 'Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|' + + 'Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|' + + 'ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|' + + 'Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|' + + 'Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|' + + 'Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|' + + 'Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|' + + 'Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|' + + 'Unprotect|Use|ForEach|Sort|Tee|Where'; + + const COMPARISON_OPERATORS = + '-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|' + + '-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|' + + '-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|' + + '-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|' + + '-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|' + + '-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|' + + '-split|-wildcard|-xor'; + + const KEYWORDS = { + $pattern: /-?[A-z\.\-]+\b/, + keyword: + 'if else foreach return do while until elseif begin for trap data dynamicparam ' + + 'end break throw param continue finally in switch exit filter try process catch ' + + 'hidden static parameter', + // "echo" relevance has been set to 0 to avoid auto-detect conflicts with shell transcripts + built_in: + 'ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp ' + + 'cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx ' + + 'fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group ' + + 'gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi ' + + 'iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh ' + + 'popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp ' + + 'rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp ' + + 'spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write' + // TODO: 'validate[A-Z]+' can't work in keywords + }; + + const TITLE_NAME_RE = /\w[\w\d]*((-)[\w\d]+)*/; + + const BACKTICK_ESCAPE = { + begin: '`[\\s\\S]', + relevance: 0 + }; + + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$\B/ + }, + { + className: 'keyword', + begin: /\$this/ + }, + { + begin: /\$[\w\d][\w\d_:]*/ + } + ] + }; + + const LITERAL = { + className: 'literal', + begin: /\$(null|true|false)\b/ + }; + + const QUOTE_STRING = { + className: "string", + variants: [ + { + begin: /"/, + end: /"/ + }, + { + begin: /@"/, + end: /^"@/ + } + ], + contains: [ + BACKTICK_ESCAPE, + VAR, + { + className: 'variable', + begin: /\$[A-z]/, + end: /[^A-z]/ + } + ] + }; + + const APOS_STRING = { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /@'/, + end: /^'@/ + } + ] + }; + + const PS_HELPTAGS = { + className: "doctag", + variants: [ + /* no paramater help tags */ + { + begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/ + }, + /* one parameter help tags */ + { + begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/ + } + ] + }; + + const PS_COMMENT = hljs.inherit( + hljs.COMMENT(null, null), + { + variants: [ + /* single-line comment */ + { + begin: /#/, + end: /$/ + }, + /* multi-line comment */ + { + begin: /<#/, + end: /#>/ + } + ], + contains: [ PS_HELPTAGS ] + } + ); + + const CMDLETS = { + className: 'built_in', + variants: [ + { + begin: '('.concat(VALID_VERBS, ')+(-)[\\w\\d]+') + } + ] + }; + + const PS_CLASS = { + className: 'class', + beginKeywords: 'class enum', + end: /\s*[{]/, + excludeEnd: true, + relevance: 0, + contains: [ hljs.TITLE_MODE ] + }; + + const PS_FUNCTION = { + className: 'function', + begin: /function\s+/, + end: /\s*\{|$/, + excludeEnd: true, + returnBegin: true, + relevance: 0, + contains: [ + { + begin: "function", + relevance: 0, + className: "keyword" + }, + { + className: "title", + begin: TITLE_NAME_RE, + relevance: 0 + }, + { + begin: /\(/, + end: /\)/, + className: "params", + relevance: 0, + contains: [ VAR ] + } + // CMDLETS + ] + }; + + // Using statment, plus type, plus assembly name. + const PS_USING = { + begin: /using\s/, + end: /$/, + returnBegin: true, + contains: [ + QUOTE_STRING, + APOS_STRING, + { + className: 'keyword', + begin: /(using|assembly|command|module|namespace|type)/ + } + ] + }; + + // Comperison operators & function named parameters. + const PS_ARGUMENTS = { + variants: [ + // PS literals are pretty verbose so it's a good idea to accent them a bit. + { + className: 'operator', + begin: '('.concat(COMPARISON_OPERATORS, ')\\b') + }, + { + className: 'literal', + begin: /(-)[\w\d]+/, + relevance: 0 + } + ] + }; + + const HASH_SIGNS = { + className: 'selector-tag', + begin: /@\B/, + relevance: 0 + }; + + // It's a very general rule so I'll narrow it a bit with some strict boundaries + // to avoid any possible false-positive collisions! + const PS_METHODS = { + className: 'function', + begin: /\[.*\]\s*[\w]+[ ]??\(/, + end: /$/, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'keyword', + begin: '('.concat( + KEYWORDS.keyword.toString().replace(/\s/g, '|' + ), ')\\b'), + endsParent: true, + relevance: 0 + }, + hljs.inherit(hljs.TITLE_MODE, { + endsParent: true + }) + ] + }; + + const GENTLEMANS_SET = [ + // STATIC_MEMBER, + PS_METHODS, + PS_COMMENT, + BACKTICK_ESCAPE, + hljs.NUMBER_MODE, + QUOTE_STRING, + APOS_STRING, + // PS_NEW_OBJECT_TYPE, + CMDLETS, + VAR, + LITERAL, + HASH_SIGNS + ]; + + const PS_TYPE = { + begin: /\[/, + end: /\]/, + excludeBegin: true, + excludeEnd: true, + relevance: 0, + contains: [].concat( + 'self', + GENTLEMANS_SET, + { + begin: "(" + TYPES.join("|") + ")", + className: "built_in", + relevance: 0 + }, + { + className: 'type', + begin: /[\.\w\d]+/, + relevance: 0 + } + ) + }; + + PS_METHODS.contains.unshift(PS_TYPE); + + return { + name: 'PowerShell', + aliases: [ + "ps", + "ps1" + ], + case_insensitive: true, + keywords: KEYWORDS, + contains: GENTLEMANS_SET.concat( + PS_CLASS, + PS_FUNCTION, + PS_USING, + PS_ARGUMENTS, + PS_TYPE + ) + }; +} + +module.exports = powershell; + + +/***/ }), + +/***/ 74063: +/***/ ((module) => { + +/* +Language: Processing +Description: Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. +Author: Erik Paluka +Website: https://processing.org +Category: graphics +*/ + +function processing(hljs) { + return { + name: 'Processing', + keywords: { + keyword: 'BufferedReader PVector PFont PImage PGraphics HashMap boolean byte char color ' + + 'double float int long String Array FloatDict FloatList IntDict IntList JSONArray JSONObject ' + + 'Object StringDict StringList Table TableRow XML ' + + // Java keywords + 'false synchronized int abstract float private char boolean static null if const ' + + 'for true while long throw strictfp finally protected import native final return void ' + + 'enum else break transient new catch instanceof byte super volatile case assert short ' + + 'package default double public try this switch continue throws protected public private', + literal: 'P2D P3D HALF_PI PI QUARTER_PI TAU TWO_PI', + title: 'setup draw', + built_in: 'displayHeight displayWidth mouseY mouseX mousePressed pmouseX pmouseY key ' + + 'keyCode pixels focused frameCount frameRate height width ' + + 'size createGraphics beginDraw createShape loadShape PShape arc ellipse line point ' + + 'quad rect triangle bezier bezierDetail bezierPoint bezierTangent curve curveDetail curvePoint ' + + 'curveTangent curveTightness shape shapeMode beginContour beginShape bezierVertex curveVertex ' + + 'endContour endShape quadraticVertex vertex ellipseMode noSmooth rectMode smooth strokeCap ' + + 'strokeJoin strokeWeight mouseClicked mouseDragged mouseMoved mousePressed mouseReleased ' + + 'mouseWheel keyPressed keyPressedkeyReleased keyTyped print println save saveFrame day hour ' + + 'millis minute month second year background clear colorMode fill noFill noStroke stroke alpha ' + + 'blue brightness color green hue lerpColor red saturation modelX modelY modelZ screenX screenY ' + + 'screenZ ambient emissive shininess specular add createImage beginCamera camera endCamera frustum ' + + 'ortho perspective printCamera printProjection cursor frameRate noCursor exit loop noLoop popStyle ' + + 'pushStyle redraw binary boolean byte char float hex int str unbinary unhex join match matchAll nf ' + + 'nfc nfp nfs split splitTokens trim append arrayCopy concat expand reverse shorten sort splice subset ' + + 'box sphere sphereDetail createInput createReader loadBytes loadJSONArray loadJSONObject loadStrings ' + + 'loadTable loadXML open parseXML saveTable selectFolder selectInput beginRaw beginRecord createOutput ' + + 'createWriter endRaw endRecord PrintWritersaveBytes saveJSONArray saveJSONObject saveStream saveStrings ' + + 'saveXML selectOutput popMatrix printMatrix pushMatrix resetMatrix rotate rotateX rotateY rotateZ scale ' + + 'shearX shearY translate ambientLight directionalLight lightFalloff lights lightSpecular noLights normal ' + + 'pointLight spotLight image imageMode loadImage noTint requestImage tint texture textureMode textureWrap ' + + 'blend copy filter get loadPixels set updatePixels blendMode loadShader PShaderresetShader shader createFont ' + + 'loadFont text textFont textAlign textLeading textMode textSize textWidth textAscent textDescent abs ceil ' + + 'constrain dist exp floor lerp log mag map max min norm pow round sq sqrt acos asin atan atan2 cos degrees ' + + 'radians sin tan noise noiseDetail noiseSeed random randomGaussian randomSeed' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = processing; + + +/***/ }), + +/***/ 47643: +/***/ ((module) => { + +/* +Language: Python profiler +Description: Python profiler results +Author: Brian Beck +*/ + +function profile(hljs) { + return { + name: 'Python profiler', + contains: [ + hljs.C_NUMBER_MODE, + { + begin: '[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}', + end: ':', + excludeEnd: true + }, + { + begin: '(ncalls|tottime|cumtime)', + end: '$', + keywords: 'ncalls tottime|10 cumtime|10 filename', + relevance: 10 + }, + { + begin: 'function calls', + end: '$', + contains: [ hljs.C_NUMBER_MODE ], + relevance: 10 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\\(', + end: '\\)$', + excludeBegin: true, + excludeEnd: true, + relevance: 0 + } + ] + }; +} + +module.exports = profile; + + +/***/ }), + +/***/ 80127: +/***/ ((module) => { + +/* +Language: Prolog +Description: Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics. +Author: Raivo Laanemets +Website: https://en.wikipedia.org/wiki/Prolog +*/ + +function prolog(hljs) { + const ATOM = { + + begin: /[a-z][A-Za-z0-9_]*/, + relevance: 0 + }; + + const VAR = { + + className: 'symbol', + variants: [ + { + begin: /[A-Z][a-zA-Z0-9_]*/ + }, + { + begin: /_[A-Za-z0-9_]*/ + } + ], + relevance: 0 + }; + + const PARENTED = { + + begin: /\(/, + end: /\)/, + relevance: 0 + }; + + const LIST = { + + begin: /\[/, + end: /\]/ + }; + + const LINE_COMMENT = { + + className: 'comment', + begin: /%/, + end: /$/, + contains: [ hljs.PHRASAL_WORDS_MODE ] + }; + + const BACKTICK_STRING = { + + className: 'string', + begin: /`/, + end: /`/, + contains: [ hljs.BACKSLASH_ESCAPE ] + }; + + const CHAR_CODE = { + className: 'string', // 0'a etc. + begin: /0'(\\'|.)/ + }; + + const SPACE_CODE = { + className: 'string', + begin: /0'\\s/ // 0'\s + }; + + const PRED_OP = { // relevance booster + begin: /:-/ + }; + + const inner = [ + + ATOM, + VAR, + PARENTED, + PRED_OP, + LIST, + LINE_COMMENT, + hljs.C_BLOCK_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + BACKTICK_STRING, + CHAR_CODE, + SPACE_CODE, + hljs.C_NUMBER_MODE + ]; + + PARENTED.contains = inner; + LIST.contains = inner; + + return { + name: 'Prolog', + contains: inner.concat([ + { // relevance booster + begin: /\.$/ + } + ]) + }; +} + +module.exports = prolog; + + +/***/ }), + +/***/ 9309: +/***/ ((module) => { + +/* +Language: .properties +Contributors: Valentin Aitken , Egor Rogov +Website: https://en.wikipedia.org/wiki/.properties +Category: common, config +*/ + +function properties(hljs) { + + // whitespaces: space, tab, formfeed + var WS0 = '[ \\t\\f]*'; + var WS1 = '[ \\t\\f]+'; + // delimiter + var EQUAL_DELIM = WS0+'[:=]'+WS0; + var WS_DELIM = WS1; + var DELIM = '(' + EQUAL_DELIM + '|' + WS_DELIM + ')'; + var KEY_ALPHANUM = '([^\\\\\\W:= \\t\\f\\n]|\\\\.)+'; + var KEY_OTHER = '([^\\\\:= \\t\\f\\n]|\\\\.)+'; + + var DELIM_AND_VALUE = { + // skip DELIM + end: DELIM, + relevance: 0, + starts: { + // value: everything until end of line (again, taking into account backslashes) + className: 'string', + end: /$/, + relevance: 0, + contains: [ + { begin: '\\\\\\\\'}, + { begin: '\\\\\\n' } + ] + } + }; + + return { + name: '.properties', + case_insensitive: true, + illegal: /\S/, + contains: [ + hljs.COMMENT('^\\s*[!#]', '$'), + // key: everything until whitespace or = or : (taking into account backslashes) + // case of a "normal" key + { + returnBegin: true, + variants: [ + { begin: KEY_ALPHANUM + EQUAL_DELIM, relevance: 1 }, + { begin: KEY_ALPHANUM + WS_DELIM, relevance: 0 } + ], + contains: [ + { + className: 'attr', + begin: KEY_ALPHANUM, + endsParent: true, + relevance: 0 + } + ], + starts: DELIM_AND_VALUE + }, + // case of key containing non-alphanumeric chars => relevance = 0 + { + begin: KEY_OTHER + DELIM, + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'meta', + begin: KEY_OTHER, + endsParent: true, + relevance: 0 + } + ], + starts: DELIM_AND_VALUE + }, + // case of an empty key + { + className: 'attr', + relevance: 0, + begin: KEY_OTHER + WS0 + '$' + } + ] + }; +} + +module.exports = properties; + + +/***/ }), + +/***/ 61719: +/***/ ((module) => { + +/* +Language: Protocol Buffers +Author: Dan Tao +Description: Protocol buffer message definition format +Website: https://developers.google.com/protocol-buffers/docs/proto3 +Category: protocols +*/ + +function protobuf(hljs) { + return { + name: 'Protocol Buffers', + keywords: { + keyword: 'package import option optional required repeated group oneof', + built_in: 'double float int32 int64 uint32 uint64 sint32 sint64 ' + + 'fixed32 fixed64 sfixed32 sfixed64 bool string bytes', + literal: 'true false' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'message enum service', end: /\{/, + illegal: /\n/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title + }) + ] + }, + { + className: 'function', + beginKeywords: 'rpc', + end: /[{;]/, excludeEnd: true, + keywords: 'rpc returns' + }, + { // match enum items (relevance) + // BLAH = ...; + begin: /^\s*[A-Z_]+(?=\s*=[^\n]+;$)/ + } + ] + }; +} + +module.exports = protobuf; + + +/***/ }), + +/***/ 29854: +/***/ ((module) => { + +/* +Language: Puppet +Author: Jose Molina Colmenero +Website: https://puppet.com/docs +Category: config +*/ + +function puppet(hljs) { + const PUPPET_KEYWORDS = { + keyword: + /* language keywords */ + 'and case default else elsif false if in import enherits node or true undef unless main settings $string ', + literal: + /* metaparameters */ + 'alias audit before loglevel noop require subscribe tag ' + + /* normal attributes */ + 'owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check ' + + 'en_address ip_address realname command environment hour monute month monthday special target weekday ' + + 'creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore ' + + 'links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source ' + + 'souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ' + + 'ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel ' + + 'native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options ' + + 'device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use ' + + 'message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform ' + + 'responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running ' + + 'start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age ' + + 'password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled ' + + 'enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist ' + + 'priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey ' + + 'sslverify mounted', + built_in: + /* core facts */ + 'architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers ' + + 'domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ' + + 'ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion ' + + 'kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease ' + + 'lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major ' + + 'macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease ' + + 'operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion ' + + 'rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced ' + + 'selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime ' + + 'uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version' + }; + + const COMMENT = hljs.COMMENT('#', '$'); + + const IDENT_RE = '([A-Za-z_]|::)(\\w|::)*'; + + const TITLE = hljs.inherit(hljs.TITLE_MODE, { + begin: IDENT_RE + }); + + const VARIABLE = { + className: 'variable', + begin: '\\$' + IDENT_RE + }; + + const STRING = { + className: 'string', + contains: [ + hljs.BACKSLASH_ESCAPE, + VARIABLE + ], + variants: [ + { + begin: /'/, + end: /'/ + }, + { + begin: /"/, + end: /"/ + } + ] + }; + + return { + name: 'Puppet', + aliases: [ 'pp' ], + contains: [ + COMMENT, + VARIABLE, + STRING, + { + beginKeywords: 'class', + end: '\\{|;', + illegal: /=/, + contains: [ + TITLE, + COMMENT + ] + }, + { + beginKeywords: 'define', + end: /\{/, + contains: [ + { + className: 'section', + begin: hljs.IDENT_RE, + endsParent: true + } + ] + }, + { + begin: hljs.IDENT_RE + '\\s+\\{', + returnBegin: true, + end: /\S/, + contains: [ + { + className: 'keyword', + begin: hljs.IDENT_RE + }, + { + begin: /\{/, + end: /\}/, + keywords: PUPPET_KEYWORDS, + relevance: 0, + contains: [ + STRING, + COMMENT, + { + begin: '[a-zA-Z_]+\\s*=>', + returnBegin: true, + end: '=>', + contains: [ + { + className: 'attr', + begin: hljs.IDENT_RE + } + ] + }, + { + className: 'number', + begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b', + relevance: 0 + }, + VARIABLE + ] + } + ], + relevance: 0 + } + ] + }; +} + +module.exports = puppet; + + +/***/ }), + +/***/ 30006: +/***/ ((module) => { + +/* +Language: PureBASIC +Author: Tristano Ajmone +Description: Syntax highlighting for PureBASIC (v.5.00-5.60). No inline ASM highlighting. (v.1.2, May 2017) +Credits: I've taken inspiration from the PureBasic language file for GeSHi, created by Gustavo Julio Fiorenza (GuShH). +Website: https://www.purebasic.com +*/ + +// Base deafult colors in PB IDE: background: #FFFFDF; foreground: #000000; + +function purebasic(hljs) { + const STRINGS = { // PB IDE color: #0080FF (Azure Radiance) + className: 'string', + begin: '(~)?"', + end: '"', + illegal: '\\n' + }; + const CONSTANTS = { // PB IDE color: #924B72 (Cannon Pink) + // "#" + a letter or underscore + letters, digits or underscores + (optional) "$" + className: 'symbol', + begin: '#[a-zA-Z_]\\w*\\$?' + }; + + return { + name: 'PureBASIC', + aliases: [ + 'pb', + 'pbi' + ], + keywords: // PB IDE color: #006666 (Blue Stone) + Bold + // Keywords from all version of PureBASIC 5.00 upward ... + 'Align And Array As Break CallDebugger Case CompilerCase CompilerDefault ' + + 'CompilerElse CompilerElseIf CompilerEndIf CompilerEndSelect CompilerError ' + + 'CompilerIf CompilerSelect CompilerWarning Continue Data DataSection Debug ' + + 'DebugLevel Declare DeclareC DeclareCDLL DeclareDLL DeclareModule Default ' + + 'Define Dim DisableASM DisableDebugger DisableExplicit Else ElseIf EnableASM ' + + 'EnableDebugger EnableExplicit End EndDataSection EndDeclareModule EndEnumeration ' + + 'EndIf EndImport EndInterface EndMacro EndModule EndProcedure EndSelect ' + + 'EndStructure EndStructureUnion EndWith Enumeration EnumerationBinary Extends ' + + 'FakeReturn For ForEach ForEver Global Gosub Goto If Import ImportC ' + + 'IncludeBinary IncludeFile IncludePath Interface List Macro MacroExpandedCount ' + + 'Map Module NewList NewMap Next Not Or Procedure ProcedureC ' + + 'ProcedureCDLL ProcedureDLL ProcedureReturn Protected Prototype PrototypeC ReDim ' + + 'Read Repeat Restore Return Runtime Select Shared Static Step Structure ' + + 'StructureUnion Swap Threaded To UndefineMacro Until Until UnuseModule ' + + 'UseModule Wend While With XIncludeFile XOr', + contains: [ + // COMMENTS | PB IDE color: #00AAAA (Persian Green) + hljs.COMMENT(';', '$', { + relevance: 0 + }), + + { // PROCEDURES DEFINITIONS + className: 'function', + begin: '\\b(Procedure|Declare)(C|CDLL|DLL)?\\b', + end: '\\(', + excludeEnd: true, + returnBegin: true, + contains: [ + { // PROCEDURE KEYWORDS | PB IDE color: #006666 (Blue Stone) + Bold + className: 'keyword', + begin: '(Procedure|Declare)(C|CDLL|DLL)?', + excludeEnd: true + }, + { // PROCEDURE RETURN TYPE SETTING | PB IDE color: #000000 (Black) + className: 'type', + begin: '\\.\\w*' + // end: ' ', + }, + hljs.UNDERSCORE_TITLE_MODE // PROCEDURE NAME | PB IDE color: #006666 (Blue Stone) + ] + }, + STRINGS, + CONSTANTS + ] + }; +} + +/* ============================================================================== + CHANGELOG + ============================================================================== + - v.1.2 (2017-05-12) + -- BUG-FIX: Some keywords were accidentally joyned together. Now fixed. + - v.1.1 (2017-04-30) + -- Updated to PureBASIC 5.60. + -- Keywords list now built by extracting them from the PureBASIC SDK's + "SyntaxHilighting.dll" (from each PureBASIC version). Tokens from each + version are added to the list, and renamed or removed tokens are kept + for the sake of covering all versions of the language from PureBASIC + v5.00 upward. (NOTE: currently, there are no renamed or deprecated + tokens in the keywords list). For more info, see: + -- http://www.purebasic.fr/english/viewtopic.php?&p=506269 + -- https://github.com/tajmone/purebasic-archives/tree/master/syntax-highlighting/guidelines + - v.1.0 (April 2016) + -- First release + -- Keywords list taken and adapted from GuShH's (Gustavo Julio Fiorenza) + PureBasic language file for GeSHi: + -- https://github.com/easybook/geshi/blob/master/geshi/purebasic.php +*/ + +module.exports = purebasic; + + +/***/ }), + +/***/ 7078: +/***/ ((module) => { + +/* +Language: Python REPL +Requires: python.js +Author: Josh Goebel +Category: common +*/ + +function pythonRepl(hljs) { + return { + aliases: [ 'pycon' ], + contains: [ + { + className: 'meta', + starts: { + // a space separates the REPL prefix from the actual code + // this is purely for cleaner HTML output + end: / |$/, + starts: { + end: '$', + subLanguage: 'python' + } + }, + variants: [ + { + begin: /^>>>(?=[ ]|$)/ + }, + { + begin: /^\.\.\.(?=[ ]|$)/ + } + ] + } + ] + }; +} + +module.exports = pythonRepl; + + +/***/ }), + +/***/ 16201: +/***/ ((module) => { + +/* +Language: Q +Description: Q is a vector-based functional paradigm programming language built into the kdb+ database. + (K/Q/Kdb+ from Kx Systems) +Author: Sergey Vidyuk +Website: https://kx.com/connect-with-us/developers/ +*/ + +function q(hljs) { + const KEYWORDS = { + $pattern: /(`?)[A-Za-z0-9_]+\b/, + keyword: + 'do while select delete by update from', + literal: + '0b 1b', + built_in: + 'neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum', + type: + '`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid' + }; + + return { + name: 'Q', + aliases: [ + 'k', + 'kdb' + ], + keywords: KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = q; + + +/***/ }), + +/***/ 32348: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: QML +Requires: javascript.js, xml.js +Author: John Foster +Description: Syntax highlighting for the Qt Quick QML scripting language, based mostly off + the JavaScript parser. +Website: https://doc.qt.io/qt-5/qmlapplications.html +Category: scripting +*/ + +function qml(hljs) { + const KEYWORDS = { + keyword: + 'in of on if for while finally var new function do return void else break catch ' + + 'instanceof with throw case default try this switch continue typeof delete ' + + 'let yield const export super debugger as async await import', + literal: + 'true false null undefined NaN Infinity', + built_in: + 'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' + + 'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' + + 'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' + + 'TypeError URIError Number Math Date String RegExp Array Float32Array ' + + 'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' + + 'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' + + 'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' + + 'Behavior bool color coordinate date double enumeration font geocircle georectangle ' + + 'geoshape int list matrix4x4 parent point quaternion real rect ' + + 'size string url variant vector2d vector3d vector4d ' + + 'Promise' + }; + + const QML_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9\\._]*'; + + // Isolate property statements. Ends at a :, =, ;, ,, a comment or end of line. + // Use property class. + const PROPERTY = { + className: 'keyword', + begin: '\\bproperty\\b', + starts: { + className: 'string', + end: '(:|=|;|,|//|/\\*|$)', + returnEnd: true + } + }; + + // Isolate signal statements. Ends at a ) a comment or end of line. + // Use property class. + const SIGNAL = { + className: 'keyword', + begin: '\\bsignal\\b', + starts: { + className: 'string', + end: '(\\(|:|=|;|,|//|/\\*|$)', + returnEnd: true + } + }; + + // id: is special in QML. When we see id: we want to mark the id: as attribute and + // emphasize the token following. + const ID_ID = { + className: 'attribute', + begin: '\\bid\\s*:', + starts: { + className: 'string', + end: QML_IDENT_RE, + returnEnd: false + } + }; + + // Find QML object attribute. An attribute is a QML identifier followed by :. + // Unfortunately it's hard to know where it ends, as it may contain scalars, + // objects, object definitions, or javascript. The true end is either when the parent + // ends or the next attribute is detected. + const QML_ATTRIBUTE = { + begin: QML_IDENT_RE + '\\s*:', + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: QML_IDENT_RE, + end: '\\s*:', + excludeEnd: true, + relevance: 0 + } + ], + relevance: 0 + }; + + // Find QML object. A QML object is a QML identifier followed by { and ends at the matching }. + // All we really care about is finding IDENT followed by { and just mark up the IDENT and ignore the {. + const QML_OBJECT = { + begin: concat(QML_IDENT_RE, /\s*\{/), + end: /\{/, + returnBegin: true, + relevance: 0, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: QML_IDENT_RE + }) + ] + }; + + return { + name: 'QML', + aliases: [ 'qt' ], + case_insensitive: false, + keywords: KEYWORDS, + contains: [ + { + className: 'meta', + begin: /^\s*['"]use (strict|asm)['"]/ + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + { // template string + className: 'string', + begin: '`', + end: '`', + contains: [ + hljs.BACKSLASH_ESCAPE, + { + className: 'subst', + begin: '\\$\\{', + end: '\\}' + } + ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'number', + variants: [ + { + begin: '\\b(0[bB][01]+)' + }, + { + begin: '\\b(0[oO][0-7]+)' + }, + { + begin: hljs.C_NUMBER_RE + } + ], + relevance: 0 + }, + { // "value" container + begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*', + keywords: 'return throw case', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.REGEXP_MODE, + { // E4X / JSX + begin: /\s*[);\]]/, + relevance: 0, + subLanguage: 'xml' + } + ], + relevance: 0 + }, + SIGNAL, + PROPERTY, + { + className: 'function', + beginKeywords: 'function', + end: /\{/, + excludeEnd: true, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + begin: /[A-Za-z$_][0-9A-Za-z$_]*/ + }), + { + className: 'params', + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + } + ], + illegal: /\[|%/ + }, + { + // hack: prevents detection of keywords after dots + begin: '\\.' + hljs.IDENT_RE, + relevance: 0 + }, + ID_ID, + QML_ATTRIBUTE, + QML_OBJECT + ], + illegal: /#/ + }; +} + +module.exports = qml; + + +/***/ }), + +/***/ 40720: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: R +Description: R is a free software environment for statistical computing and graphics. +Author: Joe Cheng +Contributors: Konrad Rudolph +Website: https://www.r-project.org +Category: common,scientific +*/ + +/** @type LanguageFn */ +function r(hljs) { + // Identifiers in R cannot start with `_`, but they can start with `.` if it + // is not immediately followed by a digit. + // R also supports quoted identifiers, which are near-arbitrary sequences + // delimited by backticks (`…`), which may contain escape sequences. These are + // handled in a separate mode. See `test/markup/r/names.txt` for examples. + // FIXME: Support Unicode identifiers. + const IDENT_RE = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/; + const SIMPLE_IDENT = /[a-zA-Z][a-zA-Z_0-9]*/; + + return { + name: 'R', + + // only in Haskell, not R + illegal: /->/, + keywords: { + $pattern: IDENT_RE, + keyword: + 'function if in break next repeat else for while', + literal: + 'NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 ' + + 'NA_character_|10 NA_complex_|10', + built_in: + // Builtin constants + 'LETTERS letters month.abb month.name pi T F ' + + // Primitive functions + // These are all the functions in `base` that are implemented as a + // `.Primitive`, minus those functions that are also keywords. + 'abs acos acosh all any anyNA Arg as.call as.character ' + + 'as.complex as.double as.environment as.integer as.logical ' + + 'as.null.default as.numeric as.raw asin asinh atan atanh attr ' + + 'attributes baseenv browser c call ceiling class Conj cos cosh ' + + 'cospi cummax cummin cumprod cumsum digamma dim dimnames ' + + 'emptyenv exp expression floor forceAndCall gamma gc.time ' + + 'globalenv Im interactive invisible is.array is.atomic is.call ' + + 'is.character is.complex is.double is.environment is.expression ' + + 'is.finite is.function is.infinite is.integer is.language ' + + 'is.list is.logical is.matrix is.na is.name is.nan is.null ' + + 'is.numeric is.object is.pairlist is.raw is.recursive is.single ' + + 'is.symbol lazyLoadDBfetch length lgamma list log max min ' + + 'missing Mod names nargs nzchar oldClass on.exit pos.to.env ' + + 'proc.time prod quote range Re rep retracemem return round ' + + 'seq_along seq_len seq.int sign signif sin sinh sinpi sqrt ' + + 'standardGeneric substitute sum switch tan tanh tanpi tracemem ' + + 'trigamma trunc unclass untracemem UseMethod xtfrm', + }, + compilerExtensions: [ + // allow beforeMatch to act as a "qualifier" for the match + // the full match begin must be [beforeMatch][begin] + (mode, parent) => { + if (!mode.beforeMatch) return; + // starts conflicts with endsParent which we need to make sure the child + // rule is not matched multiple times + if (mode.starts) throw new Error("beforeMatch cannot be used with starts"); + + const originalMode = Object.assign({}, mode); + Object.keys(mode).forEach((key) => { delete mode[key]; }); + + mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin)); + mode.starts = { + relevance: 0, + contains: [ + Object.assign(originalMode, { endsParent: true }) + ] + }; + mode.relevance = 0; + + delete originalMode.beforeMatch; + } + ], + contains: [ + // Roxygen comments + hljs.COMMENT( + /#'/, + /$/, + { + contains: [ + { + // Handle `@examples` separately to cause all subsequent code + // until the next `@`-tag on its own line to be kept as-is, + // preventing highlighting. This code is example R code, so nested + // doctags shouldn’t be treated as such. See + // `test/markup/r/roxygen.txt` for an example. + className: 'doctag', + begin: '@examples', + starts: { + contains: [ + { begin: /\n/ }, + { + begin: /#'\s*(?=@[a-zA-Z]+)/, + endsParent: true, + }, + { + begin: /#'/, + end: /$/, + excludeBegin: true, + } + ] + } + }, + { + // Handle `@param` to highlight the parameter name following + // after. + className: 'doctag', + begin: '@param', + end: /$/, + contains: [ + { + className: 'variable', + variants: [ + { begin: IDENT_RE }, + { begin: /`(?:\\.|[^`\\])+`/ } + ], + endsParent: true + } + ] + }, + { + className: 'doctag', + begin: /@[a-zA-Z]+/ + }, + { + className: 'meta-keyword', + begin: /\\[a-zA-Z]+/, + } + ] + } + ), + + hljs.HASH_COMMENT_MODE, + + { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\(/, end: /\)(-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\{/, end: /\}(-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\[/, end: /\](-*)"/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\(/, end: /\)(-*)'/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\{/, end: /\}(-*)'/ }), + hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\[/, end: /\](-*)'/ }), + {begin: '"', end: '"', relevance: 0}, + {begin: "'", end: "'", relevance: 0} + ], + }, + { + className: 'number', + relevance: 0, + beforeMatch: /([^a-zA-Z0-9._])/, // not part of an identifier + variants: [ + // TODO: replace with negative look-behind when available + // { begin: /(? { + +/* +Language: ReasonML +Description: Reason lets you write simple, fast and quality type safe code while leveraging both the JavaScript & OCaml ecosystems. +Website: https://reasonml.github.io +Author: Gidi Meir Morris +Category: functional +*/ +function reasonml(hljs) { + function orReValues(ops) { + return ops + .map(function(op) { + return op + .split('') + .map(function(char) { + return '\\' + char; + }) + .join(''); + }) + .join('|'); + } + + const RE_IDENT = '~?[a-z$_][0-9a-zA-Z$_]*'; + const RE_MODULE_IDENT = '`?[A-Z$_][0-9a-zA-Z$_]*'; + + const RE_PARAM_TYPEPARAM = '\'?[a-z$_][0-9a-z$_]*'; + const RE_PARAM_TYPE = '\\s*:\\s*[a-z$_][0-9a-z$_]*(\\(\\s*(' + RE_PARAM_TYPEPARAM + '\\s*(,' + RE_PARAM_TYPEPARAM + '\\s*)*)?\\))?'; + const RE_PARAM = RE_IDENT + '(' + RE_PARAM_TYPE + '){0,2}'; + const RE_OPERATOR = "(" + orReValues([ + '||', + '++', + '**', + '+.', + '*', + '/', + '*.', + '/.', + '...' + ]) + "|\\|>|&&|==|===)"; + const RE_OPERATOR_SPACED = "\\s+" + RE_OPERATOR + "\\s+"; + + const KEYWORDS = { + keyword: + 'and as asr assert begin class constraint do done downto else end exception external ' + + 'for fun function functor if in include inherit initializer ' + + 'land lazy let lor lsl lsr lxor match method mod module mutable new nonrec ' + + 'object of open or private rec sig struct then to try type val virtual when while with', + built_in: + 'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 ref string unit ', + literal: + 'true false' + }; + + const RE_NUMBER = '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)'; + + const NUMBER_MODE = { + className: 'number', + relevance: 0, + variants: [ + { + begin: RE_NUMBER + }, + { + begin: '\\(-' + RE_NUMBER + '\\)' + } + ] + }; + + const OPERATOR_MODE = { + className: 'operator', + relevance: 0, + begin: RE_OPERATOR + }; + const LIST_CONTENTS_MODES = [ + { + className: 'identifier', + relevance: 0, + begin: RE_IDENT + }, + OPERATOR_MODE, + NUMBER_MODE + ]; + + const MODULE_ACCESS_CONTENTS = [ + hljs.QUOTE_STRING_MODE, + OPERATOR_MODE, + { + className: 'module', + begin: "\\b" + RE_MODULE_IDENT, + returnBegin: true, + end: "\.", + contains: [ + { + className: 'identifier', + begin: RE_MODULE_IDENT, + relevance: 0 + } + ] + } + ]; + + const PARAMS_CONTENTS = [ + { + className: 'module', + begin: "\\b" + RE_MODULE_IDENT, + returnBegin: true, + end: "\.", + relevance: 0, + contains: [ + { + className: 'identifier', + begin: RE_MODULE_IDENT, + relevance: 0 + } + ] + } + ]; + + const PARAMS_MODE = { + begin: RE_IDENT, + end: '(,|\\n|\\))', + relevance: 0, + contains: [ + OPERATOR_MODE, + { + className: 'typing', + begin: ':', + end: '(,|\\n)', + returnBegin: true, + relevance: 0, + contains: PARAMS_CONTENTS + } + ] + }; + + const FUNCTION_BLOCK_MODE = { + className: 'function', + relevance: 0, + keywords: KEYWORDS, + variants: [ + { + begin: '\\s(\\(\\.?.*?\\)|' + RE_IDENT + ')\\s*=>', + end: '\\s*=>', + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'params', + variants: [ + { + begin: RE_IDENT + }, + { + begin: RE_PARAM + }, + { + begin: /\(\s*\)/ + } + ] + } + ] + }, + { + begin: '\\s\\(\\.?[^;\\|]*\\)\\s*=>', + end: '\\s=>', + returnBegin: true, + relevance: 0, + contains: [ + { + className: 'params', + relevance: 0, + variants: [ PARAMS_MODE ] + } + ] + }, + { + begin: '\\(\\.\\s' + RE_IDENT + '\\)\\s*=>' + } + ] + }; + MODULE_ACCESS_CONTENTS.push(FUNCTION_BLOCK_MODE); + + const CONSTRUCTOR_MODE = { + className: 'constructor', + begin: RE_MODULE_IDENT + '\\(', + end: '\\)', + illegal: '\\n', + keywords: KEYWORDS, + contains: [ + hljs.QUOTE_STRING_MODE, + OPERATOR_MODE, + { + className: 'params', + begin: '\\b' + RE_IDENT + } + ] + }; + + const PATTERN_MATCH_BLOCK_MODE = { + className: 'pattern-match', + begin: '\\|', + returnBegin: true, + keywords: KEYWORDS, + end: '=>', + relevance: 0, + contains: [ + CONSTRUCTOR_MODE, + OPERATOR_MODE, + { + relevance: 0, + className: 'constructor', + begin: RE_MODULE_IDENT + } + ] + }; + + const MODULE_ACCESS_MODE = { + className: 'module-access', + keywords: KEYWORDS, + returnBegin: true, + variants: [ + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+" + RE_IDENT + }, + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\(", + end: "\\)", + returnBegin: true, + contains: [ + FUNCTION_BLOCK_MODE, + { + begin: '\\(', + end: '\\)', + skip: true + } + ].concat(MODULE_ACCESS_CONTENTS) + }, + { + begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\{", + end: /\}/ + } + ], + contains: MODULE_ACCESS_CONTENTS + }; + + PARAMS_CONTENTS.push(MODULE_ACCESS_MODE); + + return { + name: 'ReasonML', + aliases: [ 're' ], + keywords: KEYWORDS, + illegal: '(:-|:=|\\$\\{|\\+=)', + contains: [ + hljs.COMMENT('/\\*', '\\*/', { + illegal: '^(#,\\/\\/)' + }), + { + className: 'character', + begin: '\'(\\\\[^\']+|[^\'])\'', + illegal: '\\n', + relevance: 0 + }, + hljs.QUOTE_STRING_MODE, + { + className: 'literal', + begin: '\\(\\)', + relevance: 0 + }, + { + className: 'literal', + begin: '\\[\\|', + end: '\\|\\]', + relevance: 0, + contains: LIST_CONTENTS_MODES + }, + { + className: 'literal', + begin: '\\[', + end: '\\]', + relevance: 0, + contains: LIST_CONTENTS_MODES + }, + CONSTRUCTOR_MODE, + { + className: 'operator', + begin: RE_OPERATOR_SPACED, + illegal: '-->', + relevance: 0 + }, + NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + PATTERN_MATCH_BLOCK_MODE, + FUNCTION_BLOCK_MODE, + { + className: 'module-def', + begin: "\\bmodule\\s+" + RE_IDENT + "\\s+" + RE_MODULE_IDENT + "\\s+=\\s+\\{", + end: /\}/, + returnBegin: true, + keywords: KEYWORDS, + relevance: 0, + contains: [ + { + className: 'module', + relevance: 0, + begin: RE_MODULE_IDENT + }, + { + begin: /\{/, + end: /\}/, + skip: true + } + ].concat(MODULE_ACCESS_CONTENTS) + }, + MODULE_ACCESS_MODE + ] + }; +} + +module.exports = reasonml; + + +/***/ }), + +/***/ 38035: +/***/ ((module) => { + +/* +Language: RenderMan RIB +Author: Konstantin Evdokimenko +Contributors: Shuen-Huei Guan +Website: https://renderman.pixar.com/resources/RenderMan_20/ribBinding.html +Category: graphics +*/ + +function rib(hljs) { + return { + name: 'RenderMan RIB', + keywords: + 'ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis ' + + 'Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone ' + + 'CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail ' + + 'DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format ' + + 'FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry ' + + 'Hider Hyperboloid Identity Illuminate Imager Interior LightSource ' + + 'MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte ' + + 'MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option ' + + 'Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples ' + + 'PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection ' + + 'Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ' + + 'ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere ' + + 'SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd ' + + 'TransformPoints Translate TrimCurve WorldBegin WorldEnd', + illegal: ' { + +/* +Language: Roboconf +Author: Vincent Zurczak +Description: Syntax highlighting for Roboconf's DSL +Website: http://roboconf.net +Category: config +*/ + +function roboconf(hljs) { + const IDENTIFIER = '[a-zA-Z-_][^\\n{]+\\{'; + + const PROPERTY = { + className: 'attribute', + begin: /[a-zA-Z-_]+/, + end: /\s*:/, + excludeEnd: true, + starts: { + end: ';', + relevance: 0, + contains: [ + { + className: 'variable', + begin: /\.[a-zA-Z-_]+/ + }, + { + className: 'keyword', + begin: /\(optional\)/ + } + ] + } + }; + + return { + name: 'Roboconf', + aliases: [ + 'graph', + 'instances' + ], + case_insensitive: true, + keywords: 'import', + contains: [ + // Facet sections + { + begin: '^facet ' + IDENTIFIER, + end: /\}/, + keywords: 'facet', + contains: [ + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Instance sections + { + begin: '^\\s*instance of ' + IDENTIFIER, + end: /\}/, + keywords: 'name count channels instance-data instance-state instance of', + illegal: /\S/, + contains: [ + 'self', + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Component sections + { + begin: '^' + IDENTIFIER, + end: /\}/, + contains: [ + PROPERTY, + hljs.HASH_COMMENT_MODE + ] + }, + + // Comments + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = roboconf; + + +/***/ }), + +/***/ 13071: +/***/ ((module) => { + +/* +Language: Microtik RouterOS script +Author: Ivan Dementev +Description: Scripting host provides a way to automate some router maintenance tasks by means of executing user-defined scripts bounded to some event occurrence +Website: https://wiki.mikrotik.com/wiki/Manual:Scripting +*/ + +// Colors from RouterOS terminal: +// green - #0E9A00 +// teal - #0C9A9A +// purple - #99069A +// light-brown - #9A9900 + +function routeros(hljs) { + const STATEMENTS = 'foreach do while for if from to step else on-error and or not in'; + + // Global commands: Every global command should start with ":" token, otherwise it will be treated as variable. + const GLOBAL_COMMANDS = 'global local beep delay put len typeof pick log time set find environment terminal error execute parse resolve toarray tobool toid toip toip6 tonum tostr totime'; + + // Common commands: Following commands available from most sub-menus: + const COMMON_COMMANDS = 'add remove enable disable set get print export edit find run debug error info warning'; + + const LITERALS = 'true false yes no nothing nil null'; + + const OBJECTS = 'traffic-flow traffic-generator firewall scheduler aaa accounting address-list address align area bandwidth-server bfd bgp bridge client clock community config connection console customer default dhcp-client dhcp-server discovery dns e-mail ethernet filter firmware gps graphing group hardware health hotspot identity igmp-proxy incoming instance interface ip ipsec ipv6 irq l2tp-server lcd ldp logging mac-server mac-winbox mangle manual mirror mme mpls nat nd neighbor network note ntp ospf ospf-v3 ovpn-server page peer pim ping policy pool port ppp pppoe-client pptp-server prefix profile proposal proxy queue radius resource rip ripng route routing screen script security-profiles server service service-port settings shares smb sms sniffer snmp snooper socks sstp-server system tool tracking type upgrade upnp user-manager users user vlan secret vrrp watchdog web-access wireless pptp pppoe lan wan layer7-protocol lease simple raw'; + + const VAR = { + className: 'variable', + variants: [ + { + begin: /\$[\w\d#@][\w\d_]*/ + }, + { + begin: /\$\{(.*?)\}/ + } + ] + }; + + const QUOTE_STRING = { + className: 'string', + begin: /"/, + end: /"/, + contains: [ + hljs.BACKSLASH_ESCAPE, + VAR, + { + className: 'variable', + begin: /\$\(/, + end: /\)/, + contains: [ hljs.BACKSLASH_ESCAPE ] + } + ] + }; + + const APOS_STRING = { + className: 'string', + begin: /'/, + end: /'/ + }; + + return { + name: 'Microtik RouterOS script', + aliases: [ + 'mikrotik' + ], + case_insensitive: true, + keywords: { + $pattern: /:?[\w-]+/, + literal: LITERALS, + keyword: STATEMENTS + ' :' + STATEMENTS.split(' ').join(' :') + ' :' + GLOBAL_COMMANDS.split(' ').join(' :') + }, + contains: [ + { // illegal syntax + variants: [ + { // -- comment + begin: /\/\*/, + end: /\*\// + }, + { // Stan comment + begin: /\/\//, + end: /$/ + }, + { // HTML tags + begin: /<\//, + end: />/ + } + ], + illegal: /./ + }, + hljs.COMMENT('^#', '$'), + QUOTE_STRING, + APOS_STRING, + VAR, + // attribute=value + { + // > is to avoid matches with => in other grammars + begin: /[\w-]+=([^\s{}[\]()>]+)/, + relevance: 0, + returnBegin: true, + contains: [ + { + className: 'attribute', + begin: /[^=]+/ + }, + { + begin: /=/, + endsWithParent: true, + relevance: 0, + contains: [ + QUOTE_STRING, + APOS_STRING, + VAR, + { + className: 'literal', + begin: '\\b(' + LITERALS.split(' ').join('|') + ')\\b' + }, + { + // Do not format unclassified values. Needed to exclude highlighting of values as built_in. + begin: /("[^"]*"|[^\s{}[\]]+)/ + } + /* + { + // IPv4 addresses and subnets + className: 'number', + variants: [ + {begin: IPADDR_wBITMASK+'(,'+IPADDR_wBITMASK+')*'}, //192.168.0.0/24,1.2.3.0/24 + {begin: IPADDR+'-'+IPADDR}, // 192.168.0.1-192.168.0.3 + {begin: IPADDR+'(,'+IPADDR+')*'}, // 192.168.0.1,192.168.0.34,192.168.24.1,192.168.0.1 + ] + }, + { + // MAC addresses and DHCP Client IDs + className: 'number', + begin: /\b(1:)?([0-9A-Fa-f]{1,2}[:-]){5}([0-9A-Fa-f]){1,2}\b/, + }, + */ + ] + } + ] + }, + { + // HEX values + className: 'number', + begin: /\*[0-9a-fA-F]+/ + }, + { + begin: '\\b(' + COMMON_COMMANDS.split(' ').join('|') + ')([\\s[(\\]|])', + returnBegin: true, + contains: [ + { + className: 'builtin-name', // 'function', + begin: /\w+/ + } + ] + }, + { + className: 'built_in', + variants: [ + { + begin: '(\\.\\./|/|\\s)((' + OBJECTS.split(' ').join('|') + ');?\\s)+' + }, + { + begin: /\.\./, + relevance: 0 + } + ] + } + ] + }; +} + +module.exports = routeros; + + +/***/ }), + +/***/ 17355: +/***/ ((module) => { + +/* +Language: RenderMan RSL +Author: Konstantin Evdokimenko +Contributors: Shuen-Huei Guan +Website: https://renderman.pixar.com/resources/RenderMan_20/shadingLanguage.html +Category: graphics +*/ + +function rsl(hljs) { + return { + name: 'RenderMan RSL', + keywords: { + keyword: + 'float color point normal vector matrix while for if do return else break extern continue', + built_in: + 'abs acos ambient area asin atan atmosphere attribute calculatenormal ceil cellnoise ' + + 'clamp comp concat cos degrees depth Deriv diffuse distance Du Dv environment exp ' + + 'faceforward filterstep floor format fresnel incident length lightsource log match ' + + 'max min mod noise normalize ntransform opposite option phong pnoise pow printf ' + + 'ptlined radians random reflect refract renderinfo round setcomp setxcomp setycomp ' + + 'setzcomp shadow sign sin smoothstep specular specularbrdf spline sqrt step tan ' + + 'texture textureinfo trace transform vtransform xcomp ycomp zcomp' + }, + illegal: ' { + +/* +Language: Oracle Rules Language +Author: Jason Jacobson +Description: The Oracle Utilities Rules Language is used to program the Oracle Utilities Applications acquired from LODESTAR Corporation. The products include Billing Component, LPSS, Pricing Component etc. through version 1.6.1. +Website: https://docs.oracle.com/cd/E17904_01/dev.1111/e10227/rlref.htm +Category: enterprise +*/ + +function ruleslanguage(hljs) { + return { + name: 'Oracle Rules Language', + keywords: { + keyword: + 'BILL_PERIOD BILL_START BILL_STOP RS_EFFECTIVE_START RS_EFFECTIVE_STOP RS_JURIS_CODE RS_OPCO_CODE ' + + 'INTDADDATTRIBUTE|5 INTDADDVMSG|5 INTDBLOCKOP|5 INTDBLOCKOPNA|5 INTDCLOSE|5 INTDCOUNT|5 ' + + 'INTDCOUNTSTATUSCODE|5 INTDCREATEMASK|5 INTDCREATEDAYMASK|5 INTDCREATEFACTORMASK|5 ' + + 'INTDCREATEHANDLE|5 INTDCREATEOVERRIDEDAYMASK|5 INTDCREATEOVERRIDEMASK|5 ' + + 'INTDCREATESTATUSCODEMASK|5 INTDCREATETOUPERIOD|5 INTDDELETE|5 INTDDIPTEST|5 INTDEXPORT|5 ' + + 'INTDGETERRORCODE|5 INTDGETERRORMESSAGE|5 INTDISEQUAL|5 INTDJOIN|5 INTDLOAD|5 INTDLOADACTUALCUT|5 ' + + 'INTDLOADDATES|5 INTDLOADHIST|5 INTDLOADLIST|5 INTDLOADLISTDATES|5 INTDLOADLISTENERGY|5 ' + + 'INTDLOADLISTHIST|5 INTDLOADRELATEDCHANNEL|5 INTDLOADSP|5 INTDLOADSTAGING|5 INTDLOADUOM|5 ' + + 'INTDLOADUOMDATES|5 INTDLOADUOMHIST|5 INTDLOADVERSION|5 INTDOPEN|5 INTDREADFIRST|5 INTDREADNEXT|5 ' + + 'INTDRECCOUNT|5 INTDRELEASE|5 INTDREPLACE|5 INTDROLLAVG|5 INTDROLLPEAK|5 INTDSCALAROP|5 INTDSCALE|5 ' + + 'INTDSETATTRIBUTE|5 INTDSETDSTPARTICIPANT|5 INTDSETSTRING|5 INTDSETVALUE|5 INTDSETVALUESTATUS|5 ' + + 'INTDSHIFTSTARTTIME|5 INTDSMOOTH|5 INTDSORT|5 INTDSPIKETEST|5 INTDSUBSET|5 INTDTOU|5 ' + + 'INTDTOURELEASE|5 INTDTOUVALUE|5 INTDUPDATESTATS|5 INTDVALUE|5 STDEV INTDDELETEEX|5 ' + + 'INTDLOADEXACTUAL|5 INTDLOADEXCUT|5 INTDLOADEXDATES|5 INTDLOADEX|5 INTDLOADEXRELATEDCHANNEL|5 ' + + 'INTDSAVEEX|5 MVLOAD|5 MVLOADACCT|5 MVLOADACCTDATES|5 MVLOADACCTHIST|5 MVLOADDATES|5 MVLOADHIST|5 ' + + 'MVLOADLIST|5 MVLOADLISTDATES|5 MVLOADLISTHIST|5 IF FOR NEXT DONE SELECT END CALL ABORT CLEAR CHANNEL FACTOR LIST NUMBER ' + + 'OVERRIDE SET WEEK DISTRIBUTIONNODE ELSE WHEN THEN OTHERWISE IENUM CSV INCLUDE LEAVE RIDER SAVE DELETE ' + + 'NOVALUE SECTION WARN SAVE_UPDATE DETERMINANT LABEL REPORT REVENUE EACH ' + + 'IN FROM TOTAL CHARGE BLOCK AND OR CSV_FILE RATE_CODE AUXILIARY_DEMAND ' + + 'UIDACCOUNT RS BILL_PERIOD_SELECT HOURS_PER_MONTH INTD_ERROR_STOP SEASON_SCHEDULE_NAME ' + + 'ACCOUNTFACTOR ARRAYUPPERBOUND CALLSTOREDPROC GETADOCONNECTION GETCONNECT GETDATASOURCE ' + + 'GETQUALIFIER GETUSERID HASVALUE LISTCOUNT LISTOP LISTUPDATE LISTVALUE PRORATEFACTOR RSPRORATE ' + + 'SETBINPATH SETDBMONITOR WQ_OPEN BILLINGHOURS DATE DATEFROMFLOAT DATETIMEFROMSTRING ' + + 'DATETIMETOSTRING DATETOFLOAT DAY DAYDIFF DAYNAME DBDATETIME HOUR MINUTE MONTH MONTHDIFF ' + + 'MONTHHOURS MONTHNAME ROUNDDATE SAMEWEEKDAYLASTYEAR SECOND WEEKDAY WEEKDIFF YEAR YEARDAY ' + + 'YEARSTR COMPSUM HISTCOUNT HISTMAX HISTMIN HISTMINNZ HISTVALUE MAXNRANGE MAXRANGE MINRANGE ' + + 'COMPIKVA COMPKVA COMPKVARFROMKQKW COMPLF IDATTR FLAG LF2KW LF2KWH MAXKW POWERFACTOR ' + + 'READING2USAGE AVGSEASON MAXSEASON MONTHLYMERGE SEASONVALUE SUMSEASON ACCTREADDATES ' + + 'ACCTTABLELOAD CONFIGADD CONFIGGET CREATEOBJECT CREATEREPORT EMAILCLIENT EXPBLKMDMUSAGE ' + + 'EXPMDMUSAGE EXPORT_USAGE FACTORINEFFECT GETUSERSPECIFIEDSTOP INEFFECT ISHOLIDAY RUNRATE ' + + 'SAVE_PROFILE SETREPORTTITLE USEREXIT WATFORRUNRATE TO TABLE ACOS ASIN ATAN ATAN2 BITAND CEIL ' + + 'COS COSECANT COSH COTANGENT DIVQUOT DIVREM EXP FABS FLOOR FMOD FREPM FREXPN LOG LOG10 MAX MAXN ' + + 'MIN MINNZ MODF POW ROUND ROUND2VALUE ROUNDINT SECANT SIN SINH SQROOT TAN TANH FLOAT2STRING ' + + 'FLOAT2STRINGNC INSTR LEFT LEN LTRIM MID RIGHT RTRIM STRING STRINGNC TOLOWER TOUPPER TRIM ' + + 'NUMDAYS READ_DATE STAGING', + built_in: + 'IDENTIFIER OPTIONS XML_ELEMENT XML_OP XML_ELEMENT_OF DOMDOCCREATE DOMDOCLOADFILE DOMDOCLOADXML ' + + 'DOMDOCSAVEFILE DOMDOCGETROOT DOMDOCADDPI DOMNODEGETNAME DOMNODEGETTYPE DOMNODEGETVALUE DOMNODEGETCHILDCT ' + + 'DOMNODEGETFIRSTCHILD DOMNODEGETSIBLING DOMNODECREATECHILDELEMENT DOMNODESETATTRIBUTE ' + + 'DOMNODEGETCHILDELEMENTCT DOMNODEGETFIRSTCHILDELEMENT DOMNODEGETSIBLINGELEMENT DOMNODEGETATTRIBUTECT ' + + 'DOMNODEGETATTRIBUTEI DOMNODEGETATTRIBUTEBYNAME DOMNODEGETBYNAME' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'literal', + variants: [ + { // looks like #-comment + begin: '#\\s+', + relevance: 0 + }, + { + begin: '#[a-zA-Z .]+' + } + ] + } + ] + }; +} + +module.exports = ruleslanguage; + + +/***/ }), + +/***/ 48775: +/***/ ((module) => { + +/* +Language: SAS +Author: Mauricio Caceres +Description: Syntax Highlighting for SAS +*/ + +function sas(hljs) { + // Data step and PROC SQL statements + const SAS_KEYWORDS = + 'do if then else end until while ' + + '' + + 'abort array attrib by call cards cards4 catname continue ' + + 'datalines datalines4 delete delim delimiter display dm drop ' + + 'endsas error file filename footnote format goto in infile ' + + 'informat input keep label leave length libname link list ' + + 'lostcard merge missing modify options output out page put ' + + 'redirect remove rename replace retain return select set skip ' + + 'startsas stop title update waitsas where window x systask ' + + '' + + 'add and alter as cascade check create delete describe ' + + 'distinct drop foreign from group having index insert into in ' + + 'key like message modify msgtype not null on or order primary ' + + 'references reset restrict select set table unique update ' + + 'validate view where'; + + // Built-in SAS functions + const SAS_FUN = + 'abs|addr|airy|arcos|arsin|atan|attrc|attrn|band|' + + 'betainv|blshift|bnot|bor|brshift|bxor|byte|cdf|ceil|' + + 'cexist|cinv|close|cnonct|collate|compbl|compound|' + + 'compress|cos|cosh|css|curobs|cv|daccdb|daccdbsl|' + + 'daccsl|daccsyd|dacctab|dairy|date|datejul|datepart|' + + 'datetime|day|dclose|depdb|depdbsl|depdbsl|depsl|' + + 'depsl|depsyd|depsyd|deptab|deptab|dequote|dhms|dif|' + + 'digamma|dim|dinfo|dnum|dopen|doptname|doptnum|dread|' + + 'dropnote|dsname|erf|erfc|exist|exp|fappend|fclose|' + + 'fcol|fdelete|fetch|fetchobs|fexist|fget|fileexist|' + + 'filename|fileref|finfo|finv|fipname|fipnamel|' + + 'fipstate|floor|fnonct|fnote|fopen|foptname|foptnum|' + + 'fpoint|fpos|fput|fread|frewind|frlen|fsep|fuzz|' + + 'fwrite|gaminv|gamma|getoption|getvarc|getvarn|hbound|' + + 'hms|hosthelp|hour|ibessel|index|indexc|indexw|input|' + + 'inputc|inputn|int|intck|intnx|intrr|irr|jbessel|' + + 'juldate|kurtosis|lag|lbound|left|length|lgamma|' + + 'libname|libref|log|log10|log2|logpdf|logpmf|logsdf|' + + 'lowcase|max|mdy|mean|min|minute|mod|month|mopen|' + + 'mort|n|netpv|nmiss|normal|note|npv|open|ordinal|' + + 'pathname|pdf|peek|peekc|pmf|point|poisson|poke|' + + 'probbeta|probbnml|probchi|probf|probgam|probhypr|' + + 'probit|probnegb|probnorm|probt|put|putc|putn|qtr|' + + 'quote|ranbin|rancau|ranexp|rangam|range|rank|rannor|' + + 'ranpoi|rantbl|rantri|ranuni|repeat|resolve|reverse|' + + 'rewind|right|round|saving|scan|sdf|second|sign|' + + 'sin|sinh|skewness|soundex|spedis|sqrt|std|stderr|' + + 'stfips|stname|stnamel|substr|sum|symget|sysget|' + + 'sysmsg|sysprod|sysrc|system|tan|tanh|time|timepart|' + + 'tinv|tnonct|today|translate|tranwrd|trigamma|' + + 'trim|trimn|trunc|uniform|upcase|uss|var|varfmt|' + + 'varinfmt|varlabel|varlen|varname|varnum|varray|' + + 'varrayx|vartype|verify|vformat|vformatd|vformatdx|' + + 'vformatn|vformatnx|vformatw|vformatwx|vformatx|' + + 'vinarray|vinarrayx|vinformat|vinformatd|vinformatdx|' + + 'vinformatn|vinformatnx|vinformatw|vinformatwx|' + + 'vinformatx|vlabel|vlabelx|vlength|vlengthx|vname|' + + 'vnamex|vtype|vtypex|weekday|year|yyq|zipfips|zipname|' + + 'zipnamel|zipstate'; + + // Built-in macro functions + const SAS_MACRO_FUN = + 'bquote|nrbquote|cmpres|qcmpres|compstor|' + + 'datatyp|display|do|else|end|eval|global|goto|' + + 'if|index|input|keydef|label|left|length|let|' + + 'local|lowcase|macro|mend|nrbquote|nrquote|' + + 'nrstr|put|qcmpres|qleft|qlowcase|qscan|' + + 'qsubstr|qsysfunc|qtrim|quote|qupcase|scan|str|' + + 'substr|superq|syscall|sysevalf|sysexec|sysfunc|' + + 'sysget|syslput|sysprod|sysrc|sysrput|then|to|' + + 'trim|unquote|until|upcase|verify|while|window'; + + return { + name: 'SAS', + case_insensitive: true, // SAS is case-insensitive + keywords: { + literal: + 'null missing _all_ _automatic_ _character_ _infile_ ' + + '_n_ _name_ _null_ _numeric_ _user_ _webout_', + meta: + SAS_KEYWORDS + }, + contains: [ + { + // Distinct highlight for proc , data, run, quit + className: 'keyword', + begin: /^\s*(proc [\w\d_]+|data|run|quit)[\s;]/ + }, + { + // Macro variables + className: 'variable', + begin: /&[a-zA-Z_&][a-zA-Z0-9_]*\.?/ + }, + { + // Special emphasis for datalines|cards + className: 'emphasis', + begin: /^\s*datalines|cards.*;/, + end: /^\s*;\s*$/ + }, + { // Built-in macro variables take precedence + className: 'built_in', + begin: '%(' + SAS_MACRO_FUN + ')' + }, + { + // User-defined macro functions highlighted after + className: 'name', + begin: /%[a-zA-Z_][a-zA-Z_0-9]*/ + }, + { + className: 'meta', + begin: '[^%](' + SAS_FUN + ')[\(]' + }, + { + className: 'string', + variants: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + }, + hljs.COMMENT('\\*', ';'), + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = sas; + + +/***/ }), + +/***/ 77359: +/***/ ((module) => { + +/* +Language: Scheme +Description: Scheme is a programming language in the Lisp family. + (keywords based on http://community.schemewiki.org/?scheme-keywords) +Author: JP Verkamp +Contributors: Ivan Sagalaev +Origin: clojure.js +Website: http://community.schemewiki.org/?what-is-scheme +Category: lisp +*/ + +function scheme(hljs) { + const SCHEME_IDENT_RE = '[^\\(\\)\\[\\]\\{\\}",\'`;#|\\\\\\s]+'; + const SCHEME_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+([./]\\d+)?'; + const SCHEME_COMPLEX_NUMBER_RE = SCHEME_SIMPLE_NUMBER_RE + '[+\\-]' + SCHEME_SIMPLE_NUMBER_RE + 'i'; + const KEYWORDS = { + $pattern: SCHEME_IDENT_RE, + 'builtin-name': + 'case-lambda call/cc class define-class exit-handler field import ' + + 'inherit init-field interface let*-values let-values let/ec mixin ' + + 'opt-lambda override protect provide public rename require ' + + 'require-for-syntax syntax syntax-case syntax-error unit/sig unless ' + + 'when with-syntax and begin call-with-current-continuation ' + + 'call-with-input-file call-with-output-file case cond define ' + + 'define-syntax delay do dynamic-wind else for-each if lambda let let* ' + + 'let-syntax letrec letrec-syntax map or syntax-rules \' * + , ,@ - ... / ' + + '; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan ' + + 'boolean? caar cadr call-with-input-file call-with-output-file ' + + 'call-with-values car cdddar cddddr cdr ceiling char->integer ' + + 'char-alphabetic? char-ci<=? char-ci=? char-ci>? ' + + 'char-downcase char-lower-case? char-numeric? char-ready? char-upcase ' + + 'char-upper-case? char-whitespace? char<=? char=? char>? ' + + 'char? close-input-port close-output-port complex? cons cos ' + + 'current-input-port current-output-port denominator display eof-object? ' + + 'eq? equal? eqv? eval even? exact->inexact exact? exp expt floor ' + + 'force gcd imag-part inexact->exact inexact? input-port? integer->char ' + + 'integer? interaction-environment lcm length list list->string ' + + 'list->vector list-ref list-tail list? load log magnitude make-polar ' + + 'make-rectangular make-string make-vector max member memq memv min ' + + 'modulo negative? newline not null-environment null? number->string ' + + 'number? numerator odd? open-input-file open-output-file output-port? ' + + 'pair? peek-char port? positive? procedure? quasiquote quote quotient ' + + 'rational? rationalize read read-char real-part real? remainder reverse ' + + 'round scheme-report-environment set! set-car! set-cdr! sin sqrt string ' + + 'string->list string->number string->symbol string-append string-ci<=? ' + + 'string-ci=? string-ci>? string-copy ' + + 'string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? ' + + 'tan transcript-off transcript-on truncate values vector ' + + 'vector->list vector-fill! vector-length vector-ref vector-set! ' + + 'with-input-from-file with-output-to-file write write-char zero?' + }; + + const LITERAL = { + className: 'literal', + begin: '(#t|#f|#\\\\' + SCHEME_IDENT_RE + '|#\\\\.)' + }; + + const NUMBER = { + className: 'number', + variants: [ + { + begin: SCHEME_SIMPLE_NUMBER_RE, + relevance: 0 + }, + { + begin: SCHEME_COMPLEX_NUMBER_RE, + relevance: 0 + }, + { + begin: '#b[0-1]+(/[0-1]+)?' + }, + { + begin: '#o[0-7]+(/[0-7]+)?' + }, + { + begin: '#x[0-9a-f]+(/[0-9a-f]+)?' + } + ] + }; + + const STRING = hljs.QUOTE_STRING_MODE; + + const COMMENT_MODES = [ + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + hljs.COMMENT('#\\|', '\\|#') + ]; + + const IDENT = { + begin: SCHEME_IDENT_RE, + relevance: 0 + }; + + const QUOTED_IDENT = { + className: 'symbol', + begin: '\'' + SCHEME_IDENT_RE + }; + + const BODY = { + endsWithParent: true, + relevance: 0 + }; + + const QUOTED_LIST = { + variants: [ + { + begin: /'/ + }, + { + begin: '`' + } + ], + contains: [ + { + begin: '\\(', + end: '\\)', + contains: [ + 'self', + LITERAL, + STRING, + NUMBER, + IDENT, + QUOTED_IDENT + ] + } + ] + }; + + const NAME = { + className: 'name', + relevance: 0, + begin: SCHEME_IDENT_RE, + keywords: KEYWORDS + }; + + const LAMBDA = { + begin: /lambda/, + endsWithParent: true, + returnBegin: true, + contains: [ + NAME, + { + endsParent: true, + variants: [ + { + begin: /\(/, + end: /\)/ + }, + { + begin: /\[/, + end: /\]/ + } + ], + contains: [ IDENT ] + } + ] + }; + + const LIST = { + variants: [ + { + begin: '\\(', + end: '\\)' + }, + { + begin: '\\[', + end: '\\]' + } + ], + contains: [ + LAMBDA, + NAME, + BODY + ] + }; + + BODY.contains = [ + LITERAL, + NUMBER, + STRING, + IDENT, + QUOTED_IDENT, + QUOTED_LIST, + LIST + ].concat(COMMENT_MODES); + + return { + name: 'Scheme', + illegal: /\S/, + contains: [ + hljs.SHEBANG(), + NUMBER, + STRING, + QUOTED_IDENT, + QUOTED_LIST, + LIST + ].concat(COMMENT_MODES) + }; +} + +module.exports = scheme; + + +/***/ }), + +/***/ 10348: +/***/ ((module) => { + +/* +Language: Scilab +Author: Sylvestre Ledru +Origin: matlab.js +Description: Scilab is a port from Matlab +Website: https://www.scilab.org +Category: scientific +*/ + +function scilab(hljs) { + const COMMON_CONTAINS = [ + hljs.C_NUMBER_MODE, + { + className: 'string', + begin: '\'|\"', + end: '\'|\"', + contains: [ hljs.BACKSLASH_ESCAPE, + { + begin: '\'\'' + } ] + } + ]; + + return { + name: 'Scilab', + aliases: [ 'sci' ], + keywords: { + $pattern: /%?\w+/, + keyword: 'abort break case clear catch continue do elseif else endfunction end for function ' + + 'global if pause return resume select try then while', + literal: + '%f %F %t %T %pi %eps %inf %nan %e %i %z %s', + built_in: // Scilab has more than 2000 functions. Just list the most commons + 'abs and acos asin atan ceil cd chdir clearglobal cosh cos cumprod deff disp error ' + + 'exec execstr exists exp eye gettext floor fprintf fread fsolve imag isdef isempty ' + + 'isinfisnan isvector lasterror length load linspace list listfiles log10 log2 log ' + + 'max min msprintf mclose mopen ones or pathconvert poly printf prod pwd rand real ' + + 'round sinh sin size gsort sprintf sqrt strcat strcmps tring sum system tanh tan ' + + 'type typename warning zeros matrix' + }, + illegal: '("|#|/\\*|\\s+/\\w+)', + contains: [ + { + className: 'function', + beginKeywords: 'function', + end: '$', + contains: [ + hljs.UNDERSCORE_TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)' + } + ] + }, + // seems to be a guard against [ident]' or [ident]. + // perhaps to prevent attributes from flagging as keywords? + { + begin: '[a-zA-Z_][a-zA-Z_0-9]*[\\.\']+', + relevance: 0 + }, + { + begin: '\\[', + end: '\\][\\.\']*', + relevance: 0, + contains: COMMON_CONTAINS + }, + hljs.COMMENT('//', '$') + ].concat(COMMON_CONTAINS) + }; +} + +module.exports = scilab; + + +/***/ }), + +/***/ 69908: +/***/ ((module) => { + +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/* +Language: SCSS +Description: Scss is an extension of the syntax of CSS. +Author: Kurt Emch +Website: https://sass-lang.com +Category: common, css +*/ + +/** @type LanguageFn */ +function scss(hljs) { + const modes = MODES(hljs); + const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS; + const PSEUDO_CLASSES$1 = PSEUDO_CLASSES; + + const AT_IDENTIFIER = '@[a-z-]+'; // @font-face + const AT_MODIFIERS = "and or not only"; + const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*'; + const VARIABLE = { + className: 'variable', + begin: '(\\$' + IDENT_RE + ')\\b' + }; + + return { + name: 'SCSS', + case_insensitive: true, + illegal: '[=/|\']', + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'selector-id', + begin: '#[A-Za-z0-9_-]+', + relevance: 0 + }, + { + className: 'selector-class', + begin: '\\.[A-Za-z0-9_-]+', + relevance: 0 + }, + modes.ATTRIBUTE_SELECTOR_MODE, + { + className: 'selector-tag', + begin: '\\b(' + TAGS.join('|') + ')\\b', + // was there, before, but why? + relevance: 0 + }, + { + className: 'selector-pseudo', + begin: ':(' + PSEUDO_CLASSES$1.join('|') + ')' + }, + { + className: 'selector-pseudo', + begin: '::(' + PSEUDO_ELEMENTS$1.join('|') + ')' + }, + VARIABLE, + { // pseudo-selector params + begin: /\(/, + end: /\)/, + contains: [ hljs.CSS_NUMBER_MODE ] + }, + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b' + }, + { + begin: '\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b' + }, + { + begin: ':', + end: ';', + contains: [ + VARIABLE, + modes.HEXCOLOR, + hljs.CSS_NUMBER_MODE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + modes.IMPORTANT + ] + }, + // matching these here allows us to treat them more like regular CSS + // rules so everything between the {} gets regular rule highlighting, + // which is what we want for page and font-face + { + begin: '@(page|font-face)', + lexemes: AT_IDENTIFIER, + keywords: '@page @font-face' + }, + { + begin: '@', + end: '[{;]', + returnBegin: true, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ + { + begin: AT_IDENTIFIER, + className: "keyword" + }, + { + begin: /[a-z-]+(?=:)/, + className: "attribute" + }, + VARIABLE, + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + modes.HEXCOLOR, + hljs.CSS_NUMBER_MODE + ] + } + ] + }; +} + +module.exports = scss; + + +/***/ }), + +/***/ 52836: +/***/ ((module) => { + +/* +Language: Shell Session +Requires: bash.js +Author: TSUYUSATO Kitsune +Category: common +Audit: 2020 +*/ + +/** @type LanguageFn */ +function shell(hljs) { + return { + name: 'Shell Session', + aliases: [ 'console' ], + contains: [ + { + className: 'meta', + // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result. + // For instance, in the following example, it would match "echo /path/to/home >" as a prompt: + // echo /path/to/home > t.exe + begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#]/, + starts: { + end: /[^\\](?=\s*$)/, + subLanguage: 'bash' + } + } + ] + }; +} + +module.exports = shell; + + +/***/ }), + +/***/ 62602: +/***/ ((module) => { + +/* +Language: Smali +Author: Dennis Titze +Description: Basic Smali highlighting +Website: https://github.com/JesusFreke/smali +*/ + +function smali(hljs) { + const smali_instr_low_prio = [ + 'add', + 'and', + 'cmp', + 'cmpg', + 'cmpl', + 'const', + 'div', + 'double', + 'float', + 'goto', + 'if', + 'int', + 'long', + 'move', + 'mul', + 'neg', + 'new', + 'nop', + 'not', + 'or', + 'rem', + 'return', + 'shl', + 'shr', + 'sput', + 'sub', + 'throw', + 'ushr', + 'xor' + ]; + const smali_instr_high_prio = [ + 'aget', + 'aput', + 'array', + 'check', + 'execute', + 'fill', + 'filled', + 'goto/16', + 'goto/32', + 'iget', + 'instance', + 'invoke', + 'iput', + 'monitor', + 'packed', + 'sget', + 'sparse' + ]; + const smali_keywords = [ + 'transient', + 'constructor', + 'abstract', + 'final', + 'synthetic', + 'public', + 'private', + 'protected', + 'static', + 'bridge', + 'system' + ]; + return { + name: 'Smali', + contains: [ + { + className: 'string', + begin: '"', + end: '"', + relevance: 0 + }, + hljs.COMMENT( + '#', + '$', + { + relevance: 0 + } + ), + { + className: 'keyword', + variants: [ + { + begin: '\\s*\\.end\\s[a-zA-Z0-9]*' + }, + { + begin: '^[ ]*\\.[a-zA-Z]*', + relevance: 0 + }, + { + begin: '\\s:[a-zA-Z_0-9]*', + relevance: 0 + }, + { + begin: '\\s(' + smali_keywords.join('|') + ')' + } + ] + }, + { + className: 'built_in', + variants: [ + { + begin: '\\s(' + smali_instr_low_prio.join('|') + ')\\s' + }, + { + begin: '\\s(' + smali_instr_low_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)+\\s', + relevance: 10 + }, + { + begin: '\\s(' + smali_instr_high_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)*\\s', + relevance: 10 + } + ] + }, + { + className: 'class', + begin: 'L[^\(;:\n]*;', + relevance: 0 + }, + { + begin: '[vp][0-9]+' + } + ] + }; +} + +module.exports = smali; + + +/***/ }), + +/***/ 70787: +/***/ ((module) => { + +/* +Language: Smalltalk +Description: Smalltalk is an object-oriented, dynamically typed reflective programming language. +Author: Vladimir Gubarkov +Website: https://en.wikipedia.org/wiki/Smalltalk +*/ + +function smalltalk(hljs) { + const VAR_IDENT_RE = '[a-z][a-zA-Z0-9_]*'; + const CHAR = { + className: 'string', + begin: '\\$.{1}' + }; + const SYMBOL = { + className: 'symbol', + begin: '#' + hljs.UNDERSCORE_IDENT_RE + }; + return { + name: 'Smalltalk', + aliases: [ 'st' ], + keywords: 'self super nil true false thisContext', // only 6 + contains: [ + hljs.COMMENT('"', '"'), + hljs.APOS_STRING_MODE, + { + className: 'type', + begin: '\\b[A-Z][A-Za-z0-9_]*', + relevance: 0 + }, + { + begin: VAR_IDENT_RE + ':', + relevance: 0 + }, + hljs.C_NUMBER_MODE, + SYMBOL, + CHAR, + { + // This looks more complicated than needed to avoid combinatorial + // explosion under V8. It effectively means `| var1 var2 ... |` with + // whitespace adjacent to `|` being optional. + begin: '\\|[ ]*' + VAR_IDENT_RE + '([ ]+' + VAR_IDENT_RE + ')*[ ]*\\|', + returnBegin: true, + end: /\|/, + illegal: /\S/, + contains: [ { + begin: '(\\|[ ]*)?' + VAR_IDENT_RE + } ] + }, + { + begin: '#\\(', + end: '\\)', + contains: [ + hljs.APOS_STRING_MODE, + CHAR, + hljs.C_NUMBER_MODE, + SYMBOL + ] + } + ] + }; +} + +module.exports = smalltalk; + + +/***/ }), + +/***/ 92002: +/***/ ((module) => { + +/* +Language: SML (Standard ML) +Author: Edwin Dalorzo +Description: SML language definition. +Website: https://www.smlnj.org +Origin: ocaml.js +Category: functional +*/ +function sml(hljs) { + return { + name: 'SML (Standard ML)', + aliases: [ 'ml' ], + keywords: { + $pattern: '[a-z_]\\w*!?', + keyword: + /* according to Definition of Standard ML 97 */ + 'abstype and andalso as case datatype do else end eqtype ' + + 'exception fn fun functor handle if in include infix infixr ' + + 'let local nonfix of op open orelse raise rec sharing sig ' + + 'signature struct structure then type val with withtype where while', + built_in: + /* built-in types according to basis library */ + 'array bool char exn int list option order real ref string substring vector unit word', + literal: + 'true false NONE SOME LESS EQUAL GREATER nil' + }, + illegal: /\/\/|>>/, + contains: [ + { + className: 'literal', + begin: /\[(\|\|)?\]|\(\)/, + relevance: 0 + }, + hljs.COMMENT( + '\\(\\*', + '\\*\\)', + { + contains: [ 'self' ] + } + ), + { /* type variable */ + className: 'symbol', + begin: '\'[A-Za-z_](?!\')[\\w\']*' + /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */ + }, + { /* polymorphic variant */ + className: 'type', + begin: '`[A-Z][\\w\']*' + }, + { /* module or constructor */ + className: 'type', + begin: '\\b[A-Z][\\w\']*', + relevance: 0 + }, + { /* don't color identifiers, but safely catch all identifiers with ' */ + begin: '[a-z_]\\w*\'[\\w\']*' + }, + hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'string', + relevance: 0 + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'number', + begin: + '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' + + '0[oO][0-7_]+[Lln]?|' + + '0[bB][01_]+[Lln]?|' + + '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)', + relevance: 0 + }, + { + begin: /[-=]>/ // relevance booster + } + ] + }; +} + +module.exports = sml; + + +/***/ }), + +/***/ 11516: +/***/ ((module) => { + +/* +Language: SQF +Author: Søren Enevoldsen +Contributors: Marvin Saignat , Dedmen Miller +Description: Scripting language for the Arma game series +Website: https://community.bistudio.com/wiki/SQF_syntax +Category: scripting +*/ + +function sqf(hljs) { + // In SQF, a variable start with _ + const VARIABLE = { + className: 'variable', + begin: /\b_+[a-zA-Z]\w*/ + }; + + // In SQF, a function should fit myTag_fnc_myFunction pattern + // https://community.bistudio.com/wiki/Functions_Library_(Arma_3)#Adding_a_Function + const FUNCTION = { + className: 'title', + begin: /[a-zA-Z][a-zA-Z0-9]+_fnc_\w*/ + }; + + // In SQF strings, quotes matching the start are escaped by adding a consecutive. + // Example of single escaped quotes: " "" " and ' '' '. + const STRINGS = { + className: 'string', + variants: [ + { + begin: '"', + end: '"', + contains: [ { + begin: '""', + relevance: 0 + } ] + }, + { + begin: '\'', + end: '\'', + contains: [ { + begin: '\'\'', + relevance: 0 + } ] + } + ] + }; + + // list of keywords from: + // https://community.bistudio.com/wiki/PreProcessor_Commands + const PREPROCESSOR = { + className: 'meta', + begin: /#\s*[a-z]+\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'define undef ifdef ifndef else endif include' + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + hljs.inherit(STRINGS, { + className: 'meta-string' + }), + { + className: 'meta-string', + begin: /<[^\n>]*>/, + end: /$/, + illegal: '\\n' + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; + + return { + name: 'SQF', + case_insensitive: true, + keywords: { + keyword: + 'case catch default do else exit exitWith for forEach from if ' + + 'private switch then throw to try waitUntil while with', + built_in: + 'abs accTime acos action actionIDs actionKeys actionKeysImages actionKeysNames ' + + 'actionKeysNamesArray actionName actionParams activateAddons activatedAddons activateKey ' + + 'add3DENConnection add3DENEventHandler add3DENLayer addAction addBackpack addBackpackCargo ' + + 'addBackpackCargoGlobal addBackpackGlobal addCamShake addCuratorAddons addCuratorCameraArea ' + + 'addCuratorEditableObjects addCuratorEditingArea addCuratorPoints addEditorObject addEventHandler ' + + 'addForce addGoggles addGroupIcon addHandgunItem addHeadgear addItem addItemCargo ' + + 'addItemCargoGlobal addItemPool addItemToBackpack addItemToUniform addItemToVest addLiveStats ' + + 'addMagazine addMagazineAmmoCargo addMagazineCargo addMagazineCargoGlobal addMagazineGlobal ' + + 'addMagazinePool addMagazines addMagazineTurret addMenu addMenuItem addMissionEventHandler ' + + 'addMPEventHandler addMusicEventHandler addOwnedMine addPlayerScores addPrimaryWeaponItem ' + + 'addPublicVariableEventHandler addRating addResources addScore addScoreSide addSecondaryWeaponItem ' + + 'addSwitchableUnit addTeamMember addToRemainsCollector addTorque addUniform addVehicle addVest ' + + 'addWaypoint addWeapon addWeaponCargo addWeaponCargoGlobal addWeaponGlobal addWeaponItem ' + + 'addWeaponPool addWeaponTurret admin agent agents AGLToASL aimedAtTarget aimPos airDensityRTD ' + + 'airplaneThrottle airportSide AISFinishHeal alive all3DENEntities allAirports allControls ' + + 'allCurators allCutLayers allDead allDeadMen allDisplays allGroups allMapMarkers allMines ' + + 'allMissionObjects allow3DMode allowCrewInImmobile allowCuratorLogicIgnoreAreas allowDamage ' + + 'allowDammage allowFileOperations allowFleeing allowGetIn allowSprint allPlayers allSimpleObjects ' + + 'allSites allTurrets allUnits allUnitsUAV allVariables ammo ammoOnPylon and animate animateBay ' + + 'animateDoor animatePylon animateSource animationNames animationPhase animationSourcePhase ' + + 'animationState append apply armoryPoints arrayIntersect asin ASLToAGL ASLToATL assert ' + + 'assignAsCargo assignAsCargoIndex assignAsCommander assignAsDriver assignAsGunner assignAsTurret ' + + 'assignCurator assignedCargo assignedCommander assignedDriver assignedGunner assignedItems ' + + 'assignedTarget assignedTeam assignedVehicle assignedVehicleRole assignItem assignTeam ' + + 'assignToAirport atan atan2 atg ATLToASL attachedObject attachedObjects attachedTo attachObject ' + + 'attachTo attackEnabled backpack backpackCargo backpackContainer backpackItems backpackMagazines ' + + 'backpackSpaceFor behaviour benchmark binocular boundingBox boundingBoxReal boundingCenter ' + + 'breakOut breakTo briefingName buildingExit buildingPos buttonAction buttonSetAction cadetMode ' + + 'call callExtension camCommand camCommit camCommitPrepared camCommitted camConstuctionSetParams ' + + 'camCreate camDestroy cameraEffect cameraEffectEnableHUD cameraInterest cameraOn cameraView ' + + 'campaignConfigFile camPreload camPreloaded camPrepareBank camPrepareDir camPrepareDive ' + + 'camPrepareFocus camPrepareFov camPrepareFovRange camPreparePos camPrepareRelPos camPrepareTarget ' + + 'camSetBank camSetDir camSetDive camSetFocus camSetFov camSetFovRange camSetPos camSetRelPos ' + + 'camSetTarget camTarget camUseNVG canAdd canAddItemToBackpack canAddItemToUniform canAddItemToVest ' + + 'cancelSimpleTaskDestination canFire canMove canSlingLoad canStand canSuspend ' + + 'canTriggerDynamicSimulation canUnloadInCombat canVehicleCargo captive captiveNum cbChecked ' + + 'cbSetChecked ceil channelEnabled cheatsEnabled checkAIFeature checkVisibility className ' + + 'clearAllItemsFromBackpack clearBackpackCargo clearBackpackCargoGlobal clearGroupIcons ' + + 'clearItemCargo clearItemCargoGlobal clearItemPool clearMagazineCargo clearMagazineCargoGlobal ' + + 'clearMagazinePool clearOverlay clearRadio clearWeaponCargo clearWeaponCargoGlobal clearWeaponPool ' + + 'clientOwner closeDialog closeDisplay closeOverlay collapseObjectTree collect3DENHistory ' + + 'collectiveRTD combatMode commandArtilleryFire commandChat commander commandFire commandFollow ' + + 'commandFSM commandGetOut commandingMenu commandMove commandRadio commandStop ' + + 'commandSuppressiveFire commandTarget commandWatch comment commitOverlay compile compileFinal ' + + 'completedFSM composeText configClasses configFile configHierarchy configName configProperties ' + + 'configSourceAddonList configSourceMod configSourceModList confirmSensorTarget ' + + 'connectTerminalToUAV controlsGroupCtrl copyFromClipboard copyToClipboard copyWaypoints cos count ' + + 'countEnemy countFriendly countSide countType countUnknown create3DENComposition create3DENEntity ' + + 'createAgent createCenter createDialog createDiaryLink createDiaryRecord createDiarySubject ' + + 'createDisplay createGearDialog createGroup createGuardedPoint createLocation createMarker ' + + 'createMarkerLocal createMenu createMine createMissionDisplay createMPCampaignDisplay ' + + 'createSimpleObject createSimpleTask createSite createSoundSource createTask createTeam ' + + 'createTrigger createUnit createVehicle createVehicleCrew createVehicleLocal crew ctAddHeader ' + + 'ctAddRow ctClear ctCurSel ctData ctFindHeaderRows ctFindRowHeader ctHeaderControls ctHeaderCount ' + + 'ctRemoveHeaders ctRemoveRows ctrlActivate ctrlAddEventHandler ctrlAngle ctrlAutoScrollDelay ' + + 'ctrlAutoScrollRewind ctrlAutoScrollSpeed ctrlChecked ctrlClassName ctrlCommit ctrlCommitted ' + + 'ctrlCreate ctrlDelete ctrlEnable ctrlEnabled ctrlFade ctrlHTMLLoaded ctrlIDC ctrlIDD ' + + 'ctrlMapAnimAdd ctrlMapAnimClear ctrlMapAnimCommit ctrlMapAnimDone ctrlMapCursor ctrlMapMouseOver ' + + 'ctrlMapScale ctrlMapScreenToWorld ctrlMapWorldToScreen ctrlModel ctrlModelDirAndUp ctrlModelScale ' + + 'ctrlParent ctrlParentControlsGroup ctrlPosition ctrlRemoveAllEventHandlers ctrlRemoveEventHandler ' + + 'ctrlScale ctrlSetActiveColor ctrlSetAngle ctrlSetAutoScrollDelay ctrlSetAutoScrollRewind ' + + 'ctrlSetAutoScrollSpeed ctrlSetBackgroundColor ctrlSetChecked ctrlSetEventHandler ctrlSetFade ' + + 'ctrlSetFocus ctrlSetFont ctrlSetFontH1 ctrlSetFontH1B ctrlSetFontH2 ctrlSetFontH2B ctrlSetFontH3 ' + + 'ctrlSetFontH3B ctrlSetFontH4 ctrlSetFontH4B ctrlSetFontH5 ctrlSetFontH5B ctrlSetFontH6 ' + + 'ctrlSetFontH6B ctrlSetFontHeight ctrlSetFontHeightH1 ctrlSetFontHeightH2 ctrlSetFontHeightH3 ' + + 'ctrlSetFontHeightH4 ctrlSetFontHeightH5 ctrlSetFontHeightH6 ctrlSetFontHeightSecondary ' + + 'ctrlSetFontP ctrlSetFontPB ctrlSetFontSecondary ctrlSetForegroundColor ctrlSetModel ' + + 'ctrlSetModelDirAndUp ctrlSetModelScale ctrlSetPixelPrecision ctrlSetPosition ctrlSetScale ' + + 'ctrlSetStructuredText ctrlSetText ctrlSetTextColor ctrlSetTooltip ctrlSetTooltipColorBox ' + + 'ctrlSetTooltipColorShade ctrlSetTooltipColorText ctrlShow ctrlShown ctrlText ctrlTextHeight ' + + 'ctrlTextWidth ctrlType ctrlVisible ctRowControls ctRowCount ctSetCurSel ctSetData ' + + 'ctSetHeaderTemplate ctSetRowTemplate ctSetValue ctValue curatorAddons curatorCamera ' + + 'curatorCameraArea curatorCameraAreaCeiling curatorCoef curatorEditableObjects curatorEditingArea ' + + 'curatorEditingAreaType curatorMouseOver curatorPoints curatorRegisteredObjects curatorSelected ' + + 'curatorWaypointCost current3DENOperation currentChannel currentCommand currentMagazine ' + + 'currentMagazineDetail currentMagazineDetailTurret currentMagazineTurret currentMuzzle ' + + 'currentNamespace currentTask currentTasks currentThrowable currentVisionMode currentWaypoint ' + + 'currentWeapon currentWeaponMode currentWeaponTurret currentZeroing cursorObject cursorTarget ' + + 'customChat customRadio cutFadeOut cutObj cutRsc cutText damage date dateToNumber daytime ' + + 'deActivateKey debriefingText debugFSM debugLog deg delete3DENEntities deleteAt deleteCenter ' + + 'deleteCollection deleteEditorObject deleteGroup deleteGroupWhenEmpty deleteIdentity ' + + 'deleteLocation deleteMarker deleteMarkerLocal deleteRange deleteResources deleteSite deleteStatus ' + + 'deleteTeam deleteVehicle deleteVehicleCrew deleteWaypoint detach detectedMines ' + + 'diag_activeMissionFSMs diag_activeScripts diag_activeSQFScripts diag_activeSQSScripts ' + + 'diag_captureFrame diag_captureFrameToFile diag_captureSlowFrame diag_codePerformance ' + + 'diag_drawMode diag_enable diag_enabled diag_fps diag_fpsMin diag_frameNo diag_lightNewLoad ' + + 'diag_list diag_log diag_logSlowFrame diag_mergeConfigFile diag_recordTurretLimits ' + + 'diag_setLightNew diag_tickTime diag_toggle dialog diarySubjectExists didJIP didJIPOwner ' + + 'difficulty difficultyEnabled difficultyEnabledRTD difficultyOption direction directSay disableAI ' + + 'disableCollisionWith disableConversation disableDebriefingStats disableMapIndicators ' + + 'disableNVGEquipment disableRemoteSensors disableSerialization disableTIEquipment ' + + 'disableUAVConnectability disableUserInput displayAddEventHandler displayCtrl displayParent ' + + 'displayRemoveAllEventHandlers displayRemoveEventHandler displaySetEventHandler dissolveTeam ' + + 'distance distance2D distanceSqr distributionRegion do3DENAction doArtilleryFire doFire doFollow ' + + 'doFSM doGetOut doMove doorPhase doStop doSuppressiveFire doTarget doWatch drawArrow drawEllipse ' + + 'drawIcon drawIcon3D drawLine drawLine3D drawLink drawLocation drawPolygon drawRectangle ' + + 'drawTriangle driver drop dynamicSimulationDistance dynamicSimulationDistanceCoef ' + + 'dynamicSimulationEnabled dynamicSimulationSystemEnabled echo edit3DENMissionAttributes editObject ' + + 'editorSetEventHandler effectiveCommander emptyPositions enableAI enableAIFeature ' + + 'enableAimPrecision enableAttack enableAudioFeature enableAutoStartUpRTD enableAutoTrimRTD ' + + 'enableCamShake enableCaustics enableChannel enableCollisionWith enableCopilot ' + + 'enableDebriefingStats enableDiagLegend enableDynamicSimulation enableDynamicSimulationSystem ' + + 'enableEndDialog enableEngineArtillery enableEnvironment enableFatigue enableGunLights ' + + 'enableInfoPanelComponent enableIRLasers enableMimics enablePersonTurret enableRadio enableReload ' + + 'enableRopeAttach enableSatNormalOnDetail enableSaving enableSentences enableSimulation ' + + 'enableSimulationGlobal enableStamina enableTeamSwitch enableTraffic enableUAVConnectability ' + + 'enableUAVWaypoints enableVehicleCargo enableVehicleSensor enableWeaponDisassembly ' + + 'endLoadingScreen endMission engineOn enginesIsOnRTD enginesRpmRTD enginesTorqueRTD entities ' + + 'environmentEnabled estimatedEndServerTime estimatedTimeLeft evalObjectArgument everyBackpack ' + + 'everyContainer exec execEditorScript execFSM execVM exp expectedDestination exportJIPMessages ' + + 'eyeDirection eyePos face faction fadeMusic fadeRadio fadeSound fadeSpeech failMission ' + + 'fillWeaponsFromPool find findCover findDisplay findEditorObject findEmptyPosition ' + + 'findEmptyPositionReady findIf findNearestEnemy finishMissionInit finite fire fireAtTarget ' + + 'firstBackpack flag flagAnimationPhase flagOwner flagSide flagTexture fleeing floor flyInHeight ' + + 'flyInHeightASL fog fogForecast fogParams forceAddUniform forcedMap forceEnd forceFlagTexture ' + + 'forceFollowRoad forceMap forceRespawn forceSpeed forceWalk forceWeaponFire forceWeatherChange ' + + 'forEachMember forEachMemberAgent forEachMemberTeam forgetTarget format formation ' + + 'formationDirection formationLeader formationMembers formationPosition formationTask formatText ' + + 'formLeader freeLook fromEditor fuel fullCrew gearIDCAmmoCount gearSlotAmmoCount gearSlotData ' + + 'get3DENActionState get3DENAttribute get3DENCamera get3DENConnections get3DENEntity ' + + 'get3DENEntityID get3DENGrid get3DENIconsVisible get3DENLayerEntities get3DENLinesVisible ' + + 'get3DENMissionAttribute get3DENMouseOver get3DENSelected getAimingCoef getAllEnvSoundControllers ' + + 'getAllHitPointsDamage getAllOwnedMines getAllSoundControllers getAmmoCargo getAnimAimPrecision ' + + 'getAnimSpeedCoef getArray getArtilleryAmmo getArtilleryComputerSettings getArtilleryETA ' + + 'getAssignedCuratorLogic getAssignedCuratorUnit getBackpackCargo getBleedingRemaining ' + + 'getBurningValue getCameraViewDirection getCargoIndex getCenterOfMass getClientState ' + + 'getClientStateNumber getCompatiblePylonMagazines getConnectedUAV getContainerMaxLoad ' + + 'getCursorObjectParams getCustomAimCoef getDammage getDescription getDir getDirVisual ' + + 'getDLCAssetsUsage getDLCAssetsUsageByName getDLCs getEditorCamera getEditorMode ' + + 'getEditorObjectScope getElevationOffset getEnvSoundController getFatigue getForcedFlagTexture ' + + 'getFriend getFSMVariable getFuelCargo getGroupIcon getGroupIconParams getGroupIcons getHideFrom ' + + 'getHit getHitIndex getHitPointDamage getItemCargo getMagazineCargo getMarkerColor getMarkerPos ' + + 'getMarkerSize getMarkerType getMass getMissionConfig getMissionConfigValue getMissionDLCs ' + + 'getMissionLayerEntities getModelInfo getMousePosition getMusicPlayedTime getNumber ' + + 'getObjectArgument getObjectChildren getObjectDLC getObjectMaterials getObjectProxy ' + + 'getObjectTextures getObjectType getObjectViewDistance getOxygenRemaining getPersonUsedDLCs ' + + 'getPilotCameraDirection getPilotCameraPosition getPilotCameraRotation getPilotCameraTarget ' + + 'getPlateNumber getPlayerChannel getPlayerScores getPlayerUID getPos getPosASL getPosASLVisual ' + + 'getPosASLW getPosATL getPosATLVisual getPosVisual getPosWorld getPylonMagazines getRelDir ' + + 'getRelPos getRemoteSensorsDisabled getRepairCargo getResolution getShadowDistance getShotParents ' + + 'getSlingLoad getSoundController getSoundControllerResult getSpeed getStamina getStatValue ' + + 'getSuppression getTerrainGrid getTerrainHeightASL getText getTotalDLCUsageTime getUnitLoadout ' + + 'getUnitTrait getUserMFDText getUserMFDvalue getVariable getVehicleCargo getWeaponCargo ' + + 'getWeaponSway getWingsOrientationRTD getWingsPositionRTD getWPPos glanceAt globalChat globalRadio ' + + 'goggles goto group groupChat groupFromNetId groupIconSelectable groupIconsVisible groupId ' + + 'groupOwner groupRadio groupSelectedUnits groupSelectUnit gunner gusts halt handgunItems ' + + 'handgunMagazine handgunWeapon handsHit hasInterface hasPilotCamera hasWeapon hcAllGroups ' + + 'hcGroupParams hcLeader hcRemoveAllGroups hcRemoveGroup hcSelected hcSelectGroup hcSetGroup ' + + 'hcShowBar hcShownBar headgear hideBody hideObject hideObjectGlobal hideSelection hint hintC ' + + 'hintCadet hintSilent hmd hostMission htmlLoad HUDMovementLevels humidity image importAllGroups ' + + 'importance in inArea inAreaArray incapacitatedState inflame inflamed infoPanel ' + + 'infoPanelComponentEnabled infoPanelComponents infoPanels inGameUISetEventHandler inheritsFrom ' + + 'initAmbientLife inPolygon inputAction inRangeOfArtillery insertEditorObject intersect is3DEN ' + + 'is3DENMultiplayer isAbleToBreathe isAgent isArray isAutoHoverOn isAutonomous isAutotest ' + + 'isBleeding isBurning isClass isCollisionLightOn isCopilotEnabled isDamageAllowed isDedicated ' + + 'isDLCAvailable isEngineOn isEqualTo isEqualType isEqualTypeAll isEqualTypeAny isEqualTypeArray ' + + 'isEqualTypeParams isFilePatchingEnabled isFlashlightOn isFlatEmpty isForcedWalk isFormationLeader ' + + 'isGroupDeletedWhenEmpty isHidden isInRemainsCollector isInstructorFigureEnabled isIRLaserOn ' + + 'isKeyActive isKindOf isLaserOn isLightOn isLocalized isManualFire isMarkedForCollection ' + + 'isMultiplayer isMultiplayerSolo isNil isNull isNumber isObjectHidden isObjectRTD isOnRoad ' + + 'isPipEnabled isPlayer isRealTime isRemoteExecuted isRemoteExecutedJIP isServer isShowing3DIcons ' + + 'isSimpleObject isSprintAllowed isStaminaEnabled isSteamMission isStreamFriendlyUIEnabled isText ' + + 'isTouchingGround isTurnedOut isTutHintsEnabled isUAVConnectable isUAVConnected isUIContext ' + + 'isUniformAllowed isVehicleCargo isVehicleRadarOn isVehicleSensorEnabled isWalking ' + + 'isWeaponDeployed isWeaponRested itemCargo items itemsWithMagazines join joinAs joinAsSilent ' + + 'joinSilent joinString kbAddDatabase kbAddDatabaseTargets kbAddTopic kbHasTopic kbReact ' + + 'kbRemoveTopic kbTell kbWasSaid keyImage keyName knowsAbout land landAt landResult language ' + + 'laserTarget lbAdd lbClear lbColor lbColorRight lbCurSel lbData lbDelete lbIsSelected lbPicture ' + + 'lbPictureRight lbSelection lbSetColor lbSetColorRight lbSetCurSel lbSetData lbSetPicture ' + + 'lbSetPictureColor lbSetPictureColorDisabled lbSetPictureColorSelected lbSetPictureRight ' + + 'lbSetPictureRightColor lbSetPictureRightColorDisabled lbSetPictureRightColorSelected ' + + 'lbSetSelectColor lbSetSelectColorRight lbSetSelected lbSetText lbSetTextRight lbSetTooltip ' + + 'lbSetValue lbSize lbSort lbSortByValue lbText lbTextRight lbValue leader leaderboardDeInit ' + + 'leaderboardGetRows leaderboardInit leaderboardRequestRowsFriends leaderboardsRequestUploadScore ' + + 'leaderboardsRequestUploadScoreKeepBest leaderboardState leaveVehicle libraryCredits ' + + 'libraryDisclaimers lifeState lightAttachObject lightDetachObject lightIsOn lightnings limitSpeed ' + + 'linearConversion lineIntersects lineIntersectsObjs lineIntersectsSurfaces lineIntersectsWith ' + + 'linkItem list listObjects listRemoteTargets listVehicleSensors ln lnbAddArray lnbAddColumn ' + + 'lnbAddRow lnbClear lnbColor lnbCurSelRow lnbData lnbDeleteColumn lnbDeleteRow ' + + 'lnbGetColumnsPosition lnbPicture lnbSetColor lnbSetColumnsPos lnbSetCurSelRow lnbSetData ' + + 'lnbSetPicture lnbSetText lnbSetValue lnbSize lnbSort lnbSortByValue lnbText lnbValue load loadAbs ' + + 'loadBackpack loadFile loadGame loadIdentity loadMagazine loadOverlay loadStatus loadUniform ' + + 'loadVest local localize locationPosition lock lockCameraTo lockCargo lockDriver locked ' + + 'lockedCargo lockedDriver lockedTurret lockIdentity lockTurret lockWP log logEntities logNetwork ' + + 'logNetworkTerminate lookAt lookAtPos magazineCargo magazines magazinesAllTurrets magazinesAmmo ' + + 'magazinesAmmoCargo magazinesAmmoFull magazinesDetail magazinesDetailBackpack ' + + 'magazinesDetailUniform magazinesDetailVest magazinesTurret magazineTurretAmmo mapAnimAdd ' + + 'mapAnimClear mapAnimCommit mapAnimDone mapCenterOnCamera mapGridPosition markAsFinishedOnSteam ' + + 'markerAlpha markerBrush markerColor markerDir markerPos markerShape markerSize markerText ' + + 'markerType max members menuAction menuAdd menuChecked menuClear menuCollapse menuData menuDelete ' + + 'menuEnable menuEnabled menuExpand menuHover menuPicture menuSetAction menuSetCheck menuSetData ' + + 'menuSetPicture menuSetValue menuShortcut menuShortcutText menuSize menuSort menuText menuURL ' + + 'menuValue min mineActive mineDetectedBy missionConfigFile missionDifficulty missionName ' + + 'missionNamespace missionStart missionVersion mod modelToWorld modelToWorldVisual ' + + 'modelToWorldVisualWorld modelToWorldWorld modParams moonIntensity moonPhase morale move ' + + 'move3DENCamera moveInAny moveInCargo moveInCommander moveInDriver moveInGunner moveInTurret ' + + 'moveObjectToEnd moveOut moveTime moveTo moveToCompleted moveToFailed musicVolume name nameSound ' + + 'nearEntities nearestBuilding nearestLocation nearestLocations nearestLocationWithDubbing ' + + 'nearestObject nearestObjects nearestTerrainObjects nearObjects nearObjectsReady nearRoads ' + + 'nearSupplies nearTargets needReload netId netObjNull newOverlay nextMenuItemIndex ' + + 'nextWeatherChange nMenuItems not numberOfEnginesRTD numberToDate objectCurators objectFromNetId ' + + 'objectParent objStatus onBriefingGroup onBriefingNotes onBriefingPlan onBriefingTeamSwitch ' + + 'onCommandModeChanged onDoubleClick onEachFrame onGroupIconClick onGroupIconOverEnter ' + + 'onGroupIconOverLeave onHCGroupSelectionChanged onMapSingleClick onPlayerConnected ' + + 'onPlayerDisconnected onPreloadFinished onPreloadStarted onShowNewObject onTeamSwitch ' + + 'openCuratorInterface openDLCPage openMap openSteamApp openYoutubeVideo or orderGetIn overcast ' + + 'overcastForecast owner param params parseNumber parseSimpleArray parseText parsingNamespace ' + + 'particlesQuality pickWeaponPool pitch pixelGrid pixelGridBase pixelGridNoUIScale pixelH pixelW ' + + 'playableSlotsNumber playableUnits playAction playActionNow player playerRespawnTime playerSide ' + + 'playersNumber playGesture playMission playMove playMoveNow playMusic playScriptedMission ' + + 'playSound playSound3D position positionCameraToWorld posScreenToWorld posWorldToScreen ' + + 'ppEffectAdjust ppEffectCommit ppEffectCommitted ppEffectCreate ppEffectDestroy ppEffectEnable ' + + 'ppEffectEnabled ppEffectForceInNVG precision preloadCamera preloadObject preloadSound ' + + 'preloadTitleObj preloadTitleRsc preprocessFile preprocessFileLineNumbers primaryWeapon ' + + 'primaryWeaponItems primaryWeaponMagazine priority processDiaryLink productVersion profileName ' + + 'profileNamespace profileNameSteam progressLoadingScreen progressPosition progressSetPosition ' + + 'publicVariable publicVariableClient publicVariableServer pushBack pushBackUnique putWeaponPool ' + + 'queryItemsPool queryMagazinePool queryWeaponPool rad radioChannelAdd radioChannelCreate ' + + 'radioChannelRemove radioChannelSetCallSign radioChannelSetLabel radioVolume rain rainbow random ' + + 'rank rankId rating rectangular registeredTasks registerTask reload reloadEnabled remoteControl ' + + 'remoteExec remoteExecCall remoteExecutedOwner remove3DENConnection remove3DENEventHandler ' + + 'remove3DENLayer removeAction removeAll3DENEventHandlers removeAllActions removeAllAssignedItems ' + + 'removeAllContainers removeAllCuratorAddons removeAllCuratorCameraAreas ' + + 'removeAllCuratorEditingAreas removeAllEventHandlers removeAllHandgunItems removeAllItems ' + + 'removeAllItemsWithMagazines removeAllMissionEventHandlers removeAllMPEventHandlers ' + + 'removeAllMusicEventHandlers removeAllOwnedMines removeAllPrimaryWeaponItems removeAllWeapons ' + + 'removeBackpack removeBackpackGlobal removeCuratorAddons removeCuratorCameraArea ' + + 'removeCuratorEditableObjects removeCuratorEditingArea removeDrawIcon removeDrawLinks ' + + 'removeEventHandler removeFromRemainsCollector removeGoggles removeGroupIcon removeHandgunItem ' + + 'removeHeadgear removeItem removeItemFromBackpack removeItemFromUniform removeItemFromVest ' + + 'removeItems removeMagazine removeMagazineGlobal removeMagazines removeMagazinesTurret ' + + 'removeMagazineTurret removeMenuItem removeMissionEventHandler removeMPEventHandler ' + + 'removeMusicEventHandler removeOwnedMine removePrimaryWeaponItem removeSecondaryWeaponItem ' + + 'removeSimpleTask removeSwitchableUnit removeTeamMember removeUniform removeVest removeWeapon ' + + 'removeWeaponAttachmentCargo removeWeaponCargo removeWeaponGlobal removeWeaponTurret ' + + 'reportRemoteTarget requiredVersion resetCamShake resetSubgroupDirection resize resources ' + + 'respawnVehicle restartEditorCamera reveal revealMine reverse reversedMouseY roadAt ' + + 'roadsConnectedTo roleDescription ropeAttachedObjects ropeAttachedTo ropeAttachEnabled ' + + 'ropeAttachTo ropeCreate ropeCut ropeDestroy ropeDetach ropeEndPosition ropeLength ropes ' + + 'ropeUnwind ropeUnwound rotorsForcesRTD rotorsRpmRTD round runInitScript safeZoneH safeZoneW ' + + 'safeZoneWAbs safeZoneX safeZoneXAbs safeZoneY save3DENInventory saveGame saveIdentity ' + + 'saveJoysticks saveOverlay saveProfileNamespace saveStatus saveVar savingEnabled say say2D say3D ' + + 'scopeName score scoreSide screenshot screenToWorld scriptDone scriptName scudState ' + + 'secondaryWeapon secondaryWeaponItems secondaryWeaponMagazine select selectBestPlaces ' + + 'selectDiarySubject selectedEditorObjects selectEditorObject selectionNames selectionPosition ' + + 'selectLeader selectMax selectMin selectNoPlayer selectPlayer selectRandom selectRandomWeighted ' + + 'selectWeapon selectWeaponTurret sendAUMessage sendSimpleCommand sendTask sendTaskResult ' + + 'sendUDPMessage serverCommand serverCommandAvailable serverCommandExecutable serverName serverTime ' + + 'set set3DENAttribute set3DENAttributes set3DENGrid set3DENIconsVisible set3DENLayer ' + + 'set3DENLinesVisible set3DENLogicType set3DENMissionAttribute set3DENMissionAttributes ' + + 'set3DENModelsVisible set3DENObjectType set3DENSelected setAccTime setActualCollectiveRTD ' + + 'setAirplaneThrottle setAirportSide setAmmo setAmmoCargo setAmmoOnPylon setAnimSpeedCoef ' + + 'setAperture setApertureNew setArmoryPoints setAttributes setAutonomous setBehaviour ' + + 'setBleedingRemaining setBrakesRTD setCameraInterest setCamShakeDefParams setCamShakeParams ' + + 'setCamUseTI setCaptive setCenterOfMass setCollisionLight setCombatMode setCompassOscillation ' + + 'setConvoySeparation setCuratorCameraAreaCeiling setCuratorCoef setCuratorEditingAreaType ' + + 'setCuratorWaypointCost setCurrentChannel setCurrentTask setCurrentWaypoint setCustomAimCoef ' + + 'setCustomWeightRTD setDamage setDammage setDate setDebriefingText setDefaultCamera setDestination ' + + 'setDetailMapBlendPars setDir setDirection setDrawIcon setDriveOnPath setDropInterval ' + + 'setDynamicSimulationDistance setDynamicSimulationDistanceCoef setEditorMode setEditorObjectScope ' + + 'setEffectCondition setEngineRPMRTD setFace setFaceAnimation setFatigue setFeatureType ' + + 'setFlagAnimationPhase setFlagOwner setFlagSide setFlagTexture setFog setFormation ' + + 'setFormationTask setFormDir setFriend setFromEditor setFSMVariable setFuel setFuelCargo ' + + 'setGroupIcon setGroupIconParams setGroupIconsSelectable setGroupIconsVisible setGroupId ' + + 'setGroupIdGlobal setGroupOwner setGusts setHideBehind setHit setHitIndex setHitPointDamage ' + + 'setHorizonParallaxCoef setHUDMovementLevels setIdentity setImportance setInfoPanel setLeader ' + + 'setLightAmbient setLightAttenuation setLightBrightness setLightColor setLightDayLight ' + + 'setLightFlareMaxDistance setLightFlareSize setLightIntensity setLightnings setLightUseFlare ' + + 'setLocalWindParams setMagazineTurretAmmo setMarkerAlpha setMarkerAlphaLocal setMarkerBrush ' + + 'setMarkerBrushLocal setMarkerColor setMarkerColorLocal setMarkerDir setMarkerDirLocal ' + + 'setMarkerPos setMarkerPosLocal setMarkerShape setMarkerShapeLocal setMarkerSize ' + + 'setMarkerSizeLocal setMarkerText setMarkerTextLocal setMarkerType setMarkerTypeLocal setMass ' + + 'setMimic setMousePosition setMusicEffect setMusicEventHandler setName setNameSound ' + + 'setObjectArguments setObjectMaterial setObjectMaterialGlobal setObjectProxy setObjectTexture ' + + 'setObjectTextureGlobal setObjectViewDistance setOvercast setOwner setOxygenRemaining ' + + 'setParticleCircle setParticleClass setParticleFire setParticleParams setParticleRandom ' + + 'setPilotCameraDirection setPilotCameraRotation setPilotCameraTarget setPilotLight setPiPEffect ' + + 'setPitch setPlateNumber setPlayable setPlayerRespawnTime setPos setPosASL setPosASL2 setPosASLW ' + + 'setPosATL setPosition setPosWorld setPylonLoadOut setPylonsPriority setRadioMsg setRain ' + + 'setRainbow setRandomLip setRank setRectangular setRepairCargo setRotorBrakeRTD setShadowDistance ' + + 'setShotParents setSide setSimpleTaskAlwaysVisible setSimpleTaskCustomData ' + + 'setSimpleTaskDescription setSimpleTaskDestination setSimpleTaskTarget setSimpleTaskType ' + + 'setSimulWeatherLayers setSize setSkill setSlingLoad setSoundEffect setSpeaker setSpeech ' + + 'setSpeedMode setStamina setStaminaScheme setStatValue setSuppression setSystemOfUnits ' + + 'setTargetAge setTaskMarkerOffset setTaskResult setTaskState setTerrainGrid setText ' + + 'setTimeMultiplier setTitleEffect setTrafficDensity setTrafficDistance setTrafficGap ' + + 'setTrafficSpeed setTriggerActivation setTriggerArea setTriggerStatements setTriggerText ' + + 'setTriggerTimeout setTriggerType setType setUnconscious setUnitAbility setUnitLoadout setUnitPos ' + + 'setUnitPosWeak setUnitRank setUnitRecoilCoefficient setUnitTrait setUnloadInCombat ' + + 'setUserActionText setUserMFDText setUserMFDvalue setVariable setVectorDir setVectorDirAndUp ' + + 'setVectorUp setVehicleAmmo setVehicleAmmoDef setVehicleArmor setVehicleCargo setVehicleId ' + + 'setVehicleLock setVehiclePosition setVehicleRadar setVehicleReceiveRemoteTargets ' + + 'setVehicleReportOwnPosition setVehicleReportRemoteTargets setVehicleTIPars setVehicleVarName ' + + 'setVelocity setVelocityModelSpace setVelocityTransformation setViewDistance ' + + 'setVisibleIfTreeCollapsed setWantedRPMRTD setWaves setWaypointBehaviour setWaypointCombatMode ' + + 'setWaypointCompletionRadius setWaypointDescription setWaypointForceBehaviour setWaypointFormation ' + + 'setWaypointHousePosition setWaypointLoiterRadius setWaypointLoiterType setWaypointName ' + + 'setWaypointPosition setWaypointScript setWaypointSpeed setWaypointStatements setWaypointTimeout ' + + 'setWaypointType setWaypointVisible setWeaponReloadingTime setWind setWindDir setWindForce ' + + 'setWindStr setWingForceScaleRTD setWPPos show3DIcons showChat showCinemaBorder showCommandingMenu ' + + 'showCompass showCuratorCompass showGPS showHUD showLegend showMap shownArtilleryComputer ' + + 'shownChat shownCompass shownCuratorCompass showNewEditorObject shownGPS shownHUD shownMap ' + + 'shownPad shownRadio shownScoretable shownUAVFeed shownWarrant shownWatch showPad showRadio ' + + 'showScoretable showSubtitles showUAVFeed showWarrant showWatch showWaypoint showWaypoints side ' + + 'sideChat sideEnemy sideFriendly sideRadio simpleTasks simulationEnabled simulCloudDensity ' + + 'simulCloudOcclusion simulInClouds simulWeatherSync sin size sizeOf skill skillFinal skipTime ' + + 'sleep sliderPosition sliderRange sliderSetPosition sliderSetRange sliderSetSpeed sliderSpeed ' + + 'slingLoadAssistantShown soldierMagazines someAmmo sort soundVolume spawn speaker speed speedMode ' + + 'splitString sqrt squadParams stance startLoadingScreen step stop stopEngineRTD stopped str ' + + 'sunOrMoon supportInfo suppressFor surfaceIsWater surfaceNormal surfaceType swimInDepth ' + + 'switchableUnits switchAction switchCamera switchGesture switchLight switchMove ' + + 'synchronizedObjects synchronizedTriggers synchronizedWaypoints synchronizeObjectsAdd ' + + 'synchronizeObjectsRemove synchronizeTrigger synchronizeWaypoint systemChat systemOfUnits tan ' + + 'targetKnowledge targets targetsAggregate targetsQuery taskAlwaysVisible taskChildren ' + + 'taskCompleted taskCustomData taskDescription taskDestination taskHint taskMarkerOffset taskParent ' + + 'taskResult taskState taskType teamMember teamName teams teamSwitch teamSwitchEnabled teamType ' + + 'terminate terrainIntersect terrainIntersectASL terrainIntersectAtASL text textLog textLogFormat ' + + 'tg time timeMultiplier titleCut titleFadeOut titleObj titleRsc titleText toArray toFixed toLower ' + + 'toString toUpper triggerActivated triggerActivation triggerArea triggerAttachedVehicle ' + + 'triggerAttachObject triggerAttachVehicle triggerDynamicSimulation triggerStatements triggerText ' + + 'triggerTimeout triggerTimeoutCurrent triggerType turretLocal turretOwner turretUnit tvAdd tvClear ' + + 'tvCollapse tvCollapseAll tvCount tvCurSel tvData tvDelete tvExpand tvExpandAll tvPicture ' + + 'tvSetColor tvSetCurSel tvSetData tvSetPicture tvSetPictureColor tvSetPictureColorDisabled ' + + 'tvSetPictureColorSelected tvSetPictureRight tvSetPictureRightColor tvSetPictureRightColorDisabled ' + + 'tvSetPictureRightColorSelected tvSetText tvSetTooltip tvSetValue tvSort tvSortByValue tvText ' + + 'tvTooltip tvValue type typeName typeOf UAVControl uiNamespace uiSleep unassignCurator ' + + 'unassignItem unassignTeam unassignVehicle underwater uniform uniformContainer uniformItems ' + + 'uniformMagazines unitAddons unitAimPosition unitAimPositionVisual unitBackpack unitIsUAV unitPos ' + + 'unitReady unitRecoilCoefficient units unitsBelowHeight unlinkItem unlockAchievement ' + + 'unregisterTask updateDrawIcon updateMenuItem updateObjectTree useAISteeringComponent ' + + 'useAudioTimeForMoves userInputDisabled vectorAdd vectorCos vectorCrossProduct vectorDiff ' + + 'vectorDir vectorDirVisual vectorDistance vectorDistanceSqr vectorDotProduct vectorFromTo ' + + 'vectorMagnitude vectorMagnitudeSqr vectorModelToWorld vectorModelToWorldVisual vectorMultiply ' + + 'vectorNormalized vectorUp vectorUpVisual vectorWorldToModel vectorWorldToModelVisual vehicle ' + + 'vehicleCargoEnabled vehicleChat vehicleRadio vehicleReceiveRemoteTargets vehicleReportOwnPosition ' + + 'vehicleReportRemoteTargets vehicles vehicleVarName velocity velocityModelSpace verifySignature ' + + 'vest vestContainer vestItems vestMagazines viewDistance visibleCompass visibleGPS visibleMap ' + + 'visiblePosition visiblePositionASL visibleScoretable visibleWatch waves waypointAttachedObject ' + + 'waypointAttachedVehicle waypointAttachObject waypointAttachVehicle waypointBehaviour ' + + 'waypointCombatMode waypointCompletionRadius waypointDescription waypointForceBehaviour ' + + 'waypointFormation waypointHousePosition waypointLoiterRadius waypointLoiterType waypointName ' + + 'waypointPosition waypoints waypointScript waypointsEnabledUAV waypointShow waypointSpeed ' + + 'waypointStatements waypointTimeout waypointTimeoutCurrent waypointType waypointVisible ' + + 'weaponAccessories weaponAccessoriesCargo weaponCargo weaponDirection weaponInertia weaponLowered ' + + 'weapons weaponsItems weaponsItemsCargo weaponState weaponsTurret weightRTD WFSideText wind ', + literal: + 'blufor civilian configNull controlNull displayNull east endl false grpNull independent lineBreak ' + + 'locationNull nil objNull opfor pi resistance scriptNull sideAmbientLife sideEmpty sideLogic ' + + 'sideUnknown taskNull teamMemberNull true west' + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.NUMBER_MODE, + VARIABLE, + FUNCTION, + STRINGS, + PREPROCESSOR + ], + illegal: /#|^\$ / + }; +} + +module.exports = sqf; + + +/***/ }), + +/***/ 42318: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* + Language: SQL + Website: https://en.wikipedia.org/wiki/SQL + Category: common, database + */ + +function sql(hljs) { + const COMMENT_MODE = hljs.COMMENT('--', '$'); + const STRING = { + className: 'string', + variants: [ + { + begin: /'/, + end: /'/, + contains: [ + {begin: /''/ } + ] + } + ] + }; + const QUOTED_IDENTIFIER = { + begin: /"/, + end: /"/, + contains: [ { begin: /""/ } ] + }; + + const LITERALS = [ + "true", + "false", + // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way. + // "null", + "unknown" + ]; + + const MULTI_WORD_TYPES = [ + "double precision", + "large object", + "with timezone", + "without timezone" + ]; + + const TYPES = [ + 'bigint', + 'binary', + 'blob', + 'boolean', + 'char', + 'character', + 'clob', + 'date', + 'dec', + 'decfloat', + 'decimal', + 'float', + 'int', + 'integer', + 'interval', + 'nchar', + 'nclob', + 'national', + 'numeric', + 'real', + 'row', + 'smallint', + 'time', + 'timestamp', + 'varchar', + 'varying', // modifier (character varying) + 'varbinary' + ]; + + const NON_RESERVED_WORDS = [ + "add", + "asc", + "collation", + "desc", + "final", + "first", + "last", + "view" + ]; + + // https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#reserved-word + const RESERVED_WORDS = [ + "abs", + "acos", + "all", + "allocate", + "alter", + "and", + "any", + "are", + "array", + "array_agg", + "array_max_cardinality", + "as", + "asensitive", + "asin", + "asymmetric", + "at", + "atan", + "atomic", + "authorization", + "avg", + "begin", + "begin_frame", + "begin_partition", + "between", + "bigint", + "binary", + "blob", + "boolean", + "both", + "by", + "call", + "called", + "cardinality", + "cascaded", + "case", + "cast", + "ceil", + "ceiling", + "char", + "char_length", + "character", + "character_length", + "check", + "classifier", + "clob", + "close", + "coalesce", + "collate", + "collect", + "column", + "commit", + "condition", + "connect", + "constraint", + "contains", + "convert", + "copy", + "corr", + "corresponding", + "cos", + "cosh", + "count", + "covar_pop", + "covar_samp", + "create", + "cross", + "cube", + "cume_dist", + "current", + "current_catalog", + "current_date", + "current_default_transform_group", + "current_path", + "current_role", + "current_row", + "current_schema", + "current_time", + "current_timestamp", + "current_path", + "current_role", + "current_transform_group_for_type", + "current_user", + "cursor", + "cycle", + "date", + "day", + "deallocate", + "dec", + "decimal", + "decfloat", + "declare", + "default", + "define", + "delete", + "dense_rank", + "deref", + "describe", + "deterministic", + "disconnect", + "distinct", + "double", + "drop", + "dynamic", + "each", + "element", + "else", + "empty", + "end", + "end_frame", + "end_partition", + "end-exec", + "equals", + "escape", + "every", + "except", + "exec", + "execute", + "exists", + "exp", + "external", + "extract", + "false", + "fetch", + "filter", + "first_value", + "float", + "floor", + "for", + "foreign", + "frame_row", + "free", + "from", + "full", + "function", + "fusion", + "get", + "global", + "grant", + "group", + "grouping", + "groups", + "having", + "hold", + "hour", + "identity", + "in", + "indicator", + "initial", + "inner", + "inout", + "insensitive", + "insert", + "int", + "integer", + "intersect", + "intersection", + "interval", + "into", + "is", + "join", + "json_array", + "json_arrayagg", + "json_exists", + "json_object", + "json_objectagg", + "json_query", + "json_table", + "json_table_primitive", + "json_value", + "lag", + "language", + "large", + "last_value", + "lateral", + "lead", + "leading", + "left", + "like", + "like_regex", + "listagg", + "ln", + "local", + "localtime", + "localtimestamp", + "log", + "log10", + "lower", + "match", + "match_number", + "match_recognize", + "matches", + "max", + "member", + "merge", + "method", + "min", + "minute", + "mod", + "modifies", + "module", + "month", + "multiset", + "national", + "natural", + "nchar", + "nclob", + "new", + "no", + "none", + "normalize", + "not", + "nth_value", + "ntile", + "null", + "nullif", + "numeric", + "octet_length", + "occurrences_regex", + "of", + "offset", + "old", + "omit", + "on", + "one", + "only", + "open", + "or", + "order", + "out", + "outer", + "over", + "overlaps", + "overlay", + "parameter", + "partition", + "pattern", + "per", + "percent", + "percent_rank", + "percentile_cont", + "percentile_disc", + "period", + "portion", + "position", + "position_regex", + "power", + "precedes", + "precision", + "prepare", + "primary", + "procedure", + "ptf", + "range", + "rank", + "reads", + "real", + "recursive", + "ref", + "references", + "referencing", + "regr_avgx", + "regr_avgy", + "regr_count", + "regr_intercept", + "regr_r2", + "regr_slope", + "regr_sxx", + "regr_sxy", + "regr_syy", + "release", + "result", + "return", + "returns", + "revoke", + "right", + "rollback", + "rollup", + "row", + "row_number", + "rows", + "running", + "savepoint", + "scope", + "scroll", + "search", + "second", + "seek", + "select", + "sensitive", + "session_user", + "set", + "show", + "similar", + "sin", + "sinh", + "skip", + "smallint", + "some", + "specific", + "specifictype", + "sql", + "sqlexception", + "sqlstate", + "sqlwarning", + "sqrt", + "start", + "static", + "stddev_pop", + "stddev_samp", + "submultiset", + "subset", + "substring", + "substring_regex", + "succeeds", + "sum", + "symmetric", + "system", + "system_time", + "system_user", + "table", + "tablesample", + "tan", + "tanh", + "then", + "time", + "timestamp", + "timezone_hour", + "timezone_minute", + "to", + "trailing", + "translate", + "translate_regex", + "translation", + "treat", + "trigger", + "trim", + "trim_array", + "true", + "truncate", + "uescape", + "union", + "unique", + "unknown", + "unnest", + "update ", + "upper", + "user", + "using", + "value", + "values", + "value_of", + "var_pop", + "var_samp", + "varbinary", + "varchar", + "varying", + "versioning", + "when", + "whenever", + "where", + "width_bucket", + "window", + "with", + "within", + "without", + "year", + ]; + + // these are reserved words we have identified to be functions + // and should only be highlighted in a dispatch-like context + // ie, array_agg(...), etc. + const RESERVED_FUNCTIONS = [ + "abs", + "acos", + "array_agg", + "asin", + "atan", + "avg", + "cast", + "ceil", + "ceiling", + "coalesce", + "corr", + "cos", + "cosh", + "count", + "covar_pop", + "covar_samp", + "cume_dist", + "dense_rank", + "deref", + "element", + "exp", + "extract", + "first_value", + "floor", + "json_array", + "json_arrayagg", + "json_exists", + "json_object", + "json_objectagg", + "json_query", + "json_table", + "json_table_primitive", + "json_value", + "lag", + "last_value", + "lead", + "listagg", + "ln", + "log", + "log10", + "lower", + "max", + "min", + "mod", + "nth_value", + "ntile", + "nullif", + "percent_rank", + "percentile_cont", + "percentile_disc", + "position", + "position_regex", + "power", + "rank", + "regr_avgx", + "regr_avgy", + "regr_count", + "regr_intercept", + "regr_r2", + "regr_slope", + "regr_sxx", + "regr_sxy", + "regr_syy", + "row_number", + "sin", + "sinh", + "sqrt", + "stddev_pop", + "stddev_samp", + "substring", + "substring_regex", + "sum", + "tan", + "tanh", + "translate", + "translate_regex", + "treat", + "trim", + "trim_array", + "unnest", + "upper", + "value_of", + "var_pop", + "var_samp", + "width_bucket", + ]; + + // these functions can + const POSSIBLE_WITHOUT_PARENS = [ + "current_catalog", + "current_date", + "current_default_transform_group", + "current_path", + "current_role", + "current_schema", + "current_transform_group_for_type", + "current_user", + "session_user", + "system_time", + "system_user", + "current_time", + "localtime", + "current_timestamp", + "localtimestamp" + ]; + + // those exist to boost relevance making these very + // "SQL like" keyword combos worth +1 extra relevance + const COMBOS = [ + "create table", + "insert into", + "primary key", + "foreign key", + "not null", + "alter table", + "add constraint", + "grouping sets", + "on overflow", + "character set", + "respect nulls", + "ignore nulls", + "nulls first", + "nulls last", + "depth first", + "breadth first" + ]; + + const FUNCTIONS = RESERVED_FUNCTIONS; + + const KEYWORDS = [...RESERVED_WORDS, ...NON_RESERVED_WORDS].filter((keyword) => { + return !RESERVED_FUNCTIONS.includes(keyword); + }); + + const VARIABLE = { + className: "variable", + begin: /@[a-z0-9]+/, + }; + + const OPERATOR = { + className: "operator", + begin: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/, + relevance: 0, + }; + + const FUNCTION_CALL = { + begin: concat(/\b/, either(...FUNCTIONS), /\s*\(/), + keywords: { + built_in: FUNCTIONS + } + }; + + // keywords with less than 3 letters are reduced in relevancy + function reduceRelevancy(list, {exceptions, when} = {}) { + const qualifyFn = when; + exceptions = exceptions || []; + return list.map((item) => { + if (item.match(/\|\d+$/) || exceptions.includes(item)) { + return item; + } else if (qualifyFn(item)) { + return `${item}|0`; + } else { + return item; + } + }); + } + + return { + name: 'SQL', + case_insensitive: true, + // does not include {} or HTML tags ` x.length < 3 }), + literal: LITERALS, + type: TYPES, + built_in: POSSIBLE_WITHOUT_PARENS + }, + contains: [ + { + begin: either(...COMBOS), + keywords: { + $pattern: /[\w\.]+/, + keyword: KEYWORDS.concat(COMBOS), + literal: LITERALS, + type: TYPES + }, + }, + { + className: "type", + begin: either(...MULTI_WORD_TYPES) + }, + FUNCTION_CALL, + VARIABLE, + STRING, + QUOTED_IDENTIFIER, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + OPERATOR + ] + }; +} + +module.exports = sql; + + +/***/ }), + +/***/ 21420: +/***/ ((module) => { + +/* + Language: SQL More (mix of MySQL, Oracle, etc) + Contributors: Nikolay Lisienko , Heiko August , Travis Odom , Vadimtro , Benjamin Auder + Website: https://en.wikipedia.org/wiki/SQL + Category: database + */ + +/* + +This is a preservation of the old bloated SQL grammar which includes pretty much +the kitchen sink because no one was keeping track of which keywords belong to +which databases. This is likely to be removed in the future. + +- Oracle SQL should be factored into it's own 3rd party grammar. +- MySQL should be factored out into it's own 3rd party grammar. + +*/ + +function sql_more(hljs) { + var COMMENT_MODE = hljs.COMMENT('--', '$'); + return { + name: 'SQL (more)', + aliases: ["mysql", "oracle"], + disableAutodetect: true, + case_insensitive: true, + illegal: /[<>{}*]/, + contains: [ + { + beginKeywords: + 'begin end start commit rollback savepoint lock alter create drop rename call ' + + 'delete do handler insert load replace select truncate update set show pragma grant ' + + 'merge describe use explain help declare prepare execute deallocate release ' + + 'unlock purge reset change stop analyze cache flush optimize repair kill ' + + 'install uninstall checksum restore check backup revoke comment values with', + end: /;/, endsWithParent: true, + keywords: { + $pattern: /[\w\.]+/, + keyword: + 'as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add ' + + 'addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias ' + + 'all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply ' + + 'archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan ' + + 'atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid ' + + 'authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile ' + + 'before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float ' + + 'binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound ' + + 'bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel ' + + 'capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base ' + + 'char_length character_length characters characterset charindex charset charsetform charsetid check ' + + 'checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close ' + + 'cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation ' + + 'collect colu colum column column_value columns columns_updated comment commit compact compatibility ' + + 'compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn ' + + 'connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection ' + + 'consider consistent constant constraint constraints constructor container content contents context ' + + 'contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost ' + + 'count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation ' + + 'critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user ' + + 'cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add ' + + 'date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts ' + + 'day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate ' + + 'declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults ' + + 'deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank ' + + 'depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor ' + + 'deterministic diagnostics difference dimension direct_load directory disable disable_all ' + + 'disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div ' + + 'do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable ' + + 'editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt ' + + 'end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors ' + + 'escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding ' + + 'execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external ' + + 'external_1 external_2 externally extract failed failed_login_attempts failover failure far fast ' + + 'feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final ' + + 'finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign ' + + 'form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ' + + 'ftp full function general generated get get_format get_lock getdate getutcdate global global_name ' + + 'globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups ' + + 'gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex ' + + 'hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified ' + + 'identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment ' + + 'index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile ' + + 'initial initialized initially initrans inmemory inner innodb input insert install instance instantiable ' + + 'instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat ' + + 'is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists ' + + 'keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase ' + + 'lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit ' + + 'lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate ' + + 'locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call ' + + 'logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime ' + + 'managed management manual map mapping mask master master_pos_wait match matched materialized max ' + + 'maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans ' + + 'md5 measures median medium member memcompress memory merge microsecond mid migration min minextents ' + + 'minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month ' + + 'months mount move movement multiset mutex name name_const names nan national native natural nav nchar ' + + 'nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile ' + + 'nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile ' + + 'nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder ' + + 'nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck ' + + 'noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe ' + + 'nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ' + + 'ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old ' + + 'on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date ' + + 'oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary ' + + 'out outer outfile outline output over overflow overriding package pad parallel parallel_enable ' + + 'parameters parent parse partial partition partitions pascal passing password password_grace_time ' + + 'password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex ' + + 'pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc ' + + 'performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin ' + + 'policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction ' + + 'prediction_cost prediction_details prediction_probability prediction_set prepare present preserve ' + + 'prior priority private private_sga privileges procedural procedure procedure_analyze processlist ' + + 'profiles project prompt protection public publishingservername purge quarter query quick quiesce quota ' + + 'quotename radians raise rand range rank raw read reads readsize rebuild record records ' + + 'recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh ' + + 'regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy ' + + 'reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename ' + + 'repair repeat replace replicate replication required reset resetlogs resize resource respect restore ' + + 'restricted result result_cache resumable resume retention return returning returns reuse reverse revoke ' + + 'right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows ' + + 'rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll ' + + 'sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select ' + + 'self semi sequence sequential serializable server servererror session session_user sessions_per_user set ' + + 'sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor ' + + 'si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin ' + + 'size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex ' + + 'source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows ' + + 'sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone ' + + 'standby start starting startup statement static statistics stats_binomial_test stats_crosstab ' + + 'stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep ' + + 'stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev ' + + 'stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate ' + + 'subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum ' + + 'suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate ' + + 'sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo ' + + 'template temporary terminated tertiary_weights test than then thread through tier ties time time_format ' + + 'time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr ' + + 'timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking ' + + 'transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate ' + + 'try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress ' + + 'under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot ' + + 'unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert ' + + 'url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date ' + + 'utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var ' + + 'var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray ' + + 'verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear ' + + 'wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped ' + + 'xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces ' + + 'xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek', + literal: + 'true false null unknown', + built_in: + 'array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number ' + + 'numeric real record serial serial8 smallint text time timestamp tinyint varchar varchar2 varying void' + }, + contains: [ + { + className: 'string', + begin: '\'', end: '\'', + contains: [{begin: '\'\''}] + }, + { + className: 'string', + begin: '"', end: '"', + contains: [{begin: '""'}] + }, + { + className: 'string', + begin: '`', end: '`' + }, + hljs.C_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + hljs.HASH_COMMENT_MODE + ] + }, + hljs.C_BLOCK_COMMENT_MODE, + COMMENT_MODE, + hljs.HASH_COMMENT_MODE + ] + }; +} + +module.exports = sql_more; + + +/***/ }), + +/***/ 16272: +/***/ ((module) => { + +/* +Language: Stan +Description: The Stan probabilistic programming language +Author: Jeffrey B. Arnold +Website: http://mc-stan.org/ +Category: scientific +*/ + +function stan(hljs) { + // variable names cannot conflict with block identifiers + const BLOCKS = [ + 'functions', + 'model', + 'data', + 'parameters', + 'quantities', + 'transformed', + 'generated' + ]; + const STATEMENTS = [ + 'for', + 'in', + 'if', + 'else', + 'while', + 'break', + 'continue', + 'return' + ]; + const SPECIAL_FUNCTIONS = [ + 'print', + 'reject', + 'increment_log_prob|10', + 'integrate_ode|10', + 'integrate_ode_rk45|10', + 'integrate_ode_bdf|10', + 'algebra_solver' + ]; + const VAR_TYPES = [ + 'int', + 'real', + 'vector', + 'ordered', + 'positive_ordered', + 'simplex', + 'unit_vector', + 'row_vector', + 'matrix', + 'cholesky_factor_corr|10', + 'cholesky_factor_cov|10', + 'corr_matrix|10', + 'cov_matrix|10', + 'void' + ]; + const FUNCTIONS = [ + 'Phi', + 'Phi_approx', + 'abs', + 'acos', + 'acosh', + 'algebra_solver', + 'append_array', + 'append_col', + 'append_row', + 'asin', + 'asinh', + 'atan', + 'atan2', + 'atanh', + 'bernoulli_cdf', + 'bernoulli_lccdf', + 'bernoulli_lcdf', + 'bernoulli_logit_lpmf', + 'bernoulli_logit_rng', + 'bernoulli_lpmf', + 'bernoulli_rng', + 'bessel_first_kind', + 'bessel_second_kind', + 'beta_binomial_cdf', + 'beta_binomial_lccdf', + 'beta_binomial_lcdf', + 'beta_binomial_lpmf', + 'beta_binomial_rng', + 'beta_cdf', + 'beta_lccdf', + 'beta_lcdf', + 'beta_lpdf', + 'beta_rng', + 'binary_log_loss', + 'binomial_cdf', + 'binomial_coefficient_log', + 'binomial_lccdf', + 'binomial_lcdf', + 'binomial_logit_lpmf', + 'binomial_lpmf', + 'binomial_rng', + 'block', + 'categorical_logit_lpmf', + 'categorical_logit_rng', + 'categorical_lpmf', + 'categorical_rng', + 'cauchy_cdf', + 'cauchy_lccdf', + 'cauchy_lcdf', + 'cauchy_lpdf', + 'cauchy_rng', + 'cbrt', + 'ceil', + 'chi_square_cdf', + 'chi_square_lccdf', + 'chi_square_lcdf', + 'chi_square_lpdf', + 'chi_square_rng', + 'cholesky_decompose', + 'choose', + 'col', + 'cols', + 'columns_dot_product', + 'columns_dot_self', + 'cos', + 'cosh', + 'cov_exp_quad', + 'crossprod', + 'csr_extract_u', + 'csr_extract_v', + 'csr_extract_w', + 'csr_matrix_times_vector', + 'csr_to_dense_matrix', + 'cumulative_sum', + 'determinant', + 'diag_matrix', + 'diag_post_multiply', + 'diag_pre_multiply', + 'diagonal', + 'digamma', + 'dims', + 'dirichlet_lpdf', + 'dirichlet_rng', + 'distance', + 'dot_product', + 'dot_self', + 'double_exponential_cdf', + 'double_exponential_lccdf', + 'double_exponential_lcdf', + 'double_exponential_lpdf', + 'double_exponential_rng', + 'e', + 'eigenvalues_sym', + 'eigenvectors_sym', + 'erf', + 'erfc', + 'exp', + 'exp2', + 'exp_mod_normal_cdf', + 'exp_mod_normal_lccdf', + 'exp_mod_normal_lcdf', + 'exp_mod_normal_lpdf', + 'exp_mod_normal_rng', + 'expm1', + 'exponential_cdf', + 'exponential_lccdf', + 'exponential_lcdf', + 'exponential_lpdf', + 'exponential_rng', + 'fabs', + 'falling_factorial', + 'fdim', + 'floor', + 'fma', + 'fmax', + 'fmin', + 'fmod', + 'frechet_cdf', + 'frechet_lccdf', + 'frechet_lcdf', + 'frechet_lpdf', + 'frechet_rng', + 'gamma_cdf', + 'gamma_lccdf', + 'gamma_lcdf', + 'gamma_lpdf', + 'gamma_p', + 'gamma_q', + 'gamma_rng', + 'gaussian_dlm_obs_lpdf', + 'get_lp', + 'gumbel_cdf', + 'gumbel_lccdf', + 'gumbel_lcdf', + 'gumbel_lpdf', + 'gumbel_rng', + 'head', + 'hypergeometric_lpmf', + 'hypergeometric_rng', + 'hypot', + 'inc_beta', + 'int_step', + 'integrate_ode', + 'integrate_ode_bdf', + 'integrate_ode_rk45', + 'inv', + 'inv_Phi', + 'inv_chi_square_cdf', + 'inv_chi_square_lccdf', + 'inv_chi_square_lcdf', + 'inv_chi_square_lpdf', + 'inv_chi_square_rng', + 'inv_cloglog', + 'inv_gamma_cdf', + 'inv_gamma_lccdf', + 'inv_gamma_lcdf', + 'inv_gamma_lpdf', + 'inv_gamma_rng', + 'inv_logit', + 'inv_sqrt', + 'inv_square', + 'inv_wishart_lpdf', + 'inv_wishart_rng', + 'inverse', + 'inverse_spd', + 'is_inf', + 'is_nan', + 'lbeta', + 'lchoose', + 'lgamma', + 'lkj_corr_cholesky_lpdf', + 'lkj_corr_cholesky_rng', + 'lkj_corr_lpdf', + 'lkj_corr_rng', + 'lmgamma', + 'lmultiply', + 'log', + 'log10', + 'log1m', + 'log1m_exp', + 'log1m_inv_logit', + 'log1p', + 'log1p_exp', + 'log2', + 'log_determinant', + 'log_diff_exp', + 'log_falling_factorial', + 'log_inv_logit', + 'log_mix', + 'log_rising_factorial', + 'log_softmax', + 'log_sum_exp', + 'logistic_cdf', + 'logistic_lccdf', + 'logistic_lcdf', + 'logistic_lpdf', + 'logistic_rng', + 'logit', + 'lognormal_cdf', + 'lognormal_lccdf', + 'lognormal_lcdf', + 'lognormal_lpdf', + 'lognormal_rng', + 'machine_precision', + 'matrix_exp', + 'max', + 'mdivide_left_spd', + 'mdivide_left_tri_low', + 'mdivide_right_spd', + 'mdivide_right_tri_low', + 'mean', + 'min', + 'modified_bessel_first_kind', + 'modified_bessel_second_kind', + 'multi_gp_cholesky_lpdf', + 'multi_gp_lpdf', + 'multi_normal_cholesky_lpdf', + 'multi_normal_cholesky_rng', + 'multi_normal_lpdf', + 'multi_normal_prec_lpdf', + 'multi_normal_rng', + 'multi_student_t_lpdf', + 'multi_student_t_rng', + 'multinomial_lpmf', + 'multinomial_rng', + 'multiply_log', + 'multiply_lower_tri_self_transpose', + 'neg_binomial_2_cdf', + 'neg_binomial_2_lccdf', + 'neg_binomial_2_lcdf', + 'neg_binomial_2_log_lpmf', + 'neg_binomial_2_log_rng', + 'neg_binomial_2_lpmf', + 'neg_binomial_2_rng', + 'neg_binomial_cdf', + 'neg_binomial_lccdf', + 'neg_binomial_lcdf', + 'neg_binomial_lpmf', + 'neg_binomial_rng', + 'negative_infinity', + 'normal_cdf', + 'normal_lccdf', + 'normal_lcdf', + 'normal_lpdf', + 'normal_rng', + 'not_a_number', + 'num_elements', + 'ordered_logistic_lpmf', + 'ordered_logistic_rng', + 'owens_t', + 'pareto_cdf', + 'pareto_lccdf', + 'pareto_lcdf', + 'pareto_lpdf', + 'pareto_rng', + 'pareto_type_2_cdf', + 'pareto_type_2_lccdf', + 'pareto_type_2_lcdf', + 'pareto_type_2_lpdf', + 'pareto_type_2_rng', + 'pi', + 'poisson_cdf', + 'poisson_lccdf', + 'poisson_lcdf', + 'poisson_log_lpmf', + 'poisson_log_rng', + 'poisson_lpmf', + 'poisson_rng', + 'positive_infinity', + 'pow', + 'print', + 'prod', + 'qr_Q', + 'qr_R', + 'quad_form', + 'quad_form_diag', + 'quad_form_sym', + 'rank', + 'rayleigh_cdf', + 'rayleigh_lccdf', + 'rayleigh_lcdf', + 'rayleigh_lpdf', + 'rayleigh_rng', + 'reject', + 'rep_array', + 'rep_matrix', + 'rep_row_vector', + 'rep_vector', + 'rising_factorial', + 'round', + 'row', + 'rows', + 'rows_dot_product', + 'rows_dot_self', + 'scaled_inv_chi_square_cdf', + 'scaled_inv_chi_square_lccdf', + 'scaled_inv_chi_square_lcdf', + 'scaled_inv_chi_square_lpdf', + 'scaled_inv_chi_square_rng', + 'sd', + 'segment', + 'sin', + 'singular_values', + 'sinh', + 'size', + 'skew_normal_cdf', + 'skew_normal_lccdf', + 'skew_normal_lcdf', + 'skew_normal_lpdf', + 'skew_normal_rng', + 'softmax', + 'sort_asc', + 'sort_desc', + 'sort_indices_asc', + 'sort_indices_desc', + 'sqrt', + 'sqrt2', + 'square', + 'squared_distance', + 'step', + 'student_t_cdf', + 'student_t_lccdf', + 'student_t_lcdf', + 'student_t_lpdf', + 'student_t_rng', + 'sub_col', + 'sub_row', + 'sum', + 'tail', + 'tan', + 'tanh', + 'target', + 'tcrossprod', + 'tgamma', + 'to_array_1d', + 'to_array_2d', + 'to_matrix', + 'to_row_vector', + 'to_vector', + 'trace', + 'trace_gen_quad_form', + 'trace_quad_form', + 'trigamma', + 'trunc', + 'uniform_cdf', + 'uniform_lccdf', + 'uniform_lcdf', + 'uniform_lpdf', + 'uniform_rng', + 'variance', + 'von_mises_lpdf', + 'von_mises_rng', + 'weibull_cdf', + 'weibull_lccdf', + 'weibull_lcdf', + 'weibull_lpdf', + 'weibull_rng', + 'wiener_lpdf', + 'wishart_lpdf', + 'wishart_rng' + ]; + const DISTRIBUTIONS = [ + 'bernoulli', + 'bernoulli_logit', + 'beta', + 'beta_binomial', + 'binomial', + 'binomial_logit', + 'categorical', + 'categorical_logit', + 'cauchy', + 'chi_square', + 'dirichlet', + 'double_exponential', + 'exp_mod_normal', + 'exponential', + 'frechet', + 'gamma', + 'gaussian_dlm_obs', + 'gumbel', + 'hypergeometric', + 'inv_chi_square', + 'inv_gamma', + 'inv_wishart', + 'lkj_corr', + 'lkj_corr_cholesky', + 'logistic', + 'lognormal', + 'multi_gp', + 'multi_gp_cholesky', + 'multi_normal', + 'multi_normal_cholesky', + 'multi_normal_prec', + 'multi_student_t', + 'multinomial', + 'neg_binomial', + 'neg_binomial_2', + 'neg_binomial_2_log', + 'normal', + 'ordered_logistic', + 'pareto', + 'pareto_type_2', + 'poisson', + 'poisson_log', + 'rayleigh', + 'scaled_inv_chi_square', + 'skew_normal', + 'student_t', + 'uniform', + 'von_mises', + 'weibull', + 'wiener', + 'wishart' + ]; + + return { + name: 'Stan', + aliases: [ 'stanfuncs' ], + keywords: { + $pattern: hljs.IDENT_RE, + title: BLOCKS, + keyword: STATEMENTS.concat(VAR_TYPES).concat(SPECIAL_FUNCTIONS), + built_in: FUNCTIONS + }, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.COMMENT( + /#/, + /$/, + { + relevance: 0, + keywords: { + 'meta-keyword': 'include' + } + } + ), + hljs.COMMENT( + /\/\*/, + /\*\//, + { + relevance: 0, + // highlight doc strings mentioned in Stan reference + contains: [ + { + className: 'doctag', + begin: /@(return|param)/ + } + ] + } + ), + { + // hack: in range constraints, lower must follow "<" + begin: /<\s*lower\s*=/, + keywords: 'lower' + }, + { + // hack: in range constraints, upper must follow either , or < + // or + begin: /[<,]\s*upper\s*=/, + keywords: 'upper' + }, + { + className: 'keyword', + begin: /\btarget\s*\+=/, + relevance: 10 + }, + { + begin: '~\\s*(' + hljs.IDENT_RE + ')\\s*\\(', + keywords: DISTRIBUTIONS + }, + { + className: 'number', + variants: [ + { + begin: /\b\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/ + }, + { + begin: /\.\d+(?:[eE][+-]?\d+)?\b/ + } + ], + relevance: 0 + }, + { + className: 'string', + begin: '"', + end: '"', + relevance: 0 + } + ] + }; +} + +module.exports = stan; + + +/***/ }), + +/***/ 53727: +/***/ ((module) => { + +/* +Language: Stata +Author: Brian Quistorff +Contributors: Drew McDonald +Description: Stata is a general-purpose statistical software package created in 1985 by StataCorp. +Website: https://en.wikipedia.org/wiki/Stata +Category: scientific +*/ + +/* + This is a fork and modification of Drew McDonald's file (https://github.com/drewmcdonald/stata-highlighting). I have also included a list of builtin commands from https://bugs.kde.org/show_bug.cgi?id=135646. +*/ + +function stata(hljs) { + return { + name: 'Stata', + aliases: [ + 'do', + 'ado' + ], + case_insensitive: true, + keywords: 'if else in foreach for forv forva forval forvalu forvalue forvalues by bys bysort xi quietly qui capture about ac ac_7 acprplot acprplot_7 adjust ado adopath adoupdate alpha ameans an ano anov anova anova_estat anova_terms anovadef aorder ap app appe appen append arch arch_dr arch_estat arch_p archlm areg areg_p args arima arima_dr arima_estat arima_p as asmprobit asmprobit_estat asmprobit_lf asmprobit_mfx__dlg asmprobit_p ass asse asser assert avplot avplot_7 avplots avplots_7 bcskew0 bgodfrey bias binreg bip0_lf biplot bipp_lf bipr_lf bipr_p biprobit bitest bitesti bitowt blogit bmemsize boot bootsamp bootstrap bootstrap_8 boxco_l boxco_p boxcox boxcox_6 boxcox_p bprobit br break brier bro brow brows browse brr brrstat bs bs_7 bsampl_w bsample bsample_7 bsqreg bstat bstat_7 bstat_8 bstrap bstrap_7 bubble bubbleplot ca ca_estat ca_p cabiplot camat canon canon_8 canon_8_p canon_estat canon_p cap caprojection capt captu captur capture cat cc cchart cchart_7 cci cd censobs_table centile cf char chdir checkdlgfiles checkestimationsample checkhlpfiles checksum chelp ci cii cl class classutil clear cli clis clist clo clog clog_lf clog_p clogi clogi_sw clogit clogit_lf clogit_p clogitp clogl_sw cloglog clonevar clslistarray cluster cluster_measures cluster_stop cluster_tree cluster_tree_8 clustermat cmdlog cnr cnre cnreg cnreg_p cnreg_sw cnsreg codebook collaps4 collapse colormult_nb colormult_nw compare compress conf confi confir confirm conren cons const constr constra constrai constrain constraint continue contract copy copyright copysource cor corc corr corr2data corr_anti corr_kmo corr_smc corre correl correla correlat correlate corrgram cou coun count cox cox_p cox_sw coxbase coxhaz coxvar cprplot cprplot_7 crc cret cretu cretur creturn cross cs cscript cscript_log csi ct ct_is ctset ctst_5 ctst_st cttost cumsp cumsp_7 cumul cusum cusum_7 cutil d|0 datasig datasign datasigna datasignat datasignatu datasignatur datasignature datetof db dbeta de dec deco decod decode deff des desc descr descri describ describe destring dfbeta dfgls dfuller di di_g dir dirstats dis discard disp disp_res disp_s displ displa display distinct do doe doed doedi doedit dotplot dotplot_7 dprobit drawnorm drop ds ds_util dstdize duplicates durbina dwstat dydx e|0 ed edi edit egen eivreg emdef en enc enco encod encode eq erase ereg ereg_lf ereg_p ereg_sw ereghet ereghet_glf ereghet_glf_sh ereghet_gp ereghet_ilf ereghet_ilf_sh ereghet_ip eret eretu eretur ereturn err erro error esize est est_cfexist est_cfname est_clickable est_expand est_hold est_table est_unhold est_unholdok estat estat_default estat_summ estat_vce_only esti estimates etodow etof etomdy ex exi exit expand expandcl fac fact facto factor factor_estat factor_p factor_pca_rotated factor_rotate factormat fcast fcast_compute fcast_graph fdades fdadesc fdadescr fdadescri fdadescrib fdadescribe fdasav fdasave fdause fh_st file open file read file close file filefilter fillin find_hlp_file findfile findit findit_7 fit fl fli flis flist for5_0 forest forestplot form forma format fpredict frac_154 frac_adj frac_chk frac_cox frac_ddp frac_dis frac_dv frac_in frac_mun frac_pp frac_pq frac_pv frac_wgt frac_xo fracgen fracplot fracplot_7 fracpoly fracpred fron_ex fron_hn fron_p fron_tn fron_tn2 frontier ftodate ftoe ftomdy ftowdate funnel funnelplot g|0 gamhet_glf gamhet_gp gamhet_ilf gamhet_ip gamma gamma_d2 gamma_p gamma_sw gammahet gdi_hexagon gdi_spokes ge gen gene gener genera generat generate genrank genstd genvmean gettoken gl gladder gladder_7 glim_l01 glim_l02 glim_l03 glim_l04 glim_l05 glim_l06 glim_l07 glim_l08 glim_l09 glim_l10 glim_l11 glim_l12 glim_lf glim_mu glim_nw1 glim_nw2 glim_nw3 glim_p glim_v1 glim_v2 glim_v3 glim_v4 glim_v5 glim_v6 glim_v7 glm glm_6 glm_p glm_sw glmpred glo glob globa global glogit glogit_8 glogit_p gmeans gnbre_lf gnbreg gnbreg_5 gnbreg_p gomp_lf gompe_sw gomper_p gompertz gompertzhet gomphet_glf gomphet_glf_sh gomphet_gp gomphet_ilf gomphet_ilf_sh gomphet_ip gphdot gphpen gphprint gprefs gprobi_p gprobit gprobit_8 gr gr7 gr_copy gr_current gr_db gr_describe gr_dir gr_draw gr_draw_replay gr_drop gr_edit gr_editviewopts gr_example gr_example2 gr_export gr_print gr_qscheme gr_query gr_read gr_rename gr_replay gr_save gr_set gr_setscheme gr_table gr_undo gr_use graph graph7 grebar greigen greigen_7 greigen_8 grmeanby grmeanby_7 gs_fileinfo gs_filetype gs_graphinfo gs_stat gsort gwood h|0 hadimvo hareg hausman haver he heck_d2 heckma_p heckman heckp_lf heckpr_p heckprob hel help hereg hetpr_lf hetpr_p hetprob hettest hexdump hilite hist hist_7 histogram hlogit hlu hmeans hotel hotelling hprobit hreg hsearch icd9 icd9_ff icd9p iis impute imtest inbase include inf infi infil infile infix inp inpu input ins insheet insp inspe inspec inspect integ inten intreg intreg_7 intreg_p intrg2_ll intrg_ll intrg_ll2 ipolate iqreg ir irf irf_create irfm iri is_svy is_svysum isid istdize ivprob_1_lf ivprob_lf ivprobit ivprobit_p ivreg ivreg_footnote ivtob_1_lf ivtob_lf ivtobit ivtobit_p jackknife jacknife jknife jknife_6 jknife_8 jkstat joinby kalarma1 kap kap_3 kapmeier kappa kapwgt kdensity kdensity_7 keep ksm ksmirnov ktau kwallis l|0 la lab labbe labbeplot labe label labelbook ladder levels levelsof leverage lfit lfit_p li lincom line linktest lis list lloghet_glf lloghet_glf_sh lloghet_gp lloghet_ilf lloghet_ilf_sh lloghet_ip llogi_sw llogis_p llogist llogistic llogistichet lnorm_lf lnorm_sw lnorma_p lnormal lnormalhet lnormhet_glf lnormhet_glf_sh lnormhet_gp lnormhet_ilf lnormhet_ilf_sh lnormhet_ip lnskew0 loadingplot loc loca local log logi logis_lf logistic logistic_p logit logit_estat logit_p loglogs logrank loneway lookfor lookup lowess lowess_7 lpredict lrecomp lroc lroc_7 lrtest ls lsens lsens_7 lsens_x lstat ltable ltable_7 ltriang lv lvr2plot lvr2plot_7 m|0 ma mac macr macro makecns man manova manova_estat manova_p manovatest mantel mark markin markout marksample mat mat_capp mat_order mat_put_rr mat_rapp mata mata_clear mata_describe mata_drop mata_matdescribe mata_matsave mata_matuse mata_memory mata_mlib mata_mosave mata_rename mata_which matalabel matcproc matlist matname matr matri matrix matrix_input__dlg matstrik mcc mcci md0_ md1_ md1debug_ md2_ md2debug_ mds mds_estat mds_p mdsconfig mdslong mdsmat mdsshepard mdytoe mdytof me_derd mean means median memory memsize menl meqparse mer merg merge meta mfp mfx mhelp mhodds minbound mixed_ll mixed_ll_reparm mkassert mkdir mkmat mkspline ml ml_5 ml_adjs ml_bhhhs ml_c_d ml_check ml_clear ml_cnt ml_debug ml_defd ml_e0 ml_e0_bfgs ml_e0_cycle ml_e0_dfp ml_e0i ml_e1 ml_e1_bfgs ml_e1_bhhh ml_e1_cycle ml_e1_dfp ml_e2 ml_e2_cycle ml_ebfg0 ml_ebfr0 ml_ebfr1 ml_ebh0q ml_ebhh0 ml_ebhr0 ml_ebr0i ml_ecr0i ml_edfp0 ml_edfr0 ml_edfr1 ml_edr0i ml_eds ml_eer0i ml_egr0i ml_elf ml_elf_bfgs ml_elf_bhhh ml_elf_cycle ml_elf_dfp ml_elfi ml_elfs ml_enr0i ml_enrr0 ml_erdu0 ml_erdu0_bfgs ml_erdu0_bhhh ml_erdu0_bhhhq ml_erdu0_cycle ml_erdu0_dfp ml_erdu0_nrbfgs ml_exde ml_footnote ml_geqnr ml_grad0 ml_graph ml_hbhhh ml_hd0 ml_hold ml_init ml_inv ml_log ml_max ml_mlout ml_mlout_8 ml_model ml_nb0 ml_opt ml_p ml_plot ml_query ml_rdgrd ml_repor ml_s_e ml_score ml_searc ml_technique ml_unhold mleval mlf_ mlmatbysum mlmatsum mlog mlogi mlogit mlogit_footnote mlogit_p mlopts mlsum mlvecsum mnl0_ mor more mov move mprobit mprobit_lf mprobit_p mrdu0_ mrdu1_ mvdecode mvencode mvreg mvreg_estat n|0 nbreg nbreg_al nbreg_lf nbreg_p nbreg_sw nestreg net newey newey_7 newey_p news nl nl_7 nl_9 nl_9_p nl_p nl_p_7 nlcom nlcom_p nlexp2 nlexp2_7 nlexp2a nlexp2a_7 nlexp3 nlexp3_7 nlgom3 nlgom3_7 nlgom4 nlgom4_7 nlinit nllog3 nllog3_7 nllog4 nllog4_7 nlog_rd nlogit nlogit_p nlogitgen nlogittree nlpred no nobreak noi nois noisi noisil noisily note notes notes_dlg nptrend numlabel numlist odbc old_ver olo olog ologi ologi_sw ologit ologit_p ologitp on one onew onewa oneway op_colnm op_comp op_diff op_inv op_str opr opro oprob oprob_sw oprobi oprobi_p oprobit oprobitp opts_exclusive order orthog orthpoly ou out outf outfi outfil outfile outs outsh outshe outshee outsheet ovtest pac pac_7 palette parse parse_dissim pause pca pca_8 pca_display pca_estat pca_p pca_rotate pcamat pchart pchart_7 pchi pchi_7 pcorr pctile pentium pergram pergram_7 permute permute_8 personal peto_st pkcollapse pkcross pkequiv pkexamine pkexamine_7 pkshape pksumm pksumm_7 pl plo plot plugin pnorm pnorm_7 poisgof poiss_lf poiss_sw poisso_p poisson poisson_estat post postclose postfile postutil pperron pr prais prais_e prais_e2 prais_p predict predictnl preserve print pro prob probi probit probit_estat probit_p proc_time procoverlay procrustes procrustes_estat procrustes_p profiler prog progr progra program prop proportion prtest prtesti pwcorr pwd q\\s qby qbys qchi qchi_7 qladder qladder_7 qnorm qnorm_7 qqplot qqplot_7 qreg qreg_c qreg_p qreg_sw qu quadchk quantile quantile_7 que quer query range ranksum ratio rchart rchart_7 rcof recast reclink recode reg reg3 reg3_p regdw regr regre regre_p2 regres regres_p regress regress_estat regriv_p remap ren rena renam rename renpfix repeat replace report reshape restore ret retu retur return rm rmdir robvar roccomp roccomp_7 roccomp_8 rocf_lf rocfit rocfit_8 rocgold rocplot rocplot_7 roctab roctab_7 rolling rologit rologit_p rot rota rotat rotate rotatemat rreg rreg_p ru run runtest rvfplot rvfplot_7 rvpplot rvpplot_7 sa safesum sample sampsi sav save savedresults saveold sc sca scal scala scalar scatter scm_mine sco scob_lf scob_p scobi_sw scobit scor score scoreplot scoreplot_help scree screeplot screeplot_help sdtest sdtesti se search separate seperate serrbar serrbar_7 serset set set_defaults sfrancia sh she shel shell shewhart shewhart_7 signestimationsample signrank signtest simul simul_7 simulate simulate_8 sktest sleep slogit slogit_d2 slogit_p smooth snapspan so sor sort spearman spikeplot spikeplot_7 spikeplt spline_x split sqreg sqreg_p sret sretu sretur sreturn ssc st st_ct st_hc st_hcd st_hcd_sh st_is st_issys st_note st_promo st_set st_show st_smpl st_subid stack statsby statsby_8 stbase stci stci_7 stcox stcox_estat stcox_fr stcox_fr_ll stcox_p stcox_sw stcoxkm stcoxkm_7 stcstat stcurv stcurve stcurve_7 stdes stem stepwise stereg stfill stgen stir stjoin stmc stmh stphplot stphplot_7 stphtest stphtest_7 stptime strate strate_7 streg streg_sw streset sts sts_7 stset stsplit stsum sttocc sttoct stvary stweib su suest suest_8 sum summ summa summar summari summariz summarize sunflower sureg survcurv survsum svar svar_p svmat svy svy_disp svy_dreg svy_est svy_est_7 svy_estat svy_get svy_gnbreg_p svy_head svy_header svy_heckman_p svy_heckprob_p svy_intreg_p svy_ivreg_p svy_logistic_p svy_logit_p svy_mlogit_p svy_nbreg_p svy_ologit_p svy_oprobit_p svy_poisson_p svy_probit_p svy_regress_p svy_sub svy_sub_7 svy_x svy_x_7 svy_x_p svydes svydes_8 svygen svygnbreg svyheckman svyheckprob svyintreg svyintreg_7 svyintrg svyivreg svylc svylog_p svylogit svymarkout svymarkout_8 svymean svymlog svymlogit svynbreg svyolog svyologit svyoprob svyoprobit svyopts svypois svypois_7 svypoisson svyprobit svyprobt svyprop svyprop_7 svyratio svyreg svyreg_p svyregress svyset svyset_7 svyset_8 svytab svytab_7 svytest svytotal sw sw_8 swcnreg swcox swereg swilk swlogis swlogit swologit swoprbt swpois swprobit swqreg swtobit swweib symmetry symmi symplot symplot_7 syntax sysdescribe sysdir sysuse szroeter ta tab tab1 tab2 tab_or tabd tabdi tabdis tabdisp tabi table tabodds tabodds_7 tabstat tabu tabul tabula tabulat tabulate te tempfile tempname tempvar tes test testnl testparm teststd tetrachoric time_it timer tis tob tobi tobit tobit_p tobit_sw token tokeni tokeniz tokenize tostring total translate translator transmap treat_ll treatr_p treatreg trim trimfill trnb_cons trnb_mean trpoiss_d2 trunc_ll truncr_p truncreg tsappend tset tsfill tsline tsline_ex tsreport tsrevar tsrline tsset tssmooth tsunab ttest ttesti tut_chk tut_wait tutorial tw tware_st two twoway twoway__fpfit_serset twoway__function_gen twoway__histogram_gen twoway__ipoint_serset twoway__ipoints_serset twoway__kdensity_gen twoway__lfit_serset twoway__normgen_gen twoway__pci_serset twoway__qfit_serset twoway__scatteri_serset twoway__sunflower_gen twoway_ksm_serset ty typ type typeof u|0 unab unabbrev unabcmd update us use uselabel var var_mkcompanion var_p varbasic varfcast vargranger varirf varirf_add varirf_cgraph varirf_create varirf_ctable varirf_describe varirf_dir varirf_drop varirf_erase varirf_graph varirf_ograph varirf_rename varirf_set varirf_table varlist varlmar varnorm varsoc varstable varstable_w varstable_w2 varwle vce vec vec_fevd vec_mkphi vec_p vec_p_w vecirf_create veclmar veclmar_w vecnorm vecnorm_w vecrank vecstable verinst vers versi versio version view viewsource vif vwls wdatetof webdescribe webseek webuse weib1_lf weib2_lf weib_lf weib_lf0 weibhet_glf weibhet_glf_sh weibhet_glfa weibhet_glfa_sh weibhet_gp weibhet_ilf weibhet_ilf_sh weibhet_ilfa weibhet_ilfa_sh weibhet_ip weibu_sw weibul_p weibull weibull_c weibull_s weibullhet wh whelp whi which whil while wilc_st wilcoxon win wind windo window winexec wntestb wntestb_7 wntestq xchart xchart_7 xcorr xcorr_7 xi xi_6 xmlsav xmlsave xmluse xpose xsh xshe xshel xshell xt_iis xt_tis xtab_p xtabond xtbin_p xtclog xtcloglog xtcloglog_8 xtcloglog_d2 xtcloglog_pa_p xtcloglog_re_p xtcnt_p xtcorr xtdata xtdes xtfront_p xtfrontier xtgee xtgee_elink xtgee_estat xtgee_makeivar xtgee_p xtgee_plink xtgls xtgls_p xthaus xthausman xtht_p xthtaylor xtile xtint_p xtintreg xtintreg_8 xtintreg_d2 xtintreg_p xtivp_1 xtivp_2 xtivreg xtline xtline_ex xtlogit xtlogit_8 xtlogit_d2 xtlogit_fe_p xtlogit_pa_p xtlogit_re_p xtmixed xtmixed_estat xtmixed_p xtnb_fe xtnb_lf xtnbreg xtnbreg_pa_p xtnbreg_refe_p xtpcse xtpcse_p xtpois xtpoisson xtpoisson_d2 xtpoisson_pa_p xtpoisson_refe_p xtpred xtprobit xtprobit_8 xtprobit_d2 xtprobit_re_p xtps_fe xtps_lf xtps_ren xtps_ren_8 xtrar_p xtrc xtrc_p xtrchh xtrefe_p xtreg xtreg_be xtreg_fe xtreg_ml xtreg_pa_p xtreg_re xtregar xtrere_p xtset xtsf_ll xtsf_llti xtsum xttab xttest0 xttobit xttobit_8 xttobit_p xttrans yx yxview__barlike_draw yxview_area_draw yxview_bar_draw yxview_dot_draw yxview_dropline_draw yxview_function_draw yxview_iarrow_draw yxview_ilabels_draw yxview_normal_draw yxview_pcarrow_draw yxview_pcbarrow_draw yxview_pccapsym_draw yxview_pcscatter_draw yxview_pcspike_draw yxview_rarea_draw yxview_rbar_draw yxview_rbarm_draw yxview_rcap_draw yxview_rcapsym_draw yxview_rconnected_draw yxview_rline_draw yxview_rscatter_draw yxview_rspike_draw yxview_spike_draw yxview_sunflower_draw zap_s zinb zinb_llf zinb_plf zip zip_llf zip_p zip_plf zt_ct_5 zt_hc_5 zt_hcd_5 zt_is_5 zt_iss_5 zt_sho_5 zt_smp_5 ztbase_5 ztcox_5 ztdes_5 ztereg_5 ztfill_5 ztgen_5 ztir_5 ztjoin_5 ztnb ztnb_p ztp ztp_p zts_5 ztset_5 ztspli_5 ztsum_5 zttoct_5 ztvary_5 ztweib_5', + contains: [ + { + className: 'symbol', + begin: /`[a-zA-Z0-9_]+'/ + }, + { + className: 'variable', + begin: /\$\{?[a-zA-Z0-9_]+\}?/ + }, + { + className: 'string', + variants: [ + { + begin: '`"[^\r\n]*?"\'' + }, + { + begin: '"[^\r\n"]*"' + } + ] + }, + + { + className: 'built_in', + variants: [ + { + begin: '\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()' + } + ] + }, + + hljs.COMMENT('^[ \t]*\\*.*$', false), + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE + ] + }; +} + +module.exports = stata; + + +/***/ }), + +/***/ 99191: +/***/ ((module) => { + +/* +Language: STEP Part 21 +Contributors: Adam Joseph Cook +Description: Syntax highlighter for STEP Part 21 files (ISO 10303-21). +Website: https://en.wikipedia.org/wiki/ISO_10303-21 +*/ + +function step21(hljs) { + const STEP21_IDENT_RE = '[A-Z_][A-Z0-9_.]*'; + const STEP21_KEYWORDS = { + $pattern: STEP21_IDENT_RE, + keyword: 'HEADER ENDSEC DATA' + }; + const STEP21_START = { + className: 'meta', + begin: 'ISO-10303-21;', + relevance: 10 + }; + const STEP21_CLOSE = { + className: 'meta', + begin: 'END-ISO-10303-21;', + relevance: 10 + }; + + return { + name: 'STEP Part 21', + aliases: [ + 'p21', + 'step', + 'stp' + ], + case_insensitive: true, // STEP 21 is case insensitive in theory, in practice all non-comments are capitalized. + keywords: STEP21_KEYWORDS, + contains: [ + STEP21_START, + STEP21_CLOSE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + hljs.COMMENT('/\\*\\*!', '\\*/'), + hljs.C_NUMBER_MODE, + hljs.inherit(hljs.APOS_STRING_MODE, { + illegal: null + }), + hljs.inherit(hljs.QUOTE_STRING_MODE, { + illegal: null + }), + { + className: 'string', + begin: "'", + end: "'" + }, + { + className: 'symbol', + variants: [ + { + begin: '#', + end: '\\d+', + illegal: '\\W' + } + ] + } + ] + }; +} + +module.exports = step21; + + +/***/ }), + +/***/ 49614: +/***/ ((module) => { + +const MODES = (hljs) => { + return { + IMPORTANT: { + className: 'meta', + begin: '!important' + }, + HEXCOLOR: { + className: 'number', + begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})' + }, + ATTRIBUTE_SELECTOR_MODE: { + className: 'selector-attr', + begin: /\[/, + end: /\]/, + illegal: '$', + contains: [ + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE + ] + } + }; +}; + +const TAGS = [ + 'a', + 'abbr', + 'address', + 'article', + 'aside', + 'audio', + 'b', + 'blockquote', + 'body', + 'button', + 'canvas', + 'caption', + 'cite', + 'code', + 'dd', + 'del', + 'details', + 'dfn', + 'div', + 'dl', + 'dt', + 'em', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'html', + 'i', + 'iframe', + 'img', + 'input', + 'ins', + 'kbd', + 'label', + 'legend', + 'li', + 'main', + 'mark', + 'menu', + 'nav', + 'object', + 'ol', + 'p', + 'q', + 'quote', + 'samp', + 'section', + 'span', + 'strong', + 'summary', + 'sup', + 'table', + 'tbody', + 'td', + 'textarea', + 'tfoot', + 'th', + 'thead', + 'time', + 'tr', + 'ul', + 'var', + 'video' +]; + +const MEDIA_FEATURES = [ + 'any-hover', + 'any-pointer', + 'aspect-ratio', + 'color', + 'color-gamut', + 'color-index', + 'device-aspect-ratio', + 'device-height', + 'device-width', + 'display-mode', + 'forced-colors', + 'grid', + 'height', + 'hover', + 'inverted-colors', + 'monochrome', + 'orientation', + 'overflow-block', + 'overflow-inline', + 'pointer', + 'prefers-color-scheme', + 'prefers-contrast', + 'prefers-reduced-motion', + 'prefers-reduced-transparency', + 'resolution', + 'scan', + 'scripting', + 'update', + 'width', + // TODO: find a better solution? + 'min-width', + 'max-width', + 'min-height', + 'max-height' +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes +const PSEUDO_CLASSES = [ + 'active', + 'any-link', + 'blank', + 'checked', + 'current', + 'default', + 'defined', + 'dir', // dir() + 'disabled', + 'drop', + 'empty', + 'enabled', + 'first', + 'first-child', + 'first-of-type', + 'fullscreen', + 'future', + 'focus', + 'focus-visible', + 'focus-within', + 'has', // has() + 'host', // host or host() + 'host-context', // host-context() + 'hover', + 'indeterminate', + 'in-range', + 'invalid', + 'is', // is() + 'lang', // lang() + 'last-child', + 'last-of-type', + 'left', + 'link', + 'local-link', + 'not', // not() + 'nth-child', // nth-child() + 'nth-col', // nth-col() + 'nth-last-child', // nth-last-child() + 'nth-last-col', // nth-last-col() + 'nth-last-of-type', //nth-last-of-type() + 'nth-of-type', //nth-of-type() + 'only-child', + 'only-of-type', + 'optional', + 'out-of-range', + 'past', + 'placeholder-shown', + 'read-only', + 'read-write', + 'required', + 'right', + 'root', + 'scope', + 'target', + 'target-within', + 'user-invalid', + 'valid', + 'visited', + 'where' // where() +]; + +// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements +const PSEUDO_ELEMENTS = [ + 'after', + 'backdrop', + 'before', + 'cue', + 'cue-region', + 'first-letter', + 'first-line', + 'grammar-error', + 'marker', + 'part', + 'placeholder', + 'selection', + 'slotted', + 'spelling-error' +]; + +const ATTRIBUTES = [ + 'align-content', + 'align-items', + 'align-self', + 'animation', + 'animation-delay', + 'animation-direction', + 'animation-duration', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-name', + 'animation-play-state', + 'animation-timing-function', + 'auto', + 'backface-visibility', + 'background', + 'background-attachment', + 'background-clip', + 'background-color', + 'background-image', + 'background-origin', + 'background-position', + 'background-repeat', + 'background-size', + 'border', + 'border-bottom', + 'border-bottom-color', + 'border-bottom-left-radius', + 'border-bottom-right-radius', + 'border-bottom-style', + 'border-bottom-width', + 'border-collapse', + 'border-color', + 'border-image', + 'border-image-outset', + 'border-image-repeat', + 'border-image-slice', + 'border-image-source', + 'border-image-width', + 'border-left', + 'border-left-color', + 'border-left-style', + 'border-left-width', + 'border-radius', + 'border-right', + 'border-right-color', + 'border-right-style', + 'border-right-width', + 'border-spacing', + 'border-style', + 'border-top', + 'border-top-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-top-style', + 'border-top-width', + 'border-width', + 'bottom', + 'box-decoration-break', + 'box-shadow', + 'box-sizing', + 'break-after', + 'break-before', + 'break-inside', + 'caption-side', + 'clear', + 'clip', + 'clip-path', + 'color', + 'column-count', + 'column-fill', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-style', + 'column-rule-width', + 'column-span', + 'column-width', + 'columns', + 'content', + 'counter-increment', + 'counter-reset', + 'cursor', + 'direction', + 'display', + 'empty-cells', + 'filter', + 'flex', + 'flex-basis', + 'flex-direction', + 'flex-flow', + 'flex-grow', + 'flex-shrink', + 'flex-wrap', + 'float', + 'font', + 'font-display', + 'font-family', + 'font-feature-settings', + 'font-kerning', + 'font-language-override', + 'font-size', + 'font-size-adjust', + 'font-smoothing', + 'font-stretch', + 'font-style', + 'font-variant', + 'font-variant-ligatures', + 'font-variation-settings', + 'font-weight', + 'height', + 'hyphens', + 'icon', + 'image-orientation', + 'image-rendering', + 'image-resolution', + 'ime-mode', + 'inherit', + 'initial', + 'justify-content', + 'left', + 'letter-spacing', + 'line-height', + 'list-style', + 'list-style-image', + 'list-style-position', + 'list-style-type', + 'margin', + 'margin-bottom', + 'margin-left', + 'margin-right', + 'margin-top', + 'marks', + 'mask', + 'max-height', + 'max-width', + 'min-height', + 'min-width', + 'nav-down', + 'nav-index', + 'nav-left', + 'nav-right', + 'nav-up', + 'none', + 'normal', + 'object-fit', + 'object-position', + 'opacity', + 'order', + 'orphans', + 'outline', + 'outline-color', + 'outline-offset', + 'outline-style', + 'outline-width', + 'overflow', + 'overflow-wrap', + 'overflow-x', + 'overflow-y', + 'padding', + 'padding-bottom', + 'padding-left', + 'padding-right', + 'padding-top', + 'page-break-after', + 'page-break-before', + 'page-break-inside', + 'perspective', + 'perspective-origin', + 'pointer-events', + 'position', + 'quotes', + 'resize', + 'right', + 'src', // @font-face + 'tab-size', + 'table-layout', + 'text-align', + 'text-align-last', + 'text-decoration', + 'text-decoration-color', + 'text-decoration-line', + 'text-decoration-style', + 'text-indent', + 'text-overflow', + 'text-rendering', + 'text-shadow', + 'text-transform', + 'text-underline-position', + 'top', + 'transform', + 'transform-origin', + 'transform-style', + 'transition', + 'transition-delay', + 'transition-duration', + 'transition-property', + 'transition-timing-function', + 'unicode-bidi', + 'vertical-align', + 'visibility', + 'white-space', + 'widows', + 'width', + 'word-break', + 'word-spacing', + 'word-wrap', + 'z-index' + // reverse makes sure longer attributes `font-weight` are matched fully + // instead of getting false positives on say `font` +].reverse(); + +/* +Language: Stylus +Author: Bryant Williams +Description: Stylus is an expressive, robust, feature-rich CSS language built for nodejs. +Website: https://github.com/stylus/stylus +Category: css +*/ + +/** @type LanguageFn */ +function stylus(hljs) { + const modes = MODES(hljs); + + const AT_MODIFIERS = "and or not only"; + const VARIABLE = { + className: 'variable', + begin: '\\$' + hljs.IDENT_RE + }; + + const AT_KEYWORDS = [ + 'charset', + 'css', + 'debug', + 'extend', + 'font-face', + 'for', + 'import', + 'include', + 'keyframes', + 'media', + 'mixin', + 'page', + 'warn', + 'while' + ]; + + const LOOKAHEAD_TAG_END = '(?=[.\\s\\n[:,(])'; + + // illegals + const ILLEGAL = [ + '\\?', + '(\\bReturn\\b)', // monkey + '(\\bEnd\\b)', // monkey + '(\\bend\\b)', // vbscript + '(\\bdef\\b)', // gradle + ';', // a whole lot of languages + '#\\s', // markdown + '\\*\\s', // markdown + '===\\s', // markdown + '\\|', + '%' // prolog + ]; + + return { + name: 'Stylus', + aliases: [ 'styl' ], + case_insensitive: false, + keywords: 'if else for in', + illegal: '(' + ILLEGAL.join('|') + ')', + contains: [ + + // strings + hljs.QUOTE_STRING_MODE, + hljs.APOS_STRING_MODE, + + // comments + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + + // hex colors + modes.HEXCOLOR, + + // class tag + { + begin: '\\.[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END, + className: 'selector-class' + }, + + // id tag + { + begin: '#[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END, + className: 'selector-id' + }, + + // tags + { + begin: '\\b(' + TAGS.join('|') + ')' + LOOKAHEAD_TAG_END, + className: 'selector-tag' + }, + + // psuedo selectors + { + className: 'selector-pseudo', + begin: '&?:(' + PSEUDO_CLASSES.join('|') + ')' + LOOKAHEAD_TAG_END + }, + { + className: 'selector-pseudo', + begin: '&?::(' + PSEUDO_ELEMENTS.join('|') + ')' + LOOKAHEAD_TAG_END + }, + + modes.ATTRIBUTE_SELECTOR_MODE, + + { + className: "keyword", + begin: /@media/, + starts: { + end: /[{;}]/, + keywords: { + $pattern: /[a-z-]+/, + keyword: AT_MODIFIERS, + attribute: MEDIA_FEATURES.join(" ") + }, + contains: [ hljs.CSS_NUMBER_MODE ] + } + }, + + // @ keywords + { + className: 'keyword', + begin: '\@((-(o|moz|ms|webkit)-)?(' + AT_KEYWORDS.join('|') + '))\\b' + }, + + // variables + VARIABLE, + + // dimension + hljs.CSS_NUMBER_MODE, + + // functions + // - only from beginning of line + whitespace + { + className: 'function', + begin: '^[a-zA-Z][a-zA-Z0-9_\-]*\\(.*\\)', + illegal: '[\\n]', + returnBegin: true, + contains: [ + { + className: 'title', + begin: '\\b[a-zA-Z][a-zA-Z0-9_\-]*' + }, + { + className: 'params', + begin: /\(/, + end: /\)/, + contains: [ + modes.HEXCOLOR, + VARIABLE, + hljs.APOS_STRING_MODE, + hljs.CSS_NUMBER_MODE, + hljs.QUOTE_STRING_MODE + ] + } + ] + }, + + // attributes + // - only from beginning of line + whitespace + // - must have whitespace after it + { + className: 'attribute', + begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b', + starts: { + // value container + end: /;|$/, + contains: [ + modes.HEXCOLOR, + VARIABLE, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.CSS_NUMBER_MODE, + hljs.C_BLOCK_COMMENT_MODE, + modes.IMPORTANT + ], + illegal: /\./, + relevance: 0 + } + } + ] + }; +} + +module.exports = stylus; + + +/***/ }), + +/***/ 32798: +/***/ ((module) => { + +/* +Language: SubUnit +Author: Sergey Bronnikov +Website: https://pypi.org/project/python-subunit/ +*/ + +function subunit(hljs) { + const DETAILS = { + className: 'string', + begin: '\\[\n(multipart)?', + end: '\\]\n' + }; + const TIME = { + className: 'string', + begin: '\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}\.\\d+Z' + }; + const PROGRESSVALUE = { + className: 'string', + begin: '(\\+|-)\\d+' + }; + const KEYWORDS = { + className: 'keyword', + relevance: 10, + variants: [ + { + begin: '^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?' + }, + { + begin: '^progress(:?)(\\s+)?(pop|push)?' + }, + { + begin: '^tags:' + }, + { + begin: '^time:' + } + ] + }; + return { + name: 'SubUnit', + case_insensitive: true, + contains: [ + DETAILS, + TIME, + PROGRESSVALUE, + KEYWORDS + ] + }; +} + +module.exports = subunit; + + +/***/ }), + +/***/ 73269: +/***/ ((module) => { + +/* +Language: Tagger Script +Author: Philipp Wolfer +Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard. +Website: https://picard.musicbrainz.org + */ +function taggerscript(hljs) { + const COMMENT = { + className: 'comment', + begin: /\$noop\(/, + end: /\)/, + contains: [ { + begin: /\(/, + end: /\)/, + contains: [ 'self', + { + begin: /\\./ + } ] + } ], + relevance: 10 + }; + + const FUNCTION = { + className: 'keyword', + begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/, + end: /\(/, + excludeEnd: true + }; + + const VARIABLE = { + className: 'variable', + begin: /%[_a-zA-Z0-9:]*/, + end: '%' + }; + + const ESCAPE_SEQUENCE = { + className: 'symbol', + begin: /\\./ + }; + + return { + name: 'Tagger Script', + contains: [ + COMMENT, + FUNCTION, + VARIABLE, + ESCAPE_SEQUENCE + ] + }; +} + +module.exports = taggerscript; + + +/***/ }), + +/***/ 73675: +/***/ ((module) => { + +/* +Language: Test Anything Protocol +Description: TAP, the Test Anything Protocol, is a simple text-based interface between testing modules in a test harness. +Requires: yaml.js +Author: Sergey Bronnikov +Website: https://testanything.org +*/ + +function tap(hljs) { + return { + name: 'Test Anything Protocol', + case_insensitive: true, + contains: [ + hljs.HASH_COMMENT_MODE, + // version of format and total amount of testcases + { + className: 'meta', + variants: [ + { + begin: '^TAP version (\\d+)$' + }, + { + begin: '^1\\.\\.(\\d+)$' + } + ] + }, + // YAML block + { + begin: /---$/, + end: '\\.\\.\\.$', + subLanguage: 'yaml', + relevance: 0 + }, + // testcase number + { + className: 'number', + begin: ' (\\d+) ' + }, + // testcase status and description + { + className: 'symbol', + variants: [ + { + begin: '^ok' + }, + { + begin: '^not ok' + } + ] + } + ] + }; +} + +module.exports = tap; + + +/***/ }), + +/***/ 49717: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/* +Language: Tcl +Description: Tcl is a very simple programming language. +Author: Radek Liska +Website: https://www.tcl.tk/about/language.html +*/ + +function tcl(hljs) { + const TCL_IDENT = /[a-zA-Z_][a-zA-Z0-9_]*/; + + const NUMBER = { + className: 'number', + variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE] + }; + + return { + name: 'Tcl', + aliases: ['tk'], + keywords: 'after append apply array auto_execok auto_import auto_load auto_mkindex ' + + 'auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd chan clock ' + + 'close concat continue dde dict encoding eof error eval exec exit expr fblocked ' + + 'fconfigure fcopy file fileevent filename flush for foreach format gets glob global ' + + 'history http if incr info interp join lappend|10 lassign|10 lindex|10 linsert|10 list ' + + 'llength|10 load lrange|10 lrepeat|10 lreplace|10 lreverse|10 lsearch|10 lset|10 lsort|10 '+ + 'mathfunc mathop memory msgcat namespace open package parray pid pkg::create pkg_mkIndex '+ + 'platform platform::shell proc puts pwd read refchan regexp registry regsub|10 rename '+ + 'return safe scan seek set socket source split string subst switch tcl_endOfWord '+ + 'tcl_findLibrary tcl_startOfNextWord tcl_startOfPreviousWord tcl_wordBreakAfter '+ + 'tcl_wordBreakBefore tcltest tclvars tell time tm trace unknown unload unset update '+ + 'uplevel upvar variable vwait while', + contains: [ + hljs.COMMENT(';[ \\t]*#', '$'), + hljs.COMMENT('^[ \\t]*#', '$'), + { + beginKeywords: 'proc', + end: '[\\{]', + excludeEnd: true, + contains: [ + { + className: 'title', + begin: '[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*', + end: '[ \\t\\n\\r]', + endsWithParent: true, + excludeEnd: true + } + ] + }, + { + className: "variable", + variants: [ + { + begin: concat( + /\$/, + optional(/::/), + TCL_IDENT, + '(::', + TCL_IDENT, + ')*' + ) + }, + { + begin: '\\$\\{(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*', + end: '\\}', + contains: [ + NUMBER + ] + } + ] + }, + { + className: 'string', + contains: [hljs.BACKSLASH_ESCAPE], + variants: [ + hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}) + ] + }, + NUMBER + ] + } +} + +module.exports = tcl; + + +/***/ }), + +/***/ 12287: +/***/ ((module) => { + +/* +Language: Thrift +Author: Oleg Efimov +Description: Thrift message definition format +Website: https://thrift.apache.org +Category: protocols +*/ + +function thrift(hljs) { + const BUILT_IN_TYPES = 'bool byte i16 i32 i64 double string binary'; + return { + name: 'Thrift', + keywords: { + keyword: + 'namespace const typedef struct enum service exception void oneway set list map required optional', + built_in: + BUILT_IN_TYPES, + literal: + 'true false' + }, + contains: [ + hljs.QUOTE_STRING_MODE, + hljs.NUMBER_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'class', + beginKeywords: 'struct enum service exception', + end: /\{/, + illegal: /\n/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + // hack: eating everything after the first title + starts: { + endsWithParent: true, + excludeEnd: true + } + }) + ] + }, + { + begin: '\\b(set|list|map)\\s*<', + end: '>', + keywords: BUILT_IN_TYPES, + contains: [ 'self' ] + } + ] + }; +} + +module.exports = thrift; + + +/***/ }), + +/***/ 6180: +/***/ ((module) => { + +/* +Language: TP +Author: Jay Strybis +Description: FANUC TP programming language (TPP). +*/ + +function tp(hljs) { + const TPID = { + className: 'number', + begin: '[1-9][0-9]*', /* no leading zeros */ + relevance: 0 + }; + const TPLABEL = { + className: 'symbol', + begin: ':[^\\]]+' + }; + const TPDATA = { + className: 'built_in', + begin: '(AR|P|PAYLOAD|PR|R|SR|RSR|LBL|VR|UALM|MESSAGE|UTOOL|UFRAME|TIMER|' + + 'TIMER_OVERFLOW|JOINT_MAX_SPEED|RESUME_PROG|DIAG_REC)\\[', + end: '\\]', + contains: [ + 'self', + TPID, + TPLABEL + ] + }; + const TPIO = { + className: 'built_in', + begin: '(AI|AO|DI|DO|F|RI|RO|UI|UO|GI|GO|SI|SO)\\[', + end: '\\]', + contains: [ + 'self', + TPID, + hljs.QUOTE_STRING_MODE, /* for pos section at bottom */ + TPLABEL + ] + }; + + return { + name: 'TP', + keywords: { + keyword: + 'ABORT ACC ADJUST AND AP_LD BREAK CALL CNT COL CONDITION CONFIG DA DB ' + + 'DIV DETECT ELSE END ENDFOR ERR_NUM ERROR_PROG FINE FOR GP GUARD INC ' + + 'IF JMP LINEAR_MAX_SPEED LOCK MOD MONITOR OFFSET Offset OR OVERRIDE ' + + 'PAUSE PREG PTH RT_LD RUN SELECT SKIP Skip TA TB TO TOOL_OFFSET ' + + 'Tool_Offset UF UT UFRAME_NUM UTOOL_NUM UNLOCK WAIT X Y Z W P R STRLEN ' + + 'SUBSTR FINDSTR VOFFSET PROG ATTR MN POS', + literal: + 'ON OFF max_speed LPOS JPOS ENABLE DISABLE START STOP RESET' + }, + contains: [ + TPDATA, + TPIO, + { + className: 'keyword', + begin: '/(PROG|ATTR|MN|POS|END)\\b' + }, + { + /* this is for cases like ,CALL */ + className: 'keyword', + begin: '(CALL|RUN|POINT_LOGIC|LBL)\\b' + }, + { + /* this is for cases like CNT100 where the default lexemes do not + * separate the keyword and the number */ + className: 'keyword', + begin: '\\b(ACC|CNT|Skip|Offset|PSPD|RT_LD|AP_LD|Tool_Offset)' + }, + { + /* to catch numbers that do not have a word boundary on the left */ + className: 'number', + begin: '\\d+(sec|msec|mm/sec|cm/min|inch/min|deg/sec|mm|in|cm)?\\b', + relevance: 0 + }, + hljs.COMMENT('//', '[;$]'), + hljs.COMMENT('!', '[;$]'), + hljs.COMMENT('--eg:', '$'), + hljs.QUOTE_STRING_MODE, + { + className: 'string', + begin: '\'', + end: '\'' + }, + hljs.C_NUMBER_MODE, + { + className: 'variable', + begin: '\\$[A-Za-z0-9_]+' + } + ] + }; +} + +module.exports = tp; + + +/***/ }), + +/***/ 53201: +/***/ ((module) => { + +/* +Language: Twig +Requires: xml.js +Author: Luke Holder +Description: Twig is a templating language for PHP +Website: https://twig.symfony.com +Category: template +*/ + +function twig(hljs) { + var PARAMS = { + className: 'params', + begin: '\\(', end: '\\)' + }; + + var FUNCTION_NAMES = 'attribute block constant cycle date dump include ' + + 'max min parent random range source template_from_string'; + + var FUNCTIONS = { + beginKeywords: FUNCTION_NAMES, + keywords: {name: FUNCTION_NAMES}, + relevance: 0, + contains: [ + PARAMS + ] + }; + + var FILTER = { + begin: /\|[A-Za-z_]+:?/, + keywords: + 'abs batch capitalize column convert_encoding date date_modify default ' + + 'escape filter first format inky_to_html inline_css join json_encode keys last ' + + 'length lower map markdown merge nl2br number_format raw reduce replace ' + + 'reverse round slice sort spaceless split striptags title trim upper url_encode', + contains: [ + FUNCTIONS + ] + }; + + var TAGS = 'apply autoescape block deprecated do embed extends filter flush for from ' + + 'if import include macro sandbox set use verbatim with'; + + TAGS = TAGS + ' ' + TAGS.split(' ').map(function(t){return 'end' + t}).join(' '); + + return { + name: 'Twig', + aliases: ['craftcms'], + case_insensitive: true, + subLanguage: 'xml', + contains: [ + hljs.COMMENT(/\{#/, /#\}/), + { + className: 'template-tag', + begin: /\{%/, end: /%\}/, + contains: [ + { + className: 'name', + begin: /\w+/, + keywords: TAGS, + starts: { + endsWithParent: true, + contains: [FILTER, FUNCTIONS], + relevance: 0 + } + } + ] + }, + { + className: 'template-variable', + begin: /\{\{/, end: /\}\}/, + contains: ['self', FILTER, FUNCTIONS] + } + ] + }; +} + +module.exports = twig; + + +/***/ }), + +/***/ 89938: +/***/ ((module) => { + +/* +Language: Vala +Author: Antono Vasiljev +Description: Vala is a new programming language that aims to bring modern programming language features to GNOME developers without imposing any additional runtime requirements and without using a different ABI compared to applications and libraries written in C. +Website: https://wiki.gnome.org/Projects/Vala +*/ + +function vala(hljs) { + return { + name: 'Vala', + keywords: { + keyword: + // Value types + 'char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 ' + + 'uint16 uint32 uint64 float double bool struct enum string void ' + + // Reference types + 'weak unowned owned ' + + // Modifiers + 'async signal static abstract interface override virtual delegate ' + + // Control Structures + 'if while do for foreach else switch case break default return try catch ' + + // Visibility + 'public private protected internal ' + + // Other + 'using new this get set const stdout stdin stderr var', + built_in: + 'DBus GLib CCode Gee Object Gtk Posix', + literal: + 'false true null' + }, + contains: [ + { + className: 'class', + beginKeywords: 'class interface namespace', + end: /\{/, + excludeEnd: true, + illegal: '[^,:\\n\\s\\.]', + contains: [ hljs.UNDERSCORE_TITLE_MODE ] + }, + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + { + className: 'string', + begin: '"""', + end: '"""', + relevance: 5 + }, + hljs.APOS_STRING_MODE, + hljs.QUOTE_STRING_MODE, + hljs.C_NUMBER_MODE, + { + className: 'meta', + begin: '^#', + end: '$', + relevance: 2 + } + ] + }; +} + +module.exports = vala; + + +/***/ }), + +/***/ 76053: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: Visual Basic .NET +Description: Visual Basic .NET (VB.NET) is a multi-paradigm, object-oriented programming language, implemented on the .NET Framework. +Authors: Poren Chiang , Jan Pilzer +Website: https://docs.microsoft.com/dotnet/visual-basic/getting-started +Category: common +*/ + +/** @type LanguageFn */ +function vbnet(hljs) { + /** + * Character Literal + * Either a single character ("a"C) or an escaped double quote (""""C). + */ + const CHARACTER = { + className: 'string', + begin: /"(""|[^/n])"C\b/ + }; + + const STRING = { + className: 'string', + begin: /"/, + end: /"/, + illegal: /\n/, + contains: [ + { + // double quote escape + begin: /""/ + } + ] + }; + + /** Date Literals consist of a date, a time, or both separated by whitespace, surrounded by # */ + const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/; + const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/; + const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/; + const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/; + const DATE = { + className: 'literal', + variants: [ + { + // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date) + begin: concat(/# */, either(YYYY_MM_DD, MM_DD_YYYY), / *#/) + }, + { + // #H:mm[:ss]# (24h Time) + begin: concat(/# */, TIME_24H, / *#/) + }, + { + // #h[:mm[:ss]] A# (12h Time) + begin: concat(/# */, TIME_12H, / *#/) + }, + { + // date plus time + begin: concat( + /# */, + either(YYYY_MM_DD, MM_DD_YYYY), + / +/, + either(TIME_12H, TIME_24H), + / *#/ + ) + } + ] + }; + + const NUMBER = { + className: 'number', + relevance: 0, + variants: [ + { + // Float + begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/ + }, + { + // Integer (base 10) + begin: /\b\d[\d_]*((U?[SIL])|[%&])?/ + }, + { + // Integer (base 16) + begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/ + }, + { + // Integer (base 8) + begin: /&O[0-7_]+((U?[SIL])|[%&])?/ + }, + { + // Integer (base 2) + begin: /&B[01_]+((U?[SIL])|[%&])?/ + } + ] + }; + + const LABEL = { + className: 'label', + begin: /^\w+:/ + }; + + const DOC_COMMENT = hljs.COMMENT(/'''/, /$/, { + contains: [ + { + className: 'doctag', + begin: /<\/?/, + end: />/ + } + ] + }); + + const COMMENT = hljs.COMMENT(null, /$/, { + variants: [ + { + begin: /'/ + }, + { + // TODO: Use `beforeMatch:` for leading spaces + begin: /([\t ]|^)REM(?=\s)/ + } + ] + }); + + const DIRECTIVES = { + className: 'meta', + // TODO: Use `beforeMatch:` for indentation once available + begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/, + end: /$/, + keywords: { + 'meta-keyword': + 'const disable else elseif enable end externalsource if region then' + }, + contains: [ COMMENT ] + }; + + return { + name: 'Visual Basic .NET', + aliases: [ 'vb' ], + case_insensitive: true, + classNameAliases: { + label: 'symbol' + }, + keywords: { + keyword: + 'addhandler alias aggregate ansi as async assembly auto binary by byref byval ' + /* a-b */ + 'call case catch class compare const continue custom declare default delegate dim distinct do ' + /* c-d */ + 'each equals else elseif end enum erase error event exit explicit finally for friend from function ' + /* e-f */ + 'get global goto group handles if implements imports in inherits interface into iterator ' + /* g-i */ + 'join key let lib loop me mid module mustinherit mustoverride mybase myclass ' + /* j-m */ + 'namespace narrowing new next notinheritable notoverridable ' + /* n */ + 'of off on operator option optional order overloads overridable overrides ' + /* o */ + 'paramarray partial preserve private property protected public ' + /* p */ + 'raiseevent readonly redim removehandler resume return ' + /* r */ + 'select set shadows shared skip static step stop structure strict sub synclock ' + /* s */ + 'take text then throw to try unicode until using when where while widening with withevents writeonly yield' /* t-y */, + built_in: + // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators + 'addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor ' + + // Type Conversion Functions https://docs.microsoft.com/dotnet/visual-basic/language-reference/functions/type-conversion-functions + 'cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort', + type: + // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types + 'boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort', + literal: 'true false nothing' + }, + illegal: + '//|\\{|\\}|endif|gosub|variant|wend|^\\$ ' /* reserved deprecated keywords */, + contains: [ + CHARACTER, + STRING, + DATE, + NUMBER, + LABEL, + DOC_COMMENT, + COMMENT, + DIRECTIVES + ] + }; +} + +module.exports = vbnet; + + +/***/ }), + +/***/ 97589: +/***/ ((module) => { + +/* +Language: VBScript in HTML +Requires: xml.js, vbscript.js +Author: Ivan Sagalaev +Description: "Bridge" language defining fragments of VBScript in HTML within <% .. %> +Website: https://en.wikipedia.org/wiki/VBScript +Category: scripting +*/ + +function vbscriptHtml(hljs) { + return { + name: 'VBScript in HTML', + subLanguage: 'xml', + contains: [ + { + begin: '<%', + end: '%>', + subLanguage: 'vbscript' + } + ] + }; +} + +module.exports = vbscriptHtml; + + +/***/ }), + +/***/ 38111: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: VBScript +Description: VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. +Author: Nikita Ledyaev +Contributors: Michal Gabrukiewicz +Website: https://en.wikipedia.org/wiki/VBScript +Category: scripting +*/ + +/** @type LanguageFn */ +function vbscript(hljs) { + const BUILT_IN_FUNCTIONS = ('lcase month vartype instrrev ubound setlocale getobject rgb getref string ' + + 'weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency ' + + 'conversions csng timevalue second year space abs clng timeserial fixs len asc ' + + 'isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate ' + + 'instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex ' + + 'chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim ' + + 'strcomp int createobject loadpicture tan formatnumber mid ' + + 'split cint sin datepart ltrim sqr ' + + 'time derived eval date formatpercent exp inputbox left ascw ' + + 'chrw regexp cstr err').split(" "); + const BUILT_IN_OBJECTS = [ + "server", + "response", + "request", + // take no arguments so can be called without () + "scriptengine", + "scriptenginebuildversion", + "scriptengineminorversion", + "scriptenginemajorversion" + ]; + + const BUILT_IN_CALL = { + begin: concat(either(...BUILT_IN_FUNCTIONS), "\\s*\\("), + // relevance 0 because this is acting as a beginKeywords really + relevance:0, + keywords: { + built_in: BUILT_IN_FUNCTIONS + } + }; + + return { + name: 'VBScript', + aliases: ['vbs'], + case_insensitive: true, + keywords: { + keyword: + 'call class const dim do loop erase execute executeglobal exit for each next function ' + + 'if then else on error option explicit new private property let get public randomize ' + + 'redim rem select case set stop sub while wend with end to elseif is or xor and not ' + + 'class_initialize class_terminate default preserve in me byval byref step resume goto', + built_in: BUILT_IN_OBJECTS, + literal: + 'true false null nothing empty' + }, + illegal: '//', + contains: [ + BUILT_IN_CALL, + hljs.inherit(hljs.QUOTE_STRING_MODE, {contains: [{begin: '""'}]}), + hljs.COMMENT( + /'/, + /$/, + { + relevance: 0 + } + ), + hljs.C_NUMBER_MODE + ] + }; +} + +module.exports = vbscript; + + +/***/ }), + +/***/ 53508: +/***/ ((module) => { + +/* +Language: Verilog +Author: Jon Evans +Contributors: Boone Severson +Description: Verilog is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. This highlighter supports Verilog and SystemVerilog through IEEE 1800-2012. +Website: http://www.verilog.com +*/ + +function verilog(hljs) { + const SV_KEYWORDS = { + $pattern: /[\w\$]+/, + keyword: + 'accept_on alias always always_comb always_ff always_latch and assert assign ' + + 'assume automatic before begin bind bins binsof bit break buf|0 bufif0 bufif1 ' + + 'byte case casex casez cell chandle checker class clocking cmos config const ' + + 'constraint context continue cover covergroup coverpoint cross deassign default ' + + 'defparam design disable dist do edge else end endcase endchecker endclass ' + + 'endclocking endconfig endfunction endgenerate endgroup endinterface endmodule ' + + 'endpackage endprimitive endprogram endproperty endspecify endsequence endtable ' + + 'endtask enum event eventually expect export extends extern final first_match for ' + + 'force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 ' + + 'if iff ifnone ignore_bins illegal_bins implements implies import incdir include ' + + 'initial inout input inside instance int integer interconnect interface intersect ' + + 'join join_any join_none large let liblist library local localparam logic longint ' + + 'macromodule matches medium modport module nand negedge nettype new nexttime nmos ' + + 'nor noshowcancelled not notif0 notif1 or output package packed parameter pmos ' + + 'posedge primitive priority program property protected pull0 pull1 pulldown pullup ' + + 'pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos ' + + 'real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran ' + + 'rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared ' + + 'sequence shortint shortreal showcancelled signed small soft solve specify specparam ' + + 'static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on ' + + 'sync_reject_on table tagged task this throughout time timeprecision timeunit tran ' + + 'tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 ' + + 'unsigned until until_with untyped use uwire var vectored virtual void wait wait_order ' + + 'wand weak weak0 weak1 while wildcard wire with within wor xnor xor', + literal: + 'null', + built_in: + '$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale ' + + '$bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat ' + + '$realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson ' + + '$assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff ' + + '$assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk ' + + '$fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control ' + + '$coverage_get $coverage_save $set_coverage_db_name $rose $stable $past ' + + '$rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk $display ' + + '$coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename ' + + '$unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow ' + + '$floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning ' + + '$dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh ' + + '$tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random ' + + '$dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson ' + + '$dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array ' + + '$async$nand$array $async$or$array $async$nor$array $sync$and$array ' + + '$sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full $psprintf ' + + '$async$and$plane $async$nand$plane $async$or$plane $async$nor$plane ' + + '$sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system ' + + '$display $displayb $displayh $displayo $strobe $strobeb $strobeh $strobeo ' + + '$write $readmemb $readmemh $writememh $value$plusargs ' + + '$dumpvars $dumpon $dumplimit $dumpports $dumpportson $dumpportslimit ' + + '$writeb $writeh $writeo $monitor $monitorb $monitorh $monitoro $writememb ' + + '$dumpfile $dumpoff $dumpall $dumpflush $dumpportsoff $dumpportsall ' + + '$dumpportsflush $fclose $fdisplay $fdisplayb $fdisplayh $fdisplayo ' + + '$fstrobe $fstrobeb $fstrobeh $fstrobeo $swrite $swriteb $swriteh ' + + '$swriteo $fscanf $fread $fseek $fflush $feof $fopen $fwrite $fwriteb ' + + '$fwriteh $fwriteo $fmonitor $fmonitorb $fmonitorh $fmonitoro $sformat ' + + '$sformatf $fgetc $ungetc $fgets $sscanf $rewind $ftell $ferror' + }; + + return { + name: 'Verilog', + aliases: [ + 'v', + 'sv', + 'svh' + ], + case_insensitive: false, + keywords: SV_KEYWORDS, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, + hljs.C_LINE_COMMENT_MODE, + hljs.QUOTE_STRING_MODE, + { + className: 'number', + contains: [ hljs.BACKSLASH_ESCAPE ], + variants: [ + { + begin: '\\b((\\d+\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)' + }, + { + begin: '\\B((\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)' + }, + { + begin: '\\b([0-9_])+', + relevance: 0 + } + ] + }, + /* parameters to instances */ + { + className: 'variable', + variants: [ + { + begin: '#\\((?!parameter).+\\)' + }, + { + begin: '\\.\\w+', + relevance: 0 + } + ] + }, + { + className: 'meta', + begin: '`', + end: '$', + keywords: { + 'meta-keyword': + 'define __FILE__ ' + + '__LINE__ begin_keywords celldefine default_nettype define ' + + 'else elsif end_keywords endcelldefine endif ifdef ifndef ' + + 'include line nounconnected_drive pragma resetall timescale ' + + 'unconnected_drive undef undefineall' + }, + relevance: 0 + } + ] + }; +} + +module.exports = verilog; + + +/***/ }), + +/***/ 60326: +/***/ ((module) => { + +/* +Language: VHDL +Author: Igor Kalnitsky +Contributors: Daniel C.K. Kho , Guillaume Savaton +Description: VHDL is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. +Website: https://en.wikipedia.org/wiki/VHDL +*/ + +function vhdl(hljs) { + // Regular expression for VHDL numeric literals. + + // Decimal literal: + const INTEGER_RE = '\\d(_|\\d)*'; + const EXPONENT_RE = '[eE][-+]?' + INTEGER_RE; + const DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?'; + // Based literal: + const BASED_INTEGER_RE = '\\w+'; + const BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?'; + + const NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')'; + + return { + name: 'VHDL', + case_insensitive: true, + keywords: { + keyword: + 'abs access after alias all and architecture array assert assume assume_guarantee attribute ' + + 'begin block body buffer bus case component configuration constant context cover disconnect ' + + 'downto default else elsif end entity exit fairness file for force function generate ' + + 'generic group guarded if impure in inertial inout is label library linkage literal ' + + 'loop map mod nand new next nor not null of on open or others out package parameter port ' + + 'postponed procedure process property protected pure range record register reject ' + + 'release rem report restrict restrict_guarantee return rol ror select sequence ' + + 'severity shared signal sla sll sra srl strong subtype then to transport type ' + + 'unaffected units until use variable view vmode vprop vunit wait when while with xnor xor', + built_in: + 'boolean bit character ' + + 'integer time delay_length natural positive ' + + 'string bit_vector file_open_kind file_open_status ' + + 'std_logic std_logic_vector unsigned signed boolean_vector integer_vector ' + + 'std_ulogic std_ulogic_vector unresolved_unsigned u_unsigned unresolved_signed u_signed ' + + 'real_vector time_vector', + literal: + 'false true note warning error failure ' + // severity_level + 'line text side width' // textio + }, + illegal: /\{/, + contains: [ + hljs.C_BLOCK_COMMENT_MODE, // VHDL-2008 block commenting. + hljs.COMMENT('--', '$'), + hljs.QUOTE_STRING_MODE, + { + className: 'number', + begin: NUMBER_RE, + relevance: 0 + }, + { + className: 'string', + begin: '\'(U|X|0|1|Z|W|L|H|-)\'', + contains: [ hljs.BACKSLASH_ESCAPE ] + }, + { + className: 'symbol', + begin: '\'[A-Za-z](_?[A-Za-z0-9])*', + contains: [ hljs.BACKSLASH_ESCAPE ] + } + ] + }; +} + +module.exports = vhdl; + + +/***/ }), + +/***/ 33510: +/***/ ((module) => { + +/* +Language: Vim Script +Author: Jun Yang +Description: full keyword and built-in from http://vimdoc.sourceforge.net/htmldoc/ +Website: https://www.vim.org +Category: scripting +*/ + +function vim(hljs) { + return { + name: 'Vim Script', + keywords: { + $pattern: /[!#@\w]+/, + keyword: + // express version except: ! & * < = > !! # @ @@ + 'N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope ' + + 'cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ' + + 'ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 ' + + 'profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor ' + + 'so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew ' + + 'tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ ' + + // full version + 'Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload ' + + 'bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap ' + + 'cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor ' + + 'endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap ' + + 'imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview ' + + 'lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap ' + + 'nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ' + + 'ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding ' + + 'scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace ' + + 'startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious ' + 'trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew ' + + 'vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank', + built_in: // built in func + 'synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv ' + + 'complete_check add getwinposx getqflist getwinposy screencol ' + + 'clearmatches empty extend getcmdpos mzeval garbagecollect setreg ' + + 'ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable ' + + 'shiftwidth max sinh isdirectory synID system inputrestore winline ' + + 'atan visualmode inputlist tabpagewinnr round getregtype mapcheck ' + + 'hasmapto histdel argidx findfile sha256 exists toupper getcmdline ' + + 'taglist string getmatches bufnr strftime winwidth bufexists ' + + 'strtrans tabpagebuflist setcmdpos remote_read printf setloclist ' + + 'getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval ' + + 'resolve libcallnr foldclosedend reverse filter has_key bufname ' + + 'str2float strlen setline getcharmod setbufvar index searchpos ' + + 'shellescape undofile foldclosed setqflist buflisted strchars str2nr ' + + 'virtcol floor remove undotree remote_expr winheight gettabwinvar ' + + 'reltime cursor tabpagenr finddir localtime acos getloclist search ' + + 'tanh matchend rename gettabvar strdisplaywidth type abs py3eval ' + + 'setwinvar tolower wildmenumode log10 spellsuggest bufloaded ' + + 'synconcealed nextnonblank server2client complete settabwinvar ' + + 'executable input wincol setmatches getftype hlID inputsave ' + + 'searchpair or screenrow line settabvar histadd deepcopy strpart ' + + 'remote_peek and eval getftime submatch screenchar winsaveview ' + + 'matchadd mkdir screenattr getfontname libcall reltimestr getfsize ' + + 'winnr invert pow getbufline byte2line soundfold repeat fnameescape ' + + 'tagfiles sin strwidth spellbadword trunc maparg log lispindent ' + + 'hostname setpos globpath remote_foreground getchar synIDattr ' + + 'fnamemodify cscope_connection stridx winbufnr indent min ' + + 'complete_add nr2char searchpairpos inputdialog values matchlist ' + + 'items hlexists strridx browsedir expand fmod pathshorten line2byte ' + + 'argc count getwinvar glob foldtextresult getreg foreground cosh ' + + 'matchdelete has char2nr simplify histget searchdecl iconv ' + + 'winrestcmd pumvisible writefile foldlevel haslocaldir keys cos ' + + 'matchstr foldtext histnr tan tempname getcwd byteidx getbufvar ' + + 'islocked escape eventhandler remote_send serverlist winrestview ' + + 'synstack pyeval prevnonblank readfile cindent filereadable changenr ' + + 'exp' + }, + illegal: /;/, + contains: [ + hljs.NUMBER_MODE, + { + className: 'string', + begin: '\'', + end: '\'', + illegal: '\\n' + }, + + /* + A double quote can start either a string or a line comment. Strings are + ended before the end of a line by another double quote and can contain + escaped double-quotes and post-escaped line breaks. + + Also, any double quote at the beginning of a line is a comment but we + don't handle that properly at the moment: any double quote inside will + turn them into a string. Handling it properly will require a smarter + parser. + */ + { + className: 'string', + begin: /"(\\"|\n\\|[^"\n])*"/ + }, + hljs.COMMENT('"', '$'), + + { + className: 'variable', + begin: /[bwtglsav]:[\w\d_]*/ + }, + { + className: 'function', + beginKeywords: 'function function!', + end: '$', + relevance: 0, + contains: [ + hljs.TITLE_MODE, + { + className: 'params', + begin: '\\(', + end: '\\)' + } + ] + }, + { + className: 'symbol', + begin: /<[\w-]+>/ + } + ] + }; +} + +module.exports = vim; + + +/***/ }), + +/***/ 19085: +/***/ ((module) => { + +/* +Language: Intel x86 Assembly +Author: innocenat +Description: x86 assembly language using Intel's mnemonic and NASM syntax +Website: https://en.wikipedia.org/wiki/X86_assembly_language +Category: assembler +*/ + +function x86asm(hljs) { + return { + name: 'Intel x86 Assembly', + case_insensitive: true, + keywords: { + $pattern: '[.%]?' + hljs.IDENT_RE, + keyword: + 'lock rep repe repz repne repnz xaquire xrelease bnd nobnd ' + + 'aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63', + built_in: + // Instruction pointer + 'ip eip rip ' + + // 8-bit registers + 'al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ' + + // 16-bit registers + 'ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w ' + + // 32-bit registers + 'eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d ' + + // 64-bit registers + 'rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 ' + + // Segment registers + 'cs ds es fs gs ss ' + + // Floating point stack registers + 'st st0 st1 st2 st3 st4 st5 st6 st7 ' + + // MMX Registers + 'mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 ' + + // SSE registers + 'xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 ' + + 'xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ' + + // AVX registers + 'ymm0 ymm1 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9 ymm10 ymm11 ymm12 ymm13 ymm14 ymm15 ' + + 'ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 ' + + // AVX-512F registers + 'zmm0 zmm1 zmm2 zmm3 zmm4 zmm5 zmm6 zmm7 zmm8 zmm9 zmm10 zmm11 zmm12 zmm13 zmm14 zmm15 ' + + 'zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 ' + + // AVX-512F mask registers + 'k0 k1 k2 k3 k4 k5 k6 k7 ' + + // Bound (MPX) register + 'bnd0 bnd1 bnd2 bnd3 ' + + // Special register + 'cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 ' + + // NASM altreg package + 'r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b ' + + 'r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d ' + + 'r0h r1h r2h r3h ' + + 'r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l ' + + + 'db dw dd dq dt ddq do dy dz ' + + 'resb resw resd resq rest resdq reso resy resz ' + + 'incbin equ times ' + + 'byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr', + + meta: + '%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif ' + + '%if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep ' + + '%endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment ' + + '.nolist ' + + '__FILE__ __LINE__ __SECT__ __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ ' + + '__UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__ __PASS__ struc endstruc istruc at iend ' + + 'align alignb sectalign daz nodaz up down zero default option assume public ' + + + 'bits use16 use32 use64 default section segment absolute extern global common cpu float ' + + '__utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ ' + + '__float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ ' + + '__Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e ' + + 'float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__' + }, + contains: [ + hljs.COMMENT( + ';', + '$', + { + relevance: 0 + } + ), + { + className: 'number', + variants: [ + // Float number and x87 BCD + { + begin: '\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|' + + '(0[Xx])?[0-9][0-9_]*(\\.[0-9_]*)?(?:[pP](?:[+-]?[0-9_]+)?)?)\\b', + relevance: 0 + }, + + // Hex number in $ + { + begin: '\\$[0-9][0-9A-Fa-f]*', + relevance: 0 + }, + + // Number in H,D,T,Q,O,B,Y suffix + { + begin: '\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b' + }, + + // Number in X,D,T,Q,O,B,Y prefix + { + begin: '\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b' + } + ] + }, + // Double quote string + hljs.QUOTE_STRING_MODE, + { + className: 'string', + variants: [ + // Single-quoted string + { + begin: '\'', + end: '[^\\\\]\'' + }, + // Backquoted string + { + begin: '`', + end: '[^\\\\]`' + } + ], + relevance: 0 + }, + { + className: 'symbol', + variants: [ + // Global label and local label + { + begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)' + }, + // Macro-local label + { + begin: '^\\s*%%[A-Za-z0-9_$#@~.?]*:' + } + ], + relevance: 0 + }, + // Macro parameter + { + className: 'subst', + begin: '%[0-9]+', + relevance: 0 + }, + // Macro parameter + { + className: 'subst', + begin: '%!\S+', + relevance: 0 + }, + { + className: 'meta', + begin: /^\s*\.[\w_-]+/ + } + ] + }; +} + +module.exports = x86asm; + + +/***/ }), + +/***/ 85852: +/***/ ((module) => { + +/* +Language: XL +Author: Christophe de Dinechin +Description: An extensible programming language, based on parse tree rewriting +Website: http://xlr.sf.net +*/ + +function xl(hljs) { + const BUILTIN_MODULES = + 'ObjectLoader Animate MovieCredits Slides Filters Shading Materials LensFlare Mapping VLCAudioVideo ' + + 'StereoDecoder PointCloud NetworkAccess RemoteControl RegExp ChromaKey Snowfall NodeJS Speech Charts'; + + const XL_KEYWORDS = { + $pattern: /[a-zA-Z][a-zA-Z0-9_?]*/, + keyword: + 'if then else do while until for loop import with is as where when by data constant ' + + 'integer real text name boolean symbol infix prefix postfix block tree', + literal: + 'true false nil', + built_in: + 'in mod rem and or xor not abs sign floor ceil sqrt sin cos tan asin ' + + 'acos atan exp expm1 log log2 log10 log1p pi at text_length text_range ' + + 'text_find text_replace contains page slide basic_slide title_slide ' + + 'title subtitle fade_in fade_out fade_at clear_color color line_color ' + + 'line_width texture_wrap texture_transform texture scale_?x scale_?y ' + + 'scale_?z? translate_?x translate_?y translate_?z? rotate_?x rotate_?y ' + + 'rotate_?z? rectangle circle ellipse sphere path line_to move_to ' + + 'quad_to curve_to theme background contents locally time mouse_?x ' + + 'mouse_?y mouse_buttons ' + + BUILTIN_MODULES + }; + + const DOUBLE_QUOTE_TEXT = { + className: 'string', + begin: '"', + end: '"', + illegal: '\\n' + }; + const SINGLE_QUOTE_TEXT = { + className: 'string', + begin: '\'', + end: '\'', + illegal: '\\n' + }; + const LONG_TEXT = { + className: 'string', + begin: '<<', + end: '>>' + }; + const BASED_NUMBER = { + className: 'number', + begin: '[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?' + }; + const IMPORT = { + beginKeywords: 'import', + end: '$', + keywords: XL_KEYWORDS, + contains: [ DOUBLE_QUOTE_TEXT ] + }; + const FUNCTION_DEFINITION = { + className: 'function', + begin: /[a-z][^\n]*->/, + returnBegin: true, + end: /->/, + contains: [ + hljs.inherit(hljs.TITLE_MODE, { + starts: { + endsWithParent: true, + keywords: XL_KEYWORDS + } + }) + ] + }; + return { + name: 'XL', + aliases: [ 'tao' ], + keywords: XL_KEYWORDS, + contains: [ + hljs.C_LINE_COMMENT_MODE, + hljs.C_BLOCK_COMMENT_MODE, + DOUBLE_QUOTE_TEXT, + SINGLE_QUOTE_TEXT, + LONG_TEXT, + FUNCTION_DEFINITION, + IMPORT, + BASED_NUMBER, + hljs.NUMBER_MODE + ] + }; +} + +module.exports = xl; + + +/***/ }), + +/***/ 95327: +/***/ ((module) => { + +/** + * @param {string} value + * @returns {RegExp} + * */ + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function source(re) { + if (!re) return null; + if (typeof re === "string") return re; + + return re.source; +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function lookahead(re) { + return concat('(?=', re, ')'); +} + +/** + * @param {RegExp | string } re + * @returns {string} + */ +function optional(re) { + return concat('(', re, ')?'); +} + +/** + * @param {...(RegExp | string) } args + * @returns {string} + */ +function concat(...args) { + const joined = args.map((x) => source(x)).join(""); + return joined; +} + +/** + * Any of the passed expresssions may match + * + * Creates a huge this | this | that | that match + * @param {(RegExp | string)[] } args + * @returns {string} + */ +function either(...args) { + const joined = '(' + args.map((x) => source(x)).join("|") + ")"; + return joined; +} + +/* +Language: HTML, XML +Website: https://www.w3.org/XML/ +Category: common +Audit: 2020 +*/ + +/** @type LanguageFn */ +function xml(hljs) { + // Element names can contain letters, digits, hyphens, underscores, and periods + const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/); + const XML_IDENT_RE = /[A-Za-z0-9._:-]+/; + const XML_ENTITIES = { + className: 'symbol', + begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/ + }; + const XML_META_KEYWORDS = { + begin: /\s/, + contains: [ + { + className: 'meta-keyword', + begin: /#?[a-z_][a-z1-9_-]+/, + illegal: /\n/ + } + ] + }; + const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, { + begin: /\(/, + end: /\)/ + }); + const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { + className: 'meta-string' + }); + const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { + className: 'meta-string' + }); + const TAG_INTERNALS = { + endsWithParent: true, + illegal: /`]+/ + } + ] + } + ] + } + ] + }; + return { + name: 'HTML, XML', + aliases: [ + 'html', + 'xhtml', + 'rss', + 'atom', + 'xjb', + 'xsd', + 'xsl', + 'plist', + 'wsf', + 'svg' + ], + case_insensitive: true, + contains: [ + { + className: 'meta', + begin: //, + relevance: 10, + contains: [ + XML_META_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE, + XML_META_PAR_KEYWORDS, + { + begin: /\[/, + end: /\]/, + contains: [ + { + className: 'meta', + begin: //, + contains: [ + XML_META_KEYWORDS, + XML_META_PAR_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE + ] + } + ] + } + ] + }, + hljs.COMMENT( + //, + { + relevance: 10 + } + ), + { + begin: //, + relevance: 10 + }, + XML_ENTITIES, + { + className: 'meta', + begin: /<\?xml/, + end: /\?>/, + relevance: 10 + }, + { + className: 'tag', + /* + The lookahead pattern (?=...) ensures that 'begin' only matches + ')/, + end: />/, + keywords: { + name: 'style' + }, + contains: [ TAG_INTERNALS ], + starts: { + end: /<\/style>/, + returnEnd: true, + subLanguage: [ + 'css', + 'xml' + ] + } + }, + { + className: 'tag', + // See the comment in the